ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / cdrom / cdu31a.c
1 /*
2 * Sony CDU-31A CDROM interface device driver.
3 *
4 * Corey Minyard (minyard@wf-rch.cirr.com)
5 *
6 * Colossians 3:17
7 *
8 *  See Documentation/cdrom/cdu31a for additional details about this driver.
9
10 * The Sony interface device driver handles Sony interface CDROM
11 * drives and provides a complete block-level interface as well as an
12 * ioctl() interface compatible with the Sun (as specified in
13 * include/linux/cdrom.h).  With this interface, CDROMs can be
14 * accessed and standard audio CDs can be played back normally.
15 *
16 * WARNING -     All autoprobes have been removed from the driver.
17 *               You MUST configure the CDU31A via a LILO config
18 *               at boot time or in lilo.conf.  I have the
19 *               following in my lilo.conf:
20 *
21 *                append="cdu31a=0x1f88,0,PAS"
22 *
23 *               The first number is the I/O base address of the
24 *               card.  The second is the interrupt (0 means none).
25  *              The third should be "PAS" if on a Pro-Audio
26  *              spectrum, or nothing if on something else.
27  *
28  * This interface is (unfortunately) a polled interface.  This is
29  * because most Sony interfaces are set up with DMA and interrupts
30  * disables.  Some (like mine) do not even have the capability to
31  * handle interrupts or DMA.  For this reason you will see a lot of
32  * the following:
33  *
34  *   retry_count = jiffies+ SONY_JIFFIES_TIMEOUT;
35  *   while (time_before(jiffies, retry_count) && (! <some condition to wait for))
36  *   {
37  *      while (handle_sony_cd_attention())
38  *         ;
39  *
40  *      sony_sleep();
41  *   }
42  *   if (the condition not met)
43  *   {
44  *      return an error;
45  *   }
46  *
47  * This ugly hack waits for something to happen, sleeping a little
48  * between every try.  it also handles attentions, which are
49  * asynchronous events from the drive informing the driver that a disk
50  * has been inserted, removed, etc.
51  *
52  * NEWS FLASH - The driver now supports interrupts but they are
53  * turned off by default.  Use of interrupts is highly encouraged, it
54  * cuts CPU usage down to a reasonable level.  I had DMA in for a while
55  * but PC DMA is just too slow.  Better to just insb() it.
56  *
57  * One thing about these drives: They talk in MSF (Minute Second Frame) format.
58  * There are 75 frames a second, 60 seconds a minute, and up to 75 minutes on a
59  * disk.  The funny thing is that these are sent to the drive in BCD, but the
60  * interface wants to see them in decimal.  A lot of conversion goes on.
61  *
62  * DRIVER SPECIAL FEATURES
63  * -----------------------
64  *
65  * This section describes features beyond the normal audio and CD-ROM
66  * functions of the drive.
67  *
68  * 2048 byte buffer mode
69  *
70  * If a disk is mounted with -o block=2048, data is copied straight
71  * from the drive data port to the buffer.  Otherwise, the readahead
72  * buffer must be involved to hold the other 1K of data when a 1K
73  * block operation is done.  Note that with 2048 byte blocks you
74  * cannot execute files from the CD.
75  *
76  * XA compatibility
77  *
78  * The driver should support XA disks for both the CDU31A and CDU33A.
79  * It does this transparently, the using program doesn't need to set it.
80  *
81  * Multi-Session
82  *
83  * A multi-session disk looks just like a normal disk to the user.
84  * Just mount one normally, and all the data should be there.
85  * A special thanks to Koen for help with this!
86  * 
87  * Raw sector I/O
88  *
89  * Using the CDROMREADAUDIO it is possible to read raw audio and data
90  * tracks.  Both operations return 2352 bytes per sector.  On the data
91  * tracks, the first 12 bytes is not returned by the drive and the value
92  * of that data is indeterminate.
93  *
94  *
95  *  Copyright (C) 1993  Corey Minyard
96  *
97  *  This program is free software; you can redistribute it and/or modify
98  *  it under the terms of the GNU General Public License as published by
99  *  the Free Software Foundation; either version 2 of the License, or
100  *  (at your option) any later version.
101  *
102  *  This program is distributed in the hope that it will be useful,
103  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
104  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
105  *  GNU General Public License for more details.
106  *
107  *  You should have received a copy of the GNU General Public License
108  *  along with this program; if not, write to the Free Software
109  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
110  *
111  * TODO: 
112  *       CDs with form1 and form2 sectors cause problems
113  *       with current read-ahead strategy.
114  *
115  * Credits:
116  *    Heiko Eissfeldt <heiko@colossus.escape.de>
117  *         For finding abug in the return of the track numbers.
118  *         TOC processing redone for proper multisession support.
119  *
120  *
121  *  It probably a little late to be adding a history, but I guess I
122  *  will start.
123  *
124  *  10/24/95 - Added support for disabling the eject button when the
125  *             drive is open.  Note that there is a small problem
126  *             still here, if the eject button is pushed while the
127  *             drive light is flashing, the drive will return a bad
128  *             status and be reset.  It recovers, though.
129  *
130  *  03/07/97 - Fixed a problem with timers.
131  *
132  *
133  *  18 Spetember 1997 -- Ported to Uniform CD-ROM driver by 
134  *                 Heiko Eissfeldt <heiko@colossus.escape.de> with additional
135  *                 changes by Erik Andersen <andersee@debian.org>
136  *
137  *  24 January 1998 -- Removed the scd_disc_status() function, which was now
138  *                     just dead code left over from the port.
139  *                          Erik Andersen <andersee@debian.org>
140  *
141  *  16 July 1998 -- Drive donated to Erik Andersen by John Kodis
142  *                   <kodis@jagunet.com>.  Work begun on fixing driver to
143  *                   work under 2.1.X.  Added temporary extra printks
144  *                   which seem to slow it down enough to work.
145  *
146  *  9 November 1999 -- Make kernel-parameter implementation work with 2.3.x 
147  *                     Removed init_module & cleanup_module in favor of 
148  *                     module_init & module_exit.
149  *                     Torben Mathiasen <tmm@image.dk>
150 */
151
152 #include <linux/major.h>
153
154 #include <linux/module.h>
155
156 #include <linux/errno.h>
157 #include <linux/signal.h>
158 #include <linux/sched.h>
159 #include <linux/timer.h>
160 #include <linux/fs.h>
161 #include <linux/kernel.h>
162 #include <linux/hdreg.h>
163 #include <linux/genhd.h>
164 #include <linux/ioport.h>
165 #include <linux/devfs_fs_kernel.h>
166 #include <linux/string.h>
167 #include <linux/slab.h>
168 #include <linux/init.h>
169 #include <linux/interrupt.h>
170
171 #include <asm/system.h>
172 #include <asm/io.h>
173 #include <asm/uaccess.h>
174 #include <asm/dma.h>
175
176 #include <linux/cdrom.h>
177 #include "cdu31a.h"
178
179 #define MAJOR_NR CDU31A_CDROM_MAJOR
180 #include <linux/blkdev.h>
181
182 #define CDU31A_READAHEAD 4      /* 128 sector, 64kB, 32 reads read-ahead */
183 #define CDU31A_MAX_CONSECUTIVE_ATTENTIONS 10
184
185 #define DEBUG 0
186
187 /* Define the following if you have data corruption problems. */
188 #undef SONY_POLL_EACH_BYTE
189
190 /*
191 ** Edit the following data to change interrupts, DMA channels, etc.
192 ** Default is polled and no DMA.  DMA is not recommended for double-speed
193 ** drives.
194 */
195 static struct {
196         unsigned short base;    /* I/O Base Address */
197         short int_num;          /* Interrupt Number (-1 means scan for it,
198                                    0 means don't use) */
199 } cdu31a_addresses[] __initdata = {
200         {0}
201 };
202
203 static int handle_sony_cd_attention(void);
204 static int read_subcode(void);
205 static void sony_get_toc(void);
206 static int scd_spinup(void);
207 /*static int scd_open(struct inode *inode, struct file *filp);*/
208 static int scd_open(struct cdrom_device_info *, int);
209 static void do_sony_cd_cmd(unsigned char cmd,
210                            unsigned char *params,
211                            unsigned int num_params,
212                            unsigned char *result_buffer,
213                            unsigned int *result_size);
214 static void size_to_buf(unsigned int size, unsigned char *buf);
215
216 /* Parameters for the read-ahead. */
217 static unsigned int sony_next_block;    /* Next 512 byte block offset */
218 static unsigned int sony_blocks_left = 0;       /* Number of 512 byte blocks left
219                                                    in the current read command. */
220
221
222 /* The base I/O address of the Sony Interface.  This is a variable (not a
223    #define) so it can be easily changed via some future ioctl() */
224 static unsigned int cdu31a_port = 0;
225 MODULE_PARM(cdu31a_port, "i");
226
227 /*
228  * The following are I/O addresses of the various registers for the drive.  The
229  * comment for the base address also applies here.
230  */
231 static volatile unsigned short sony_cd_cmd_reg;
232 static volatile unsigned short sony_cd_param_reg;
233 static volatile unsigned short sony_cd_write_reg;
234 static volatile unsigned short sony_cd_control_reg;
235 static volatile unsigned short sony_cd_status_reg;
236 static volatile unsigned short sony_cd_result_reg;
237 static volatile unsigned short sony_cd_read_reg;
238 static volatile unsigned short sony_cd_fifost_reg;
239
240 static struct request_queue *cdu31a_queue;
241 static spinlock_t cdu31a_lock = SPIN_LOCK_UNLOCKED; /* queue lock */
242
243 static int sony_spun_up = 0;    /* Has the drive been spun up? */
244
245 static int sony_speed = 0;      /* Last wanted speed */
246
247 static int sony_xa_mode = 0;    /* Is an XA disk in the drive
248                                    and the drive a CDU31A? */
249
250 static int sony_raw_data_mode = 1;      /* 1 if data tracks, 0 if audio.
251                                            For raw data reads. */
252
253 static unsigned int sony_usage = 0;     /* How many processes have the
254                                            drive open. */
255
256 static int sony_pas_init = 0;   /* Initialize the Pro-Audio
257                                    Spectrum card? */
258
259 static struct s_sony_session_toc single_toc;    /* Holds the
260                                                    table of
261                                                    contents. */
262
263 static struct s_all_sessions_toc sony_toc;      /* entries gathered from all
264                                                    sessions */
265
266 static int sony_toc_read = 0;   /* Has the TOC been read for
267                                    the drive? */
268
269 static struct s_sony_subcode last_sony_subcode; /* Points to the last
270                                                    subcode address read */
271
272 static volatile int sony_inuse = 0;     /* Is the drive in use?  Only one operation
273                                            at a time allowed */
274
275 static DECLARE_WAIT_QUEUE_HEAD(sony_wait);      /* Things waiting for the drive */
276
277 static struct task_struct *has_cd_task = NULL;  /* The task that is currently
278                                                    using the CDROM drive, or
279                                                    NULL if none. */
280
281 static int is_double_speed = 0; /* does the drive support double speed ? */
282 static int is_a_cdu31a = 1;     /* Is the drive a CDU31A? */
283
284 static int is_auto_eject = 1;   /* Door has been locked? 1=No/0=Yes */
285
286 /*
287  * The audio status uses the values from read subchannel data as specified
288  * in include/linux/cdrom.h.
289  */
290 static volatile int sony_audio_status = CDROM_AUDIO_NO_STATUS;
291
292 /*
293  * The following are a hack for pausing and resuming audio play.  The drive
294  * does not work as I would expect it, if you stop it then start it again,
295  * the drive seeks back to the beginning and starts over.  This holds the
296  * position during a pause so a resume can restart it.  It uses the
297  * audio status variable above to tell if it is paused.
298  */
299 static unsigned volatile char cur_pos_msf[3] = { 0, 0, 0 };
300 static unsigned volatile char final_pos_msf[3] = { 0, 0, 0 };
301
302 /* What IRQ is the drive using?  0 if none. */
303 static int cdu31a_irq = 0;
304 MODULE_PARM(cdu31a_irq, "i");
305
306 /* The interrupt handler will wake this queue up when it gets an
307    interrupts. */
308 DECLARE_WAIT_QUEUE_HEAD(cdu31a_irq_wait);
309
310 static int curr_control_reg = 0;        /* Current value of the control register */
311
312 /* A disk changed variable.  When a disk change is detected, it will
313    all be set to TRUE.  As the upper layers ask for disk_changed status
314    it will be cleared. */
315 static char disk_changed;
316
317 /* Variable for using the readahead buffer.  The readahead buffer
318    is used for raw sector reads and for blocksizes that are smaller
319    than 2048 bytes. */
320 static char readahead_buffer[CD_FRAMESIZE_RAW];
321 static int readahead_dataleft = 0;
322 static int readahead_bad = 0;
323
324 /* Used to time a short period to abort an operation after the
325    drive has been idle for a while.  This keeps the light on
326    the drive from flashing for very long. */
327 static struct timer_list cdu31a_abort_timer;
328
329 /* Marks if the timeout has started an abort read.  This is used
330    on entry to the drive to tell the code to read out the status
331    from the abort read. */
332 static int abort_read_started = 0;
333
334 /*
335  * Uniform cdrom interface function
336  * report back, if disc has changed from time of last request.
337  */
338 static int scd_media_changed(struct cdrom_device_info *cdi, int disc_nr)
339 {
340         int retval;
341
342         retval = disk_changed;
343         disk_changed = 0;
344
345         return retval;
346 }
347
348 /*
349  * Uniform cdrom interface function
350  * report back, if drive is ready
351  */
352 static int scd_drive_status(struct cdrom_device_info *cdi, int slot_nr)
353 {
354         if (CDSL_CURRENT != slot_nr) {
355                 /* we have no changer support */
356                 return -EINVAL;
357         }
358         if (scd_spinup() == 0) {
359                 sony_spun_up = 1;
360         }
361         return sony_spun_up ? CDS_DISC_OK : CDS_DRIVE_NOT_READY;
362 }
363
364 static inline void enable_interrupts(void)
365 {
366         curr_control_reg |= (SONY_ATTN_INT_EN_BIT
367                              | SONY_RES_RDY_INT_EN_BIT
368                              | SONY_DATA_RDY_INT_EN_BIT);
369         outb(curr_control_reg, sony_cd_control_reg);
370 }
371
372 static inline void disable_interrupts(void)
373 {
374         curr_control_reg &= ~(SONY_ATTN_INT_EN_BIT
375                               | SONY_RES_RDY_INT_EN_BIT
376                               | SONY_DATA_RDY_INT_EN_BIT);
377         outb(curr_control_reg, sony_cd_control_reg);
378 }
379
380 /*
381  * Wait a little while (used for polling the drive).  If in initialization,
382  * setting a timeout doesn't work, so just loop for a while.
383  */
384 static inline void sony_sleep(void)
385 {
386         unsigned long flags;
387
388         if (cdu31a_irq <= 0) {
389                 yield();
390         } else {                /* Interrupt driven */
391
392                 save_flags(flags);
393                 cli();
394                 enable_interrupts();
395                 interruptible_sleep_on(&cdu31a_irq_wait);
396                 restore_flags(flags);
397         }
398 }
399
400
401 /*
402  * The following are convenience routine to read various status and set
403  * various conditions in the drive.
404  */
405 static inline int is_attention(void)
406 {
407         return ((inb(sony_cd_status_reg) & SONY_ATTN_BIT) != 0);
408 }
409
410 static inline int is_busy(void)
411 {
412         return ((inb(sony_cd_status_reg) & SONY_BUSY_BIT) != 0);
413 }
414
415 static inline int is_data_ready(void)
416 {
417         return ((inb(sony_cd_status_reg) & SONY_DATA_RDY_BIT) != 0);
418 }
419
420 static inline int is_data_requested(void)
421 {
422         return ((inb(sony_cd_status_reg) & SONY_DATA_REQUEST_BIT) != 0);
423 }
424
425 static inline int is_result_ready(void)
426 {
427         return ((inb(sony_cd_status_reg) & SONY_RES_RDY_BIT) != 0);
428 }
429
430 static inline int is_param_write_rdy(void)
431 {
432         return ((inb(sony_cd_fifost_reg) & SONY_PARAM_WRITE_RDY_BIT) != 0);
433 }
434
435 static inline int is_result_reg_not_empty(void)
436 {
437         return ((inb(sony_cd_fifost_reg) & SONY_RES_REG_NOT_EMP_BIT) != 0);
438 }
439
440 static inline void reset_drive(void)
441 {
442         curr_control_reg = 0;
443         readahead_dataleft = 0;
444         sony_toc_read = 0;
445         outb(SONY_DRIVE_RESET_BIT, sony_cd_control_reg);
446 }
447
448 /*
449  * Uniform cdrom interface function
450  * reset drive and return when it is ready
451  */
452 static int scd_reset(struct cdrom_device_info *cdi)
453 {
454         unsigned long retry_count;
455
456         reset_drive();
457
458         retry_count = jiffies + SONY_RESET_TIMEOUT;
459         while (time_before(jiffies, retry_count) && (!is_attention())) {
460                 sony_sleep();
461         }
462
463         return 0;
464 }
465
466 static inline void clear_attention(void)
467 {
468         outb(curr_control_reg | SONY_ATTN_CLR_BIT, sony_cd_control_reg);
469 }
470
471 static inline void clear_result_ready(void)
472 {
473         outb(curr_control_reg | SONY_RES_RDY_CLR_BIT, sony_cd_control_reg);
474 }
475
476 static inline void clear_data_ready(void)
477 {
478         outb(curr_control_reg | SONY_DATA_RDY_CLR_BIT,
479              sony_cd_control_reg);
480 }
481
482 static inline void clear_param_reg(void)
483 {
484         outb(curr_control_reg | SONY_PARAM_CLR_BIT, sony_cd_control_reg);
485 }
486
487 static inline unsigned char read_status_register(void)
488 {
489         return (inb(sony_cd_status_reg));
490 }
491
492 static inline unsigned char read_result_register(void)
493 {
494         return (inb(sony_cd_result_reg));
495 }
496
497 static inline unsigned char read_data_register(void)
498 {
499         return (inb(sony_cd_read_reg));
500 }
501
502 static inline void write_param(unsigned char param)
503 {
504         outb(param, sony_cd_param_reg);
505 }
506
507 static inline void write_cmd(unsigned char cmd)
508 {
509         outb(curr_control_reg | SONY_RES_RDY_INT_EN_BIT,
510              sony_cd_control_reg);
511         outb(cmd, sony_cd_cmd_reg);
512 }
513
514 static irqreturn_t cdu31a_interrupt(int irq, void *dev_id, struct pt_regs *regs)
515 {
516         unsigned char val;
517
518         if (abort_read_started) {
519                 /* We might be waiting for an abort to finish.  Don't
520                    disable interrupts yet, though, because we handle
521                    this one here. */
522                 /* Clear out the result registers. */
523                 while (is_result_reg_not_empty()) {
524                         val = read_result_register();
525                 }
526                 clear_data_ready();
527                 clear_result_ready();
528
529                 /* Clear out the data */
530                 while (is_data_requested()) {
531                         val = read_data_register();
532                 }
533                 abort_read_started = 0;
534
535                 /* If something was waiting, wake it up now. */
536                 if (waitqueue_active(&cdu31a_irq_wait)) {
537                         disable_interrupts();
538                         wake_up(&cdu31a_irq_wait);
539                 }
540         } else if (waitqueue_active(&cdu31a_irq_wait)) {
541                 disable_interrupts();
542                 wake_up(&cdu31a_irq_wait);
543         } else {
544                 disable_interrupts();
545                 printk
546                     ("CDU31A: Got an interrupt but nothing was waiting\n");
547         }
548         return IRQ_HANDLED;
549 }
550
551 /*
552  * give more verbose error messages
553  */
554 static unsigned char *translate_error(unsigned char err_code)
555 {
556         static unsigned char errbuf[80];
557
558         switch (err_code) {
559         case 0x10:
560                 return "illegal command ";
561         case 0x11:
562                 return "illegal parameter ";
563
564         case 0x20:
565                 return "not loaded ";
566         case 0x21:
567                 return "no disc ";
568         case 0x22:
569                 return "not spinning ";
570         case 0x23:
571                 return "spinning ";
572         case 0x25:
573                 return "spindle servo ";
574         case 0x26:
575                 return "focus servo ";
576         case 0x29:
577                 return "eject mechanism ";
578         case 0x2a:
579                 return "audio playing ";
580         case 0x2c:
581                 return "emergency eject ";
582
583         case 0x30:
584                 return "focus ";
585         case 0x31:
586                 return "frame sync ";
587         case 0x32:
588                 return "subcode address ";
589         case 0x33:
590                 return "block sync ";
591         case 0x34:
592                 return "header address ";
593
594         case 0x40:
595                 return "illegal track read ";
596         case 0x41:
597                 return "mode 0 read ";
598         case 0x42:
599                 return "illegal mode read ";
600         case 0x43:
601                 return "illegal block size read ";
602         case 0x44:
603                 return "mode read ";
604         case 0x45:
605                 return "form read ";
606         case 0x46:
607                 return "leadout read ";
608         case 0x47:
609                 return "buffer overrun ";
610
611         case 0x53:
612                 return "unrecoverable CIRC ";
613         case 0x57:
614                 return "unrecoverable LECC ";
615
616         case 0x60:
617                 return "no TOC ";
618         case 0x61:
619                 return "invalid subcode data ";
620         case 0x63:
621                 return "focus on TOC read ";
622         case 0x64:
623                 return "frame sync on TOC read ";
624         case 0x65:
625                 return "TOC data ";
626
627         case 0x70:
628                 return "hardware failure ";
629         case 0x91:
630                 return "leadin ";
631         case 0x92:
632                 return "leadout ";
633         case 0x93:
634                 return "data track ";
635         }
636         sprintf(errbuf, "unknown 0x%02x ", err_code);
637         return errbuf;
638 }
639
640 /*
641  * Set the drive parameters so the drive will auto-spin-up when a
642  * disk is inserted.
643  */
644 static void set_drive_params(int want_doublespeed)
645 {
646         unsigned char res_reg[12];
647         unsigned int res_size;
648         unsigned char params[3];
649
650
651         params[0] = SONY_SD_AUTO_SPIN_DOWN_TIME;
652         params[1] = 0x00;       /* Never spin down the drive. */
653         do_sony_cd_cmd(SONY_SET_DRIVE_PARAM_CMD,
654                        params, 2, res_reg, &res_size);
655         if ((res_size < 2) || ((res_reg[0] & 0xf0) == 0x20)) {
656                 printk("  Unable to set spin-down time: 0x%2.2x\n",
657                        res_reg[1]);
658         }
659
660         params[0] = SONY_SD_MECH_CONTROL;
661         params[1] = SONY_AUTO_SPIN_UP_BIT;      /* Set auto spin up */
662
663         if (is_auto_eject)
664                 params[1] |= SONY_AUTO_EJECT_BIT;
665
666         if (is_double_speed && want_doublespeed) {
667                 params[1] |= SONY_DOUBLE_SPEED_BIT;     /* Set the drive to double speed if 
668                                                            possible */
669         }
670         do_sony_cd_cmd(SONY_SET_DRIVE_PARAM_CMD,
671                        params, 2, res_reg, &res_size);
672         if ((res_size < 2) || ((res_reg[0] & 0xf0) == 0x20)) {
673                 printk("  Unable to set mechanical parameters: 0x%2.2x\n",
674                        res_reg[1]);
675         }
676 }
677
678 /*
679  * Uniform cdrom interface function
680  * select reading speed for data access
681  */
682 static int scd_select_speed(struct cdrom_device_info *cdi, int speed)
683 {
684         if (speed == 0)
685                 sony_speed = 1;
686         else
687                 sony_speed = speed - 1;
688
689         set_drive_params(sony_speed);
690         return 0;
691 }
692
693 /*
694  * Uniform cdrom interface function
695  * lock or unlock eject button
696  */
697 static int scd_lock_door(struct cdrom_device_info *cdi, int lock)
698 {
699         if (lock == 0 && sony_usage == 1) {
700                 /* Unlock the door, only if nobody is using the drive */
701                 is_auto_eject = 1;
702         } else {
703                 is_auto_eject = 0;
704         }
705         set_drive_params(sony_speed);
706         return 0;
707 }
708
709 /*
710  * This code will reset the drive and attempt to restore sane parameters.
711  */
712 static void restart_on_error(void)
713 {
714         unsigned char res_reg[12];
715         unsigned int res_size;
716         unsigned long retry_count;
717
718
719         printk("cdu31a: Resetting drive on error\n");
720         reset_drive();
721         retry_count = jiffies + SONY_RESET_TIMEOUT;
722         while (time_before(jiffies, retry_count) && (!is_attention())) {
723                 sony_sleep();
724         }
725         set_drive_params(sony_speed);
726         do_sony_cd_cmd(SONY_SPIN_UP_CMD, NULL, 0, res_reg, &res_size);
727         if ((res_size < 2) || ((res_reg[0] & 0xf0) == 0x20)) {
728                 printk("cdu31a: Unable to spin up drive: 0x%2.2x\n",
729                        res_reg[1]);
730         }
731
732         current->state = TASK_INTERRUPTIBLE;
733         schedule_timeout(2 * HZ);
734
735         sony_get_toc();
736 }
737
738 /*
739  * This routine writes data to the parameter register.  Since this should
740  * happen fairly fast, it is polled with no OS waits between.
741  */
742 static int write_params(unsigned char *params, int num_params)
743 {
744         unsigned int retry_count;
745
746
747         retry_count = SONY_READY_RETRIES;
748         while ((retry_count > 0) && (!is_param_write_rdy())) {
749                 retry_count--;
750         }
751         if (!is_param_write_rdy()) {
752                 return -EIO;
753         }
754
755         while (num_params > 0) {
756                 write_param(*params);
757                 params++;
758                 num_params--;
759         }
760
761         return 0;
762 }
763
764
765 /*
766  * The following reads data from the command result register.  It is a
767  * fairly complex routine, all status info flows back through this
768  * interface.  The algorithm is stolen directly from the flowcharts in
769  * the drive manual.
770  */
771 static void
772 get_result(unsigned char *result_buffer, unsigned int *result_size)
773 {
774         unsigned char a, b;
775         int i;
776         unsigned long retry_count;
777
778
779         while (handle_sony_cd_attention());
780         /* Wait for the result data to be ready */
781         retry_count = jiffies + SONY_JIFFIES_TIMEOUT;
782         while (time_before(jiffies, retry_count)
783                && (is_busy() || (!(is_result_ready())))) {
784                 sony_sleep();
785
786                 while (handle_sony_cd_attention());
787         }
788         if (is_busy() || (!(is_result_ready()))) {
789 #if DEBUG
790                 printk("CDU31A timeout out %d\n", __LINE__);
791 #endif
792                 result_buffer[0] = 0x20;
793                 result_buffer[1] = SONY_TIMEOUT_OP_ERR;
794                 *result_size = 2;
795                 return;
796         }
797
798         /*
799          * Get the first two bytes.  This determines what else needs
800          * to be done.
801          */
802         clear_result_ready();
803         a = read_result_register();
804         *result_buffer = a;
805         result_buffer++;
806
807         /* Check for block error status result. */
808         if ((a & 0xf0) == 0x50) {
809                 *result_size = 1;
810                 return;
811         }
812
813         b = read_result_register();
814         *result_buffer = b;
815         result_buffer++;
816         *result_size = 2;
817
818         /*
819          * 0x20 means an error occurred.  Byte 2 will have the error code.
820          * Otherwise, the command succeeded, byte 2 will have the count of
821          * how many more status bytes are coming.
822          *
823          * The result register can be read 10 bytes at a time, a wait for
824          * result ready to be asserted must be done between every 10 bytes.
825          */
826         if ((a & 0xf0) != 0x20) {
827                 if (b > 8) {
828                         for (i = 0; i < 8; i++) {
829                                 *result_buffer = read_result_register();
830                                 result_buffer++;
831                                 (*result_size)++;
832                         }
833                         b = b - 8;
834
835                         while (b > 10) {
836                                 retry_count = SONY_READY_RETRIES;
837                                 while ((retry_count > 0)
838                                        && (!is_result_ready())) {
839                                         retry_count--;
840                                 }
841                                 if (!is_result_ready()) {
842 #if DEBUG
843                                         printk("CDU31A timeout out %d\n",
844                                                __LINE__);
845 #endif
846                                         result_buffer[0] = 0x20;
847                                         result_buffer[1] =
848                                             SONY_TIMEOUT_OP_ERR;
849                                         *result_size = 2;
850                                         return;
851                                 }
852
853                                 clear_result_ready();
854
855                                 for (i = 0; i < 10; i++) {
856                                         *result_buffer =
857                                             read_result_register();
858                                         result_buffer++;
859                                         (*result_size)++;
860                                 }
861                                 b = b - 10;
862                         }
863
864                         if (b > 0) {
865                                 retry_count = SONY_READY_RETRIES;
866                                 while ((retry_count > 0)
867                                        && (!is_result_ready())) {
868                                         retry_count--;
869                                 }
870                                 if (!is_result_ready()) {
871 #if DEBUG
872                                         printk("CDU31A timeout out %d\n",
873                                                __LINE__);
874 #endif
875                                         result_buffer[0] = 0x20;
876                                         result_buffer[1] =
877                                             SONY_TIMEOUT_OP_ERR;
878                                         *result_size = 2;
879                                         return;
880                                 }
881                         }
882                 }
883
884                 while (b > 0) {
885                         *result_buffer = read_result_register();
886                         result_buffer++;
887                         (*result_size)++;
888                         b--;
889                 }
890         }
891 }
892
893 /*
894  * Do a command that does not involve data transfer.  This routine must
895  * be re-entrant from the same task to support being called from the
896  * data operation code when an error occurs.
897  */
898 static void
899 do_sony_cd_cmd(unsigned char cmd,
900                unsigned char *params,
901                unsigned int num_params,
902                unsigned char *result_buffer, unsigned int *result_size)
903 {
904         unsigned long retry_count;
905         int num_retries;
906         int recursive_call;
907         unsigned long flags;
908
909
910         save_flags(flags);
911         cli();
912         if (current != has_cd_task) {   /* Allow recursive calls to this routine */
913                 while (sony_inuse) {
914                         interruptible_sleep_on(&sony_wait);
915                         if (signal_pending(current)) {
916                                 result_buffer[0] = 0x20;
917                                 result_buffer[1] = SONY_SIGNAL_OP_ERR;
918                                 *result_size = 2;
919                                 restore_flags(flags);
920                                 return;
921                         }
922                 }
923                 sony_inuse = 1;
924                 has_cd_task = current;
925                 recursive_call = 0;
926         } else {
927                 recursive_call = 1;
928         }
929
930         num_retries = 0;
931 retry_cd_operation:
932
933         while (handle_sony_cd_attention());
934
935         sti();
936
937         retry_count = jiffies + SONY_JIFFIES_TIMEOUT;
938         while (time_before(jiffies, retry_count) && (is_busy())) {
939                 sony_sleep();
940
941                 while (handle_sony_cd_attention());
942         }
943         if (is_busy()) {
944 #if DEBUG
945                 printk("CDU31A timeout out %d\n", __LINE__);
946 #endif
947                 result_buffer[0] = 0x20;
948                 result_buffer[1] = SONY_TIMEOUT_OP_ERR;
949                 *result_size = 2;
950         } else {
951                 clear_result_ready();
952                 clear_param_reg();
953
954                 write_params(params, num_params);
955                 write_cmd(cmd);
956
957                 get_result(result_buffer, result_size);
958         }
959
960         if (((result_buffer[0] & 0xf0) == 0x20)
961             && (num_retries < MAX_CDU31A_RETRIES)) {
962                 num_retries++;
963                 current->state = TASK_INTERRUPTIBLE;
964                 schedule_timeout(HZ / 10);      /* Wait .1 seconds on retries */
965                 goto retry_cd_operation;
966         }
967
968         if (!recursive_call) {
969                 has_cd_task = NULL;
970                 sony_inuse = 0;
971                 wake_up_interruptible(&sony_wait);
972         }
973
974         restore_flags(flags);
975 }
976
977
978 /*
979  * Handle an attention from the drive.  This will return 1 if it found one
980  * or 0 if not (if one is found, the caller might want to call again).
981  *
982  * This routine counts the number of consecutive times it is called
983  * (since this is always called from a while loop until it returns
984  * a 0), and returns a 0 if it happens too many times.  This will help
985  * prevent a lockup.
986  */
987 static int handle_sony_cd_attention(void)
988 {
989         unsigned char atten_code;
990         static int num_consecutive_attentions = 0;
991         volatile int val;
992
993
994 #if 0*DEBUG
995         printk("Entering handle_sony_cd_attention\n");
996 #endif
997         if (is_attention()) {
998                 if (num_consecutive_attentions >
999                     CDU31A_MAX_CONSECUTIVE_ATTENTIONS) {
1000                         printk
1001                             ("cdu31a: Too many consecutive attentions: %d\n",
1002                              num_consecutive_attentions);
1003                         num_consecutive_attentions = 0;
1004 #if DEBUG
1005                         printk("Leaving handle_sony_cd_attention at %d\n",
1006                                __LINE__);
1007 #endif
1008                         return (0);
1009                 }
1010
1011                 clear_attention();
1012                 atten_code = read_result_register();
1013
1014                 switch (atten_code) {
1015                         /* Someone changed the CD.  Mark it as changed */
1016                 case SONY_MECH_LOADED_ATTN:
1017                         disk_changed = 1;
1018                         sony_toc_read = 0;
1019                         sony_audio_status = CDROM_AUDIO_NO_STATUS;
1020                         sony_blocks_left = 0;
1021                         break;
1022
1023                 case SONY_SPIN_DOWN_COMPLETE_ATTN:
1024                         /* Mark the disk as spun down. */
1025                         sony_spun_up = 0;
1026                         break;
1027
1028                 case SONY_AUDIO_PLAY_DONE_ATTN:
1029                         sony_audio_status = CDROM_AUDIO_COMPLETED;
1030                         read_subcode();
1031                         break;
1032
1033                 case SONY_EJECT_PUSHED_ATTN:
1034                         if (is_auto_eject) {
1035                                 sony_audio_status = CDROM_AUDIO_INVALID;
1036                         }
1037                         break;
1038
1039                 case SONY_LEAD_IN_ERR_ATTN:
1040                 case SONY_LEAD_OUT_ERR_ATTN:
1041                 case SONY_DATA_TRACK_ERR_ATTN:
1042                 case SONY_AUDIO_PLAYBACK_ERR_ATTN:
1043                         sony_audio_status = CDROM_AUDIO_ERROR;
1044                         break;
1045                 }
1046
1047                 num_consecutive_attentions++;
1048 #if DEBUG
1049                 printk("Leaving handle_sony_cd_attention at %d\n",
1050                        __LINE__);
1051 #endif
1052                 return (1);
1053         } else if (abort_read_started) {
1054                 while (is_result_reg_not_empty()) {
1055                         val = read_result_register();
1056                 }
1057                 clear_data_ready();
1058                 clear_result_ready();
1059                 /* Clear out the data */
1060                 while (is_data_requested()) {
1061                         val = read_data_register();
1062                 }
1063                 abort_read_started = 0;
1064 #if DEBUG
1065                 printk("Leaving handle_sony_cd_attention at %d\n",
1066                        __LINE__);
1067 #endif
1068                 return (1);
1069         }
1070
1071         num_consecutive_attentions = 0;
1072 #if 0*DEBUG
1073         printk("Leaving handle_sony_cd_attention at %d\n", __LINE__);
1074 #endif
1075         return (0);
1076 }
1077
1078
1079 /* Convert from an integer 0-99 to BCD */
1080 static inline unsigned int int_to_bcd(unsigned int val)
1081 {
1082         int retval;
1083
1084
1085         retval = (val / 10) << 4;
1086         retval = retval | val % 10;
1087         return (retval);
1088 }
1089
1090
1091 /* Convert from BCD to an integer from 0-99 */
1092 static unsigned int bcd_to_int(unsigned int bcd)
1093 {
1094         return ((((bcd >> 4) & 0x0f) * 10) + (bcd & 0x0f));
1095 }
1096
1097
1098 /*
1099  * Convert a logical sector value (like the OS would want to use for
1100  * a block device) to an MSF format.
1101  */
1102 static void log_to_msf(unsigned int log, unsigned char *msf)
1103 {
1104         log = log + LOG_START_OFFSET;
1105         msf[0] = int_to_bcd(log / 4500);
1106         log = log % 4500;
1107         msf[1] = int_to_bcd(log / 75);
1108         msf[2] = int_to_bcd(log % 75);
1109 }
1110
1111
1112 /*
1113  * Convert an MSF format to a logical sector.
1114  */
1115 static unsigned int msf_to_log(unsigned char *msf)
1116 {
1117         unsigned int log;
1118
1119
1120         log = msf[2];
1121         log += msf[1] * 75;
1122         log += msf[0] * 4500;
1123         log = log - LOG_START_OFFSET;
1124
1125         return log;
1126 }
1127
1128
1129 /*
1130  * Take in integer size value and put it into a buffer like
1131  * the drive would want to see a number-of-sector value.
1132  */
1133 static void size_to_buf(unsigned int size, unsigned char *buf)
1134 {
1135         buf[0] = size / 65536;
1136         size = size % 65536;
1137         buf[1] = size / 256;
1138         buf[2] = size % 256;
1139 }
1140
1141 /* Starts a read operation. Returns 0 on success and 1 on failure. 
1142    The read operation used here allows multiple sequential sectors 
1143    to be read and status returned for each sector.  The driver will
1144    read the output one at a time as the requests come and abort the
1145    operation if the requested sector is not the next one from the
1146    drive. */
1147 static int
1148 start_request(unsigned int sector, unsigned int nsect, int read_nsect_only)
1149 {
1150         unsigned char params[6];
1151         unsigned int read_size;
1152         unsigned long retry_count;
1153
1154
1155 #if DEBUG
1156         printk("Entering start_request\n");
1157 #endif
1158         log_to_msf(sector, params);
1159         /* If requested, read exactly what was asked. */
1160         if (read_nsect_only) {
1161                 read_size = nsect;
1162         }
1163         /*
1164          * If the full read-ahead would go beyond the end of the media, trim
1165          * it back to read just till the end of the media.
1166          */
1167         else if ((sector + nsect) >= sony_toc.lead_out_start_lba) {
1168                 read_size = sony_toc.lead_out_start_lba - sector;
1169         }
1170         /* Read the full readahead amount. */
1171         else {
1172                 read_size = CDU31A_READAHEAD / 4;
1173         }
1174         size_to_buf(read_size, &params[3]);
1175
1176         /*
1177          * Clear any outstanding attentions and wait for the drive to
1178          * complete any pending operations.
1179          */
1180         while (handle_sony_cd_attention());
1181
1182         retry_count = jiffies + SONY_JIFFIES_TIMEOUT;
1183         while (time_before(jiffies, retry_count) && (is_busy())) {
1184                 sony_sleep();
1185
1186                 while (handle_sony_cd_attention());
1187         }
1188
1189         if (is_busy()) {
1190                 printk("CDU31A: Timeout while waiting to issue command\n");
1191 #if DEBUG
1192                 printk("Leaving start_request at %d\n", __LINE__);
1193 #endif
1194                 return (1);
1195         } else {
1196                 /* Issue the command */
1197                 clear_result_ready();
1198                 clear_param_reg();
1199
1200                 write_params(params, 6);
1201                 write_cmd(SONY_READ_BLKERR_STAT_CMD);
1202
1203                 sony_blocks_left = read_size * 4;
1204                 sony_next_block = sector * 4;
1205                 readahead_dataleft = 0;
1206                 readahead_bad = 0;
1207 #if DEBUG
1208                 printk("Leaving start_request at %d\n", __LINE__);
1209 #endif
1210                 return (0);
1211         }
1212 #if DEBUG
1213         printk("Leaving start_request at %d\n", __LINE__);
1214 #endif
1215 }
1216
1217 /* Abort a pending read operation.  Clear all the drive status and
1218    readahead variables. */
1219 static void abort_read(void)
1220 {
1221         unsigned char result_reg[2];
1222         int result_size;
1223         volatile int val;
1224
1225
1226         do_sony_cd_cmd(SONY_ABORT_CMD, NULL, 0, result_reg, &result_size);
1227         if ((result_reg[0] & 0xf0) == 0x20) {
1228                 printk("CDU31A: Error aborting read, %s error\n",
1229                        translate_error(result_reg[1]));
1230         }
1231
1232         while (is_result_reg_not_empty()) {
1233                 val = read_result_register();
1234         }
1235         clear_data_ready();
1236         clear_result_ready();
1237         /* Clear out the data */
1238         while (is_data_requested()) {
1239                 val = read_data_register();
1240         }
1241
1242         sony_blocks_left = 0;
1243         readahead_dataleft = 0;
1244         readahead_bad = 0;
1245 }
1246
1247 /* Called when the timer times out.  This will abort the
1248    pending read operation. */
1249 static void handle_abort_timeout(unsigned long data)
1250 {
1251         unsigned long flags;
1252
1253 #if DEBUG
1254         printk("Entering handle_abort_timeout\n");
1255 #endif
1256         save_flags(flags);
1257         cli();
1258         /* If it is in use, ignore it. */
1259         if (!sony_inuse) {
1260                 /* We can't use abort_read(), because it will sleep
1261                    or schedule in the timer interrupt.  Just start
1262                    the operation, finish it on the next access to
1263                    the drive. */
1264                 clear_result_ready();
1265                 clear_param_reg();
1266                 write_cmd(SONY_ABORT_CMD);
1267
1268                 sony_blocks_left = 0;
1269                 readahead_dataleft = 0;
1270                 readahead_bad = 0;
1271                 abort_read_started = 1;
1272         }
1273         restore_flags(flags);
1274 #if DEBUG
1275         printk("Leaving handle_abort_timeout\n");
1276 #endif
1277 }
1278
1279 /* Actually get data and status from the drive. */
1280 static void
1281 input_data(char *buffer,
1282            unsigned int bytesleft,
1283            unsigned int nblocks, unsigned int offset, unsigned int skip)
1284 {
1285         int i;
1286         volatile unsigned char val;
1287
1288
1289 #if DEBUG
1290         printk("Entering input_data\n");
1291 #endif
1292         /* If an XA disk on a CDU31A, skip the first 12 bytes of data from
1293            the disk.  The real data is after that. */
1294         if (sony_xa_mode) {
1295                 for (i = 0; i < CD_XA_HEAD; i++) {
1296                         val = read_data_register();
1297                 }
1298         }
1299
1300         clear_data_ready();
1301
1302         if (bytesleft == 2048) {        /* 2048 byte direct buffer transfer */
1303                 insb(sony_cd_read_reg, buffer, 2048);
1304                 readahead_dataleft = 0;
1305         } else {
1306                 /* If the input read did not align with the beginning of the block,
1307                    skip the necessary bytes. */
1308                 if (skip != 0) {
1309                         insb(sony_cd_read_reg, readahead_buffer, skip);
1310                 }
1311
1312                 /* Get the data into the buffer. */
1313                 insb(sony_cd_read_reg, &buffer[offset], bytesleft);
1314
1315                 /* Get the rest of the data into the readahead buffer at the
1316                    proper location. */
1317                 readahead_dataleft = (2048 - skip) - bytesleft;
1318                 insb(sony_cd_read_reg,
1319                      readahead_buffer + bytesleft, readahead_dataleft);
1320         }
1321         sony_blocks_left -= nblocks;
1322         sony_next_block += nblocks;
1323
1324         /* If an XA disk, we have to clear out the rest of the unused
1325            error correction data. */
1326         if (sony_xa_mode) {
1327                 for (i = 0; i < CD_XA_TAIL; i++) {
1328                         val = read_data_register();
1329                 }
1330         }
1331 #if DEBUG
1332         printk("Leaving input_data at %d\n", __LINE__);
1333 #endif
1334 }
1335
1336 /* read data from the drive.  Note the nsect must be <= 4. */
1337 static void
1338 read_data_block(char *buffer,
1339                 unsigned int block,
1340                 unsigned int nblocks,
1341                 unsigned char res_reg[], int *res_size)
1342 {
1343         unsigned long retry_count;
1344         unsigned int bytesleft;
1345         unsigned int offset;
1346         unsigned int skip;
1347
1348
1349 #if DEBUG
1350         printk("Entering read_data_block\n");
1351 #endif
1352
1353         res_reg[0] = 0;
1354         res_reg[1] = 0;
1355         *res_size = 0;
1356         bytesleft = nblocks * 512;
1357         offset = 0;
1358
1359         /* If the data in the read-ahead does not match the block offset,
1360            then fix things up. */
1361         if (((block % 4) * 512) != ((2048 - readahead_dataleft) % 2048)) {
1362                 sony_next_block += block % 4;
1363                 sony_blocks_left -= block % 4;
1364                 skip = (block % 4) * 512;
1365         } else {
1366                 skip = 0;
1367         }
1368
1369         /* We have readahead data in the buffer, get that first before we
1370            decide if a read is necessary. */
1371         if (readahead_dataleft != 0) {
1372                 if (bytesleft > readahead_dataleft) {
1373                         /* The readahead will not fill the requested buffer, but
1374                            get the data out of the readahead into the buffer. */
1375                         memcpy(buffer,
1376                                readahead_buffer + (2048 -
1377                                                    readahead_dataleft),
1378                                readahead_dataleft);
1379                         bytesleft -= readahead_dataleft;
1380                         offset += readahead_dataleft;
1381                         readahead_dataleft = 0;
1382                 } else {
1383                         /* The readahead will fill the whole buffer, get the data
1384                            and return. */
1385                         memcpy(buffer,
1386                                readahead_buffer + (2048 -
1387                                                    readahead_dataleft),
1388                                bytesleft);
1389                         readahead_dataleft -= bytesleft;
1390                         bytesleft = 0;
1391                         sony_blocks_left -= nblocks;
1392                         sony_next_block += nblocks;
1393
1394                         /* If the data in the readahead is bad, return an error so the
1395                            driver will abort the buffer. */
1396                         if (readahead_bad) {
1397                                 res_reg[0] = 0x20;
1398                                 res_reg[1] = SONY_BAD_DATA_ERR;
1399                                 *res_size = 2;
1400                         }
1401
1402                         if (readahead_dataleft == 0) {
1403                                 readahead_bad = 0;
1404                         }
1405
1406                         /* Final transfer is done for read command, get final result. */
1407                         if (sony_blocks_left == 0) {
1408                                 get_result(res_reg, res_size);
1409                         }
1410 #if DEBUG
1411                         printk("Leaving read_data_block at %d\n",
1412                                __LINE__);
1413 #endif
1414                         return;
1415                 }
1416         }
1417
1418         /* Wait for the drive to tell us we have something */
1419         retry_count = jiffies + SONY_JIFFIES_TIMEOUT;
1420         while (time_before(jiffies, retry_count) && !(is_data_ready())) {
1421                 while (handle_sony_cd_attention());
1422
1423                 sony_sleep();
1424         }
1425         if (!(is_data_ready())) {
1426                 if (is_result_ready()) {
1427                         get_result(res_reg, res_size);
1428                         if ((res_reg[0] & 0xf0) != 0x20) {
1429                                 printk
1430                                     ("CDU31A: Got result that should have been error: %d\n",
1431                                      res_reg[0]);
1432                                 res_reg[0] = 0x20;
1433                                 res_reg[1] = SONY_BAD_DATA_ERR;
1434                                 *res_size = 2;
1435                         }
1436                         abort_read();
1437                 } else {
1438 #if DEBUG
1439                         printk("CDU31A timeout out %d\n", __LINE__);
1440 #endif
1441                         res_reg[0] = 0x20;
1442                         res_reg[1] = SONY_TIMEOUT_OP_ERR;
1443                         *res_size = 2;
1444                         abort_read();
1445                 }
1446         } else {
1447                 input_data(buffer, bytesleft, nblocks, offset, skip);
1448
1449                 /* Wait for the status from the drive. */
1450                 retry_count = jiffies + SONY_JIFFIES_TIMEOUT;
1451                 while (time_before(jiffies, retry_count)
1452                        && !(is_result_ready())) {
1453                         while (handle_sony_cd_attention());
1454
1455                         sony_sleep();
1456                 }
1457
1458                 if (!is_result_ready()) {
1459 #if DEBUG
1460                         printk("CDU31A timeout out %d\n", __LINE__);
1461 #endif
1462                         res_reg[0] = 0x20;
1463                         res_reg[1] = SONY_TIMEOUT_OP_ERR;
1464                         *res_size = 2;
1465                         abort_read();
1466                 } else {
1467                         get_result(res_reg, res_size);
1468
1469                         /* If we got a buffer status, handle that. */
1470                         if ((res_reg[0] & 0xf0) == 0x50) {
1471
1472                                 if ((res_reg[0] ==
1473                                      SONY_NO_CIRC_ERR_BLK_STAT)
1474                                     || (res_reg[0] ==
1475                                         SONY_NO_LECC_ERR_BLK_STAT)
1476                                     || (res_reg[0] ==
1477                                         SONY_RECOV_LECC_ERR_BLK_STAT)) {
1478                                         /* The data was successful, but if data was read from
1479                                            the readahead  and it was bad, set the whole
1480                                            buffer as bad. */
1481                                         if (readahead_bad) {
1482                                                 readahead_bad = 0;
1483                                                 res_reg[0] = 0x20;
1484                                                 res_reg[1] =
1485                                                     SONY_BAD_DATA_ERR;
1486                                                 *res_size = 2;
1487                                         }
1488                                 } else {
1489                                         printk
1490                                             ("CDU31A: Data block error: 0x%x\n",
1491                                              res_reg[0]);
1492                                         res_reg[0] = 0x20;
1493                                         res_reg[1] = SONY_BAD_DATA_ERR;
1494                                         *res_size = 2;
1495
1496                                         /* Data is in the readahead buffer but an error was returned.
1497                                            Make sure future requests don't use the data. */
1498                                         if (bytesleft != 2048) {
1499                                                 readahead_bad = 1;
1500                                         }
1501                                 }
1502
1503                                 /* Final transfer is done for read command, get final result. */
1504                                 if (sony_blocks_left == 0) {
1505                                         get_result(res_reg, res_size);
1506                                 }
1507                         } else if ((res_reg[0] & 0xf0) != 0x20) {
1508                                 /* The drive gave me bad status, I don't know what to do.
1509                                    Reset the driver and return an error. */
1510                                 printk
1511                                     ("CDU31A: Invalid block status: 0x%x\n",
1512                                      res_reg[0]);
1513                                 restart_on_error();
1514                                 res_reg[0] = 0x20;
1515                                 res_reg[1] = SONY_BAD_DATA_ERR;
1516                                 *res_size = 2;
1517                         }
1518                 }
1519         }
1520 #if DEBUG
1521         printk("Leaving read_data_block at %d\n", __LINE__);
1522 #endif
1523 }
1524
1525
1526 /*
1527  * The OS calls this to perform a read or write operation to the drive.
1528  * Write obviously fail.  Reads to a read ahead of sony_buffer_size
1529  * bytes to help speed operations.  This especially helps since the OS
1530  * uses 1024 byte blocks and the drive uses 2048 byte blocks.  Since most
1531  * data access on a CD is done sequentially, this saves a lot of operations.
1532  */
1533 static void do_cdu31a_request(request_queue_t * q)
1534 {
1535         struct request *req;
1536         int block;
1537         int nblock;
1538         unsigned char res_reg[12];
1539         unsigned int res_size;
1540         int num_retries;
1541         unsigned long flags;
1542
1543
1544 #if DEBUG
1545         printk("Entering do_cdu31a_request\n");
1546 #endif
1547
1548         /* 
1549          * Make sure no one else is using the driver; wait for them
1550          * to finish if it is so.
1551          */
1552         save_flags(flags);
1553         cli();
1554         while (sony_inuse) {
1555                 interruptible_sleep_on(&sony_wait);
1556                 if (signal_pending(current)) {
1557                         restore_flags(flags);
1558 #if DEBUG
1559                         printk("Leaving do_cdu31a_request at %d\n",
1560                                __LINE__);
1561 #endif
1562                         return;
1563                 }
1564         }
1565         sony_inuse = 1;
1566         has_cd_task = current;
1567
1568         /* Get drive status before doing anything. */
1569         while (handle_sony_cd_attention());
1570
1571         /* Make sure we have a valid TOC. */
1572         sony_get_toc();
1573
1574         /*
1575          * jens: driver has lots of races
1576          */
1577         spin_unlock_irq(q->queue_lock);
1578
1579         /* Make sure the timer is cancelled. */
1580         del_timer(&cdu31a_abort_timer);
1581
1582         while (1) {
1583                 /*
1584                  * The beginning here is stolen from the hard disk driver.  I hope
1585                  * it's right.
1586                  */
1587                 req = elv_next_request(q);
1588                 if (!req)
1589                         goto end_do_cdu31a_request;
1590
1591                 if (!sony_spun_up)
1592                         scd_spinup();
1593
1594                 block = req->sector;
1595                 nblock = req->nr_sectors;
1596
1597                 if (!sony_toc_read) {
1598                         printk("CDU31A: TOC not read\n");
1599                         end_request(req, 0);
1600                         continue;
1601                 }
1602
1603                 /* WTF??? */
1604                 if (!(req->flags & REQ_CMD))
1605                         continue;
1606                 if (rq_data_dir(req) == WRITE) {
1607                         end_request(req, 0);
1608                         continue;
1609                 }
1610                 if (rq_data_dir(req) != READ)
1611                         panic("CDU31A: Unknown cmd");
1612                 /*
1613                  * If the block address is invalid or the request goes beyond the end of
1614                  * the media, return an error.
1615                  */
1616                 if ((block / 4) >= sony_toc.lead_out_start_lba) {
1617                         printk("CDU31A: Request past end of media\n");
1618                         end_request(req, 0);
1619                         continue;
1620                 }
1621                 if (((block + nblock) / 4) >= sony_toc.lead_out_start_lba) {
1622                         printk("CDU31A: Request past end of media\n");
1623                         end_request(req, 0);
1624                         continue;
1625                 }
1626
1627                 num_retries = 0;
1628
1629         try_read_again:
1630                 while (handle_sony_cd_attention());
1631
1632                 if (!sony_toc_read) {
1633                         printk("CDU31A: TOC not read\n");
1634                         end_request(req, 0);
1635                         continue;
1636                 }
1637
1638                 /* If no data is left to be read from the drive, start the
1639                    next request. */
1640                 if (sony_blocks_left == 0) {
1641                         if (start_request(block / 4, CDU31A_READAHEAD / 4, 0)) {
1642                                 end_request(req, 0);
1643                                 continue;
1644                         }
1645                 }
1646                 /* If the requested block is not the next one waiting in
1647                    the driver, abort the current operation and start a
1648                    new one. */
1649                 else if (block != sony_next_block) {
1650 #if DEBUG
1651                         printk("CDU31A Warning: Read for block %d, expected %d\n",
1652                                  block, sony_next_block);
1653 #endif
1654                         abort_read();
1655                         if (!sony_toc_read) {
1656                                 printk("CDU31A: TOC not read\n");
1657                                 end_request(req, 0);
1658                                 continue;
1659                         }
1660                         if (start_request(block / 4, CDU31A_READAHEAD / 4, 0)) {
1661                                 printk("CDU31a: start request failed\n");
1662                                 end_request(req, 0);
1663                                 continue;
1664                         }
1665                 }
1666
1667                 read_data_block(req->buffer, block, nblock, res_reg, &res_size);
1668
1669                 if (res_reg[0] != 0x20) {
1670                         end_request(req, 1);
1671                         continue;
1672                 }
1673
1674                 if (num_retries > MAX_CDU31A_RETRIES) {
1675                         end_request(req, 0);
1676                         continue;
1677                 }
1678
1679                 num_retries++;
1680                 if (res_reg[1] == SONY_NOT_SPIN_ERR) {
1681                         do_sony_cd_cmd(SONY_SPIN_UP_CMD, NULL, 0, res_reg,
1682                                         &res_size);
1683                 } else {
1684                         printk("CDU31A: %s error for block %d, nblock %d\n",
1685                                  translate_error(res_reg[1]), block, nblock);
1686                 }
1687                 goto try_read_again;
1688         }
1689       end_do_cdu31a_request:
1690         spin_lock_irq(q->queue_lock);
1691 #if 0
1692         /* After finished, cancel any pending operations. */
1693         abort_read();
1694 #else
1695         /* Start a timer to time out after a while to disable
1696            the read. */
1697         cdu31a_abort_timer.expires = jiffies + 2 * HZ;  /* Wait 2 seconds */
1698         add_timer(&cdu31a_abort_timer);
1699 #endif
1700
1701         has_cd_task = NULL;
1702         sony_inuse = 0;
1703         wake_up_interruptible(&sony_wait);
1704         restore_flags(flags);
1705 #if DEBUG
1706         printk("Leaving do_cdu31a_request at %d\n", __LINE__);
1707 #endif
1708 }
1709
1710
1711 /*
1712  * Read the table of contents from the drive and set up TOC if
1713  * successful.
1714  */
1715 static void sony_get_toc(void)
1716 {
1717         unsigned char res_reg[2];
1718         unsigned int res_size;
1719         unsigned char parms[1];
1720         int session;
1721         int num_spin_ups;
1722         int totaltracks = 0;
1723         int mint = 99;
1724         int maxt = 0;
1725
1726 #if DEBUG
1727         printk("Entering sony_get_toc\n");
1728 #endif
1729
1730         num_spin_ups = 0;
1731         if (!sony_toc_read) {
1732               respinup_on_gettoc:
1733                 /* Ignore the result, since it might error if spinning already. */
1734                 do_sony_cd_cmd(SONY_SPIN_UP_CMD, NULL, 0, res_reg,
1735                                &res_size);
1736
1737                 do_sony_cd_cmd(SONY_READ_TOC_CMD, NULL, 0, res_reg,
1738                                &res_size);
1739
1740                 /* The drive sometimes returns error 0.  I don't know why, but ignore
1741                    it.  It seems to mean the drive has already done the operation. */
1742                 if ((res_size < 2)
1743                     || ((res_reg[0] != 0) && (res_reg[1] != 0))) {
1744                         /* If the drive is already playing, it's ok.  */
1745                         if ((res_reg[1] == SONY_AUDIO_PLAYING_ERR)
1746                             || (res_reg[1] == 0)) {
1747                                 goto gettoc_drive_spinning;
1748                         }
1749
1750                         /* If the drive says it is not spun up (even though we just did it!)
1751                            then retry the operation at least a few times. */
1752                         if ((res_reg[1] == SONY_NOT_SPIN_ERR)
1753                             && (num_spin_ups < MAX_CDU31A_RETRIES)) {
1754                                 num_spin_ups++;
1755                                 goto respinup_on_gettoc;
1756                         }
1757
1758                         printk("cdu31a: Error reading TOC: %x %s\n",
1759                                res_reg[0], translate_error(res_reg[1]));
1760                         return;
1761                 }
1762
1763               gettoc_drive_spinning:
1764
1765                 /* The idea here is we keep asking for sessions until the command
1766                    fails.  Then we know what the last valid session on the disk is.
1767                    No need to check session 0, since session 0 is the same as session
1768                    1; the command returns different information if you give it 0. 
1769                  */
1770 #if DEBUG
1771                 memset(&sony_toc, 0x0e, sizeof(sony_toc));
1772                 memset(&single_toc, 0x0f, sizeof(single_toc));
1773 #endif
1774                 session = 1;
1775                 while (1) {
1776 /* This seems to slow things down enough to make it work.  This
1777  * appears to be a problem in do_sony_cd_cmd.  This printk seems 
1778  * to address the symptoms...  -Erik */
1779 #if 1
1780                         printk("cdu31a: Trying session %d\n", session);
1781 #endif
1782                         parms[0] = session;
1783                         do_sony_cd_cmd(SONY_READ_TOC_SPEC_CMD,
1784                                        parms, 1, res_reg, &res_size);
1785
1786 #if DEBUG
1787                         printk("%2.2x %2.2x\n", res_reg[0], res_reg[1]);
1788 #endif
1789
1790                         if ((res_size < 2)
1791                             || ((res_reg[0] & 0xf0) == 0x20)) {
1792                                 /* An error reading the TOC, this must be past the last session. */
1793                                 if (session == 1)
1794                                         printk
1795                                             ("Yikes! Couldn't read any sessions!");
1796                                 break;
1797                         }
1798 #if DEBUG
1799                         printk("Reading session %d\n", session);
1800 #endif
1801
1802                         parms[0] = session;
1803                         do_sony_cd_cmd(SONY_REQ_TOC_DATA_SPEC_CMD,
1804                                        parms,
1805                                        1,
1806                                        (unsigned char *) &single_toc,
1807                                        &res_size);
1808                         if ((res_size < 2)
1809                             || ((single_toc.exec_status[0] & 0xf0) ==
1810                                 0x20)) {
1811                                 printk
1812                                     ("cdu31a: Error reading session %d: %x %s\n",
1813                                      session, single_toc.exec_status[0],
1814                                      translate_error(single_toc.
1815                                                      exec_status[1]));
1816                                 /* An error reading the TOC.  Return without sony_toc_read
1817                                    set. */
1818                                 return;
1819                         }
1820 #if DEBUG
1821                         printk
1822                             ("add0 %01x, con0 %01x, poi0 %02x, 1st trk %d, dsktyp %x, dum0 %x\n",
1823                              single_toc.address0, single_toc.control0,
1824                              single_toc.point0,
1825                              bcd_to_int(single_toc.first_track_num),
1826                              single_toc.disk_type, single_toc.dummy0);
1827                         printk
1828                             ("add1 %01x, con1 %01x, poi1 %02x, lst trk %d, dummy1 %x, dum2 %x\n",
1829                              single_toc.address1, single_toc.control1,
1830                              single_toc.point1,
1831                              bcd_to_int(single_toc.last_track_num),
1832                              single_toc.dummy1, single_toc.dummy2);
1833                         printk
1834                             ("add2 %01x, con2 %01x, poi2 %02x leadout start min %d, sec %d, frame %d\n",
1835                              single_toc.address2, single_toc.control2,
1836                              single_toc.point2,
1837                              bcd_to_int(single_toc.lead_out_start_msf[0]),
1838                              bcd_to_int(single_toc.lead_out_start_msf[1]),
1839                              bcd_to_int(single_toc.lead_out_start_msf[2]));
1840                         if (res_size > 18 && single_toc.pointb0 > 0xaf)
1841                                 printk
1842                                     ("addb0 %01x, conb0 %01x, poib0 %02x, nextsession min %d, sec %d, frame %d\n"
1843                                      "#mode5_ptrs %02d, max_start_outer_leadout_msf min %d, sec %d, frame %d\n",
1844                                      single_toc.addressb0,
1845                                      single_toc.controlb0,
1846                                      single_toc.pointb0,
1847                                      bcd_to_int(single_toc.
1848                                                 next_poss_prog_area_msf
1849                                                 [0]),
1850                                      bcd_to_int(single_toc.
1851                                                 next_poss_prog_area_msf
1852                                                 [1]),
1853                                      bcd_to_int(single_toc.
1854                                                 next_poss_prog_area_msf
1855                                                 [2]),
1856                                      single_toc.num_mode_5_pointers,
1857                                      bcd_to_int(single_toc.
1858                                                 max_start_outer_leadout_msf
1859                                                 [0]),
1860                                      bcd_to_int(single_toc.
1861                                                 max_start_outer_leadout_msf
1862                                                 [1]),
1863                                      bcd_to_int(single_toc.
1864                                                 max_start_outer_leadout_msf
1865                                                 [2]));
1866                         if (res_size > 27 && single_toc.pointb1 > 0xaf)
1867                                 printk
1868                                     ("addb1 %01x, conb1 %01x, poib1 %02x, %x %x %x %x #skipint_ptrs %d, #skiptrkassign %d %x\n",
1869                                      single_toc.addressb1,
1870                                      single_toc.controlb1,
1871                                      single_toc.pointb1,
1872                                      single_toc.dummyb0_1[0],
1873                                      single_toc.dummyb0_1[1],
1874                                      single_toc.dummyb0_1[2],
1875                                      single_toc.dummyb0_1[3],
1876                                      single_toc.num_skip_interval_pointers,
1877                                      single_toc.num_skip_track_assignments,
1878                                      single_toc.dummyb0_2);
1879                         if (res_size > 36 && single_toc.pointb2 > 0xaf)
1880                                 printk
1881                                     ("addb2 %01x, conb2 %01x, poib2 %02x, %02x %02x %02x %02x %02x %02x %02x\n",
1882                                      single_toc.addressb2,
1883                                      single_toc.controlb2,
1884                                      single_toc.pointb2,
1885                                      single_toc.tracksb2[0],
1886                                      single_toc.tracksb2[1],
1887                                      single_toc.tracksb2[2],
1888                                      single_toc.tracksb2[3],
1889                                      single_toc.tracksb2[4],
1890                                      single_toc.tracksb2[5],
1891                                      single_toc.tracksb2[6]);
1892                         if (res_size > 45 && single_toc.pointb3 > 0xaf)
1893                                 printk
1894                                     ("addb3 %01x, conb3 %01x, poib3 %02x, %02x %02x %02x %02x %02x %02x %02x\n",
1895                                      single_toc.addressb3,
1896                                      single_toc.controlb3,
1897                                      single_toc.pointb3,
1898                                      single_toc.tracksb3[0],
1899                                      single_toc.tracksb3[1],
1900                                      single_toc.tracksb3[2],
1901                                      single_toc.tracksb3[3],
1902                                      single_toc.tracksb3[4],
1903                                      single_toc.tracksb3[5],
1904                                      single_toc.tracksb3[6]);
1905                         if (res_size > 54 && single_toc.pointb4 > 0xaf)
1906                                 printk
1907                                     ("addb4 %01x, conb4 %01x, poib4 %02x, %02x %02x %02x %02x %02x %02x %02x\n",
1908                                      single_toc.addressb4,
1909                                      single_toc.controlb4,
1910                                      single_toc.pointb4,
1911                                      single_toc.tracksb4[0],
1912                                      single_toc.tracksb4[1],
1913                                      single_toc.tracksb4[2],
1914                                      single_toc.tracksb4[3],
1915                                      single_toc.tracksb4[4],
1916                                      single_toc.tracksb4[5],
1917                                      single_toc.tracksb4[6]);
1918                         if (res_size > 63 && single_toc.pointc0 > 0xaf)
1919                                 printk
1920                                     ("addc0 %01x, conc0 %01x, poic0 %02x, %02x %02x %02x %02x %02x %02x %02x\n",
1921                                      single_toc.addressc0,
1922                                      single_toc.controlc0,
1923                                      single_toc.pointc0,
1924                                      single_toc.dummyc0[0],
1925                                      single_toc.dummyc0[1],
1926                                      single_toc.dummyc0[2],
1927                                      single_toc.dummyc0[3],
1928                                      single_toc.dummyc0[4],
1929                                      single_toc.dummyc0[5],
1930                                      single_toc.dummyc0[6]);
1931 #endif
1932 #undef DEBUG
1933 #define DEBUG 0
1934
1935                         sony_toc.lead_out_start_msf[0] =
1936                             bcd_to_int(single_toc.lead_out_start_msf[0]);
1937                         sony_toc.lead_out_start_msf[1] =
1938                             bcd_to_int(single_toc.lead_out_start_msf[1]);
1939                         sony_toc.lead_out_start_msf[2] =
1940                             bcd_to_int(single_toc.lead_out_start_msf[2]);
1941                         sony_toc.lead_out_start_lba =
1942                             single_toc.lead_out_start_lba =
1943                             msf_to_log(sony_toc.lead_out_start_msf);
1944
1945                         /* For points that do not exist, move the data over them
1946                            to the right location. */
1947                         if (single_toc.pointb0 != 0xb0) {
1948                                 memmove(((char *) &single_toc) + 27,
1949                                         ((char *) &single_toc) + 18,
1950                                         res_size - 18);
1951                                 res_size += 9;
1952                         } else if (res_size > 18) {
1953                                 sony_toc.lead_out_start_msf[0] =
1954                                     bcd_to_int(single_toc.
1955                                                max_start_outer_leadout_msf
1956                                                [0]);
1957                                 sony_toc.lead_out_start_msf[1] =
1958                                     bcd_to_int(single_toc.
1959                                                max_start_outer_leadout_msf
1960                                                [1]);
1961                                 sony_toc.lead_out_start_msf[2] =
1962                                     bcd_to_int(single_toc.
1963                                                max_start_outer_leadout_msf
1964                                                [2]);
1965                                 sony_toc.lead_out_start_lba =
1966                                     msf_to_log(sony_toc.
1967                                                lead_out_start_msf);
1968                         }
1969                         if (single_toc.pointb1 != 0xb1) {
1970                                 memmove(((char *) &single_toc) + 36,
1971                                         ((char *) &single_toc) + 27,
1972                                         res_size - 27);
1973                                 res_size += 9;
1974                         }
1975                         if (single_toc.pointb2 != 0xb2) {
1976                                 memmove(((char *) &single_toc) + 45,
1977                                         ((char *) &single_toc) + 36,
1978                                         res_size - 36);
1979                                 res_size += 9;
1980                         }
1981                         if (single_toc.pointb3 != 0xb3) {
1982                                 memmove(((char *) &single_toc) + 54,
1983                                         ((char *) &single_toc) + 45,
1984                                         res_size - 45);
1985                                 res_size += 9;
1986                         }
1987                         if (single_toc.pointb4 != 0xb4) {
1988                                 memmove(((char *) &single_toc) + 63,
1989                                         ((char *) &single_toc) + 54,
1990                                         res_size - 54);
1991                                 res_size += 9;
1992                         }
1993                         if (single_toc.pointc0 != 0xc0) {
1994                                 memmove(((char *) &single_toc) + 72,
1995                                         ((char *) &single_toc) + 63,
1996                                         res_size - 63);
1997                                 res_size += 9;
1998                         }
1999 #if DEBUG
2000                         printk
2001                             ("start track lba %u,  leadout start lba %u\n",
2002                              single_toc.start_track_lba,
2003                              single_toc.lead_out_start_lba);
2004                         {
2005                                 int i;
2006                                 for (i = 0;
2007                                      i <
2008                                      1 +
2009                                      bcd_to_int(single_toc.last_track_num)
2010                                      -
2011                                      bcd_to_int(single_toc.
2012                                                 first_track_num); i++) {
2013                                         printk
2014                                             ("trk %02d: add 0x%01x, con 0x%01x,  track %02d, start min %02d, sec %02d, frame %02d\n",
2015                                              i,
2016                                              single_toc.tracks[i].address,
2017                                              single_toc.tracks[i].control,
2018                                              bcd_to_int(single_toc.
2019                                                         tracks[i].track),
2020                                              bcd_to_int(single_toc.
2021                                                         tracks[i].
2022                                                         track_start_msf
2023                                                         [0]),
2024                                              bcd_to_int(single_toc.
2025                                                         tracks[i].
2026                                                         track_start_msf
2027                                                         [1]),
2028                                              bcd_to_int(single_toc.
2029                                                         tracks[i].
2030                                                         track_start_msf
2031                                                         [2]));
2032                                         if (mint >
2033                                             bcd_to_int(single_toc.
2034                                                        tracks[i].track))
2035                                                 mint =
2036                                                     bcd_to_int(single_toc.
2037                                                                tracks[i].
2038                                                                track);
2039                                         if (maxt <
2040                                             bcd_to_int(single_toc.
2041                                                        tracks[i].track))
2042                                                 maxt =
2043                                                     bcd_to_int(single_toc.
2044                                                                tracks[i].
2045                                                                track);
2046                                 }
2047                                 printk
2048                                     ("min track number %d,   max track number %d\n",
2049                                      mint, maxt);
2050                         }
2051 #endif
2052
2053                         /* prepare a special table of contents for a CD-I disc. They don't have one. */
2054                         if (single_toc.disk_type == 0x10 &&
2055                             single_toc.first_track_num == 2 &&
2056                             single_toc.last_track_num == 2 /* CD-I */ ) {
2057                                 sony_toc.tracks[totaltracks].address = 1;
2058                                 sony_toc.tracks[totaltracks].control = 4;       /* force data tracks */
2059                                 sony_toc.tracks[totaltracks].track = 1;
2060                                 sony_toc.tracks[totaltracks].
2061                                     track_start_msf[0] = 0;
2062                                 sony_toc.tracks[totaltracks].
2063                                     track_start_msf[1] = 2;
2064                                 sony_toc.tracks[totaltracks].
2065                                     track_start_msf[2] = 0;
2066                                 mint = maxt = 1;
2067                                 totaltracks++;
2068                         } else
2069                                 /* gather track entries from this session */
2070                         {
2071                                 int i;
2072                                 for (i = 0;
2073                                      i <
2074                                      1 +
2075                                      bcd_to_int(single_toc.last_track_num)
2076                                      -
2077                                      bcd_to_int(single_toc.
2078                                                 first_track_num);
2079                                      i++, totaltracks++) {
2080                                         sony_toc.tracks[totaltracks].
2081                                             address =
2082                                             single_toc.tracks[i].address;
2083                                         sony_toc.tracks[totaltracks].
2084                                             control =
2085                                             single_toc.tracks[i].control;
2086                                         sony_toc.tracks[totaltracks].
2087                                             track =
2088                                             bcd_to_int(single_toc.
2089                                                        tracks[i].track);
2090                                         sony_toc.tracks[totaltracks].
2091                                             track_start_msf[0] =
2092                                             bcd_to_int(single_toc.
2093                                                        tracks[i].
2094                                                        track_start_msf[0]);
2095                                         sony_toc.tracks[totaltracks].
2096                                             track_start_msf[1] =
2097                                             bcd_to_int(single_toc.
2098                                                        tracks[i].
2099                                                        track_start_msf[1]);
2100                                         sony_toc.tracks[totaltracks].
2101                                             track_start_msf[2] =
2102                                             bcd_to_int(single_toc.
2103                                                        tracks[i].
2104                                                        track_start_msf[2]);
2105                                         if (i == 0)
2106                                                 single_toc.
2107                                                     start_track_lba =
2108                                                     msf_to_log(sony_toc.
2109                                                                tracks
2110                                                                [totaltracks].
2111                                                                track_start_msf);
2112                                         if (mint >
2113                                             sony_toc.tracks[totaltracks].
2114                                             track)
2115                                                 mint =
2116                                                     sony_toc.
2117                                                     tracks[totaltracks].
2118                                                     track;
2119                                         if (maxt <
2120                                             sony_toc.tracks[totaltracks].
2121                                             track)
2122                                                 maxt =
2123                                                     sony_toc.
2124                                                     tracks[totaltracks].
2125                                                     track;
2126                                 }
2127                         }
2128                         sony_toc.first_track_num = mint;
2129                         sony_toc.last_track_num = maxt;
2130                         /* Disk type of last session wins. For example:
2131                            CD-Extra has disk type 0 for the first session, so
2132                            a dumb HiFi CD player thinks it is a plain audio CD.
2133                            We are interested in the disk type of the last session,
2134                            which is 0x20 (XA) for CD-Extra, so we can access the
2135                            data track ... */
2136                         sony_toc.disk_type = single_toc.disk_type;
2137                         sony_toc.sessions = session;
2138
2139                         /* don't believe everything :-) */
2140                         if (session == 1)
2141                                 single_toc.start_track_lba = 0;
2142                         sony_toc.start_track_lba =
2143                             single_toc.start_track_lba;
2144
2145                         if (session > 1 && single_toc.pointb0 == 0xb0 &&
2146                             sony_toc.lead_out_start_lba ==
2147                             single_toc.lead_out_start_lba) {
2148                                 break;
2149                         }
2150
2151                         /* Let's not get carried away... */
2152                         if (session > 40) {
2153                                 printk("cdu31a: too many sessions: %d\n",
2154                                        session);
2155                                 break;
2156                         }
2157                         session++;
2158                 }
2159                 sony_toc.track_entries = totaltracks;
2160                 /* add one entry for the LAST track with track number CDROM_LEADOUT */
2161                 sony_toc.tracks[totaltracks].address = single_toc.address2;
2162                 sony_toc.tracks[totaltracks].control = single_toc.control2;
2163                 sony_toc.tracks[totaltracks].track = CDROM_LEADOUT;
2164                 sony_toc.tracks[totaltracks].track_start_msf[0] =
2165                     sony_toc.lead_out_start_msf[0];
2166                 sony_toc.tracks[totaltracks].track_start_msf[1] =
2167                     sony_toc.lead_out_start_msf[1];
2168                 sony_toc.tracks[totaltracks].track_start_msf[2] =
2169                     sony_toc.lead_out_start_msf[2];
2170
2171                 sony_toc_read = 1;
2172 #undef DEBUG
2173 #if DEBUG
2174                 printk
2175                     ("Disk session %d, start track: %d, stop track: %d\n",
2176                      session, single_toc.start_track_lba,
2177                      single_toc.lead_out_start_lba);
2178 #endif
2179         }
2180 #if DEBUG
2181         printk("Leaving sony_get_toc\n");
2182 #endif
2183 }
2184
2185
2186 /*
2187  * Uniform cdrom interface function
2188  * return multisession offset and sector information
2189  */
2190 static int scd_get_last_session(struct cdrom_device_info *cdi,
2191                                 struct cdrom_multisession *ms_info)
2192 {
2193         if (ms_info == NULL)
2194                 return 1;
2195
2196         if (!sony_toc_read)
2197                 sony_get_toc();
2198
2199         ms_info->addr_format = CDROM_LBA;
2200         ms_info->addr.lba = sony_toc.start_track_lba;
2201         ms_info->xa_flag = sony_toc.disk_type == SONY_XA_DISK_TYPE ||
2202             sony_toc.disk_type == 0x10 /* CDI */ ;
2203
2204         return 0;
2205 }
2206
2207 /*
2208  * Search for a specific track in the table of contents.
2209  */
2210 static int find_track(int track)
2211 {
2212         int i;
2213
2214         for (i = 0; i <= sony_toc.track_entries; i++) {
2215                 if (sony_toc.tracks[i].track == track) {
2216                         return i;
2217                 }
2218         }
2219
2220         return -1;
2221 }
2222
2223
2224 /*
2225  * Read the subcode and put it in last_sony_subcode for future use.
2226  */
2227 static int read_subcode(void)
2228 {
2229         unsigned int res_size;
2230
2231
2232         do_sony_cd_cmd(SONY_REQ_SUBCODE_ADDRESS_CMD,
2233                        NULL,
2234                        0, (unsigned char *) &last_sony_subcode, &res_size);
2235         if ((res_size < 2)
2236             || ((last_sony_subcode.exec_status[0] & 0xf0) == 0x20)) {
2237                 printk("Sony CDROM error %s (read_subcode)\n",
2238                        translate_error(last_sony_subcode.exec_status[1]));
2239                 return -EIO;
2240         }
2241
2242         last_sony_subcode.track_num =
2243             bcd_to_int(last_sony_subcode.track_num);
2244         last_sony_subcode.index_num =
2245             bcd_to_int(last_sony_subcode.index_num);
2246         last_sony_subcode.abs_msf[0] =
2247             bcd_to_int(last_sony_subcode.abs_msf[0]);
2248         last_sony_subcode.abs_msf[1] =
2249             bcd_to_int(last_sony_subcode.abs_msf[1]);
2250         last_sony_subcode.abs_msf[2] =
2251             bcd_to_int(last_sony_subcode.abs_msf[2]);
2252
2253         last_sony_subcode.rel_msf[0] =
2254             bcd_to_int(last_sony_subcode.rel_msf[0]);
2255         last_sony_subcode.rel_msf[1] =
2256             bcd_to_int(last_sony_subcode.rel_msf[1]);
2257         last_sony_subcode.rel_msf[2] =
2258             bcd_to_int(last_sony_subcode.rel_msf[2]);
2259         return 0;
2260 }
2261
2262 /*
2263  * Uniform cdrom interface function
2264  * return the media catalog number found on some older audio cds
2265  */
2266 static int
2267 scd_get_mcn(struct cdrom_device_info *cdi, struct cdrom_mcn *mcn)
2268 {
2269         unsigned char resbuffer[2 + 14];
2270         unsigned char *mcnp = mcn->medium_catalog_number;
2271         unsigned char *resp = resbuffer + 3;
2272         unsigned int res_size;
2273
2274         memset(mcn->medium_catalog_number, 0, 14);
2275         do_sony_cd_cmd(SONY_REQ_UPC_EAN_CMD,
2276                        NULL, 0, resbuffer, &res_size);
2277         if ((res_size < 2) || ((resbuffer[0] & 0xf0) == 0x20));
2278         else {
2279                 /* packed bcd to single ASCII digits */
2280                 *mcnp++ = (*resp >> 4) + '0';
2281                 *mcnp++ = (*resp++ & 0x0f) + '0';
2282                 *mcnp++ = (*resp >> 4) + '0';
2283                 *mcnp++ = (*resp++ & 0x0f) + '0';
2284                 *mcnp++ = (*resp >> 4) + '0';
2285                 *mcnp++ = (*resp++ & 0x0f) + '0';
2286                 *mcnp++ = (*resp >> 4) + '0';
2287                 *mcnp++ = (*resp++ & 0x0f) + '0';
2288                 *mcnp++ = (*resp >> 4) + '0';
2289                 *mcnp++ = (*resp++ & 0x0f) + '0';
2290                 *mcnp++ = (*resp >> 4) + '0';
2291                 *mcnp++ = (*resp++ & 0x0f) + '0';
2292                 *mcnp++ = (*resp >> 4) + '0';
2293         }
2294         *mcnp = '\0';
2295         return 0;
2296 }
2297
2298
2299 /*
2300  * Get the subchannel info like the CDROMSUBCHNL command wants to see it.  If
2301  * the drive is playing, the subchannel needs to be read (since it would be
2302  * changing).  If the drive is paused or completed, the subcode information has
2303  * already been stored, just use that.  The ioctl call wants things in decimal
2304  * (not BCD), so all the conversions are done.
2305  */
2306 static int sony_get_subchnl_info(struct cdrom_subchnl *schi)
2307 {
2308         /* Get attention stuff */
2309         while (handle_sony_cd_attention());
2310
2311         sony_get_toc();
2312         if (!sony_toc_read) {
2313                 return -EIO;
2314         }
2315
2316         switch (sony_audio_status) {
2317         case CDROM_AUDIO_NO_STATUS:
2318         case CDROM_AUDIO_PLAY:
2319                 if (read_subcode() < 0) {
2320                         return -EIO;
2321                 }
2322                 break;
2323
2324         case CDROM_AUDIO_PAUSED:
2325         case CDROM_AUDIO_COMPLETED:
2326                 break;
2327
2328 #if 0
2329         case CDROM_AUDIO_NO_STATUS:
2330                 schi->cdsc_audiostatus = sony_audio_status;
2331                 return 0;
2332                 break;
2333 #endif
2334         case CDROM_AUDIO_INVALID:
2335         case CDROM_AUDIO_ERROR:
2336         default:
2337                 return -EIO;
2338         }
2339
2340         schi->cdsc_audiostatus = sony_audio_status;
2341         schi->cdsc_adr = last_sony_subcode.address;
2342         schi->cdsc_ctrl = last_sony_subcode.control;
2343         schi->cdsc_trk = last_sony_subcode.track_num;
2344         schi->cdsc_ind = last_sony_subcode.index_num;
2345         if (schi->cdsc_format == CDROM_MSF) {
2346                 schi->cdsc_absaddr.msf.minute =
2347                     last_sony_subcode.abs_msf[0];
2348                 schi->cdsc_absaddr.msf.second =
2349                     last_sony_subcode.abs_msf[1];
2350                 schi->cdsc_absaddr.msf.frame =
2351                     last_sony_subcode.abs_msf[2];
2352
2353                 schi->cdsc_reladdr.msf.minute =
2354                     last_sony_subcode.rel_msf[0];
2355                 schi->cdsc_reladdr.msf.second =
2356                     last_sony_subcode.rel_msf[1];
2357                 schi->cdsc_reladdr.msf.frame =
2358                     last_sony_subcode.rel_msf[2];
2359         } else if (schi->cdsc_format == CDROM_LBA) {
2360                 schi->cdsc_absaddr.lba =
2361                     msf_to_log(last_sony_subcode.abs_msf);
2362                 schi->cdsc_reladdr.lba =
2363                     msf_to_log(last_sony_subcode.rel_msf);
2364         }
2365
2366         return 0;
2367 }
2368
2369 /* Get audio data from the drive.  This is fairly complex because I
2370    am looking for status and data at the same time, but if I get status
2371    then I just look for data.  I need to get the status immediately so
2372    the switch from audio to data tracks will happen quickly. */
2373 static void
2374 read_audio_data(char *buffer, unsigned char res_reg[], int *res_size)
2375 {
2376         unsigned long retry_count;
2377         int result_read;
2378
2379
2380         res_reg[0] = 0;
2381         res_reg[1] = 0;
2382         *res_size = 0;
2383         result_read = 0;
2384
2385         /* Wait for the drive to tell us we have something */
2386         retry_count = jiffies + SONY_JIFFIES_TIMEOUT;
2387       continue_read_audio_wait:
2388         while (time_before(jiffies, retry_count) && !(is_data_ready())
2389                && !(is_result_ready() || result_read)) {
2390                 while (handle_sony_cd_attention());
2391
2392                 sony_sleep();
2393         }
2394         if (!(is_data_ready())) {
2395                 if (is_result_ready() && !result_read) {
2396                         get_result(res_reg, res_size);
2397
2398                         /* Read block status and continue waiting for data. */
2399                         if ((res_reg[0] & 0xf0) == 0x50) {
2400                                 result_read = 1;
2401                                 goto continue_read_audio_wait;
2402                         }
2403                         /* Invalid data from the drive.  Shut down the operation. */
2404                         else if ((res_reg[0] & 0xf0) != 0x20) {
2405                                 printk
2406                                     ("CDU31A: Got result that should have been error: %d\n",
2407                                      res_reg[0]);
2408                                 res_reg[0] = 0x20;
2409                                 res_reg[1] = SONY_BAD_DATA_ERR;
2410                                 *res_size = 2;
2411                         }
2412                         abort_read();
2413                 } else {
2414 #if DEBUG
2415                         printk("CDU31A timeout out %d\n", __LINE__);
2416 #endif
2417                         res_reg[0] = 0x20;
2418                         res_reg[1] = SONY_TIMEOUT_OP_ERR;
2419                         *res_size = 2;
2420                         abort_read();
2421                 }
2422         } else {
2423                 clear_data_ready();
2424
2425                 /* If data block, then get 2340 bytes offset by 12. */
2426                 if (sony_raw_data_mode) {
2427                         insb(sony_cd_read_reg, buffer + CD_XA_HEAD,
2428                              CD_FRAMESIZE_RAW1);
2429                 } else {
2430                         /* Audio gets the whole 2352 bytes. */
2431                         insb(sony_cd_read_reg, buffer, CD_FRAMESIZE_RAW);
2432                 }
2433
2434                 /* If I haven't already gotten the result, get it now. */
2435                 if (!result_read) {
2436                         /* Wait for the drive to tell us we have something */
2437                         retry_count = jiffies + SONY_JIFFIES_TIMEOUT;
2438                         while (time_before(jiffies, retry_count)
2439                                && !(is_result_ready())) {
2440                                 while (handle_sony_cd_attention());
2441
2442                                 sony_sleep();
2443                         }
2444
2445                         if (!is_result_ready()) {
2446 #if DEBUG
2447                                 printk("CDU31A timeout out %d\n",
2448                                        __LINE__);
2449 #endif
2450                                 res_reg[0] = 0x20;
2451                                 res_reg[1] = SONY_TIMEOUT_OP_ERR;
2452                                 *res_size = 2;
2453                                 abort_read();
2454                                 return;
2455                         } else {
2456                                 get_result(res_reg, res_size);
2457                         }
2458                 }
2459
2460                 if ((res_reg[0] & 0xf0) == 0x50) {
2461                         if ((res_reg[0] == SONY_NO_CIRC_ERR_BLK_STAT)
2462                             || (res_reg[0] == SONY_NO_LECC_ERR_BLK_STAT)
2463                             || (res_reg[0] == SONY_RECOV_LECC_ERR_BLK_STAT)
2464                             || (res_reg[0] == SONY_NO_ERR_DETECTION_STAT)) {
2465                                 /* Ok, nothing to do. */
2466                         } else {
2467                                 printk("CDU31A: Data block error: 0x%x\n",
2468                                        res_reg[0]);
2469                                 res_reg[0] = 0x20;
2470                                 res_reg[1] = SONY_BAD_DATA_ERR;
2471                                 *res_size = 2;
2472                         }
2473                 } else if ((res_reg[0] & 0xf0) != 0x20) {
2474                         /* The drive gave me bad status, I don't know what to do.
2475                            Reset the driver and return an error. */
2476                         printk("CDU31A: Invalid block status: 0x%x\n",
2477                                res_reg[0]);
2478                         restart_on_error();
2479                         res_reg[0] = 0x20;
2480                         res_reg[1] = SONY_BAD_DATA_ERR;
2481                         *res_size = 2;
2482                 }
2483         }
2484 }
2485
2486 /* Perform a raw data read.  This will automatically detect the
2487    track type and read the proper data (audio or data). */
2488 static int read_audio(struct cdrom_read_audio *ra)
2489 {
2490         int retval;
2491         unsigned char params[2];
2492         unsigned char res_reg[12];
2493         unsigned int res_size;
2494         unsigned int cframe;
2495         unsigned long flags;
2496
2497         /* 
2498          * Make sure no one else is using the driver; wait for them
2499          * to finish if it is so.
2500          */
2501         save_flags(flags);
2502         cli();
2503         while (sony_inuse) {
2504                 interruptible_sleep_on(&sony_wait);
2505                 if (signal_pending(current)) {
2506                         restore_flags(flags);
2507                         return -EAGAIN;
2508                 }
2509         }
2510         sony_inuse = 1;
2511         has_cd_task = current;
2512         restore_flags(flags);
2513
2514         if (!sony_spun_up) {
2515                 scd_spinup();
2516         }
2517
2518         /* Set the drive to do raw operations. */
2519         params[0] = SONY_SD_DECODE_PARAM;
2520         params[1] = 0x06 | sony_raw_data_mode;
2521         do_sony_cd_cmd(SONY_SET_DRIVE_PARAM_CMD,
2522                        params, 2, res_reg, &res_size);
2523         if ((res_size < 2) || ((res_reg[0] & 0xf0) == 0x20)) {
2524                 printk("CDU31A: Unable to set decode params: 0x%2.2x\n",
2525                        res_reg[1]);
2526                 return -EIO;
2527         }
2528
2529         /* From here down, we have to goto exit_read_audio instead of returning
2530            because the drive parameters have to be set back to data before
2531            return. */
2532
2533         retval = 0;
2534         /* start_request clears out any readahead data, so it should be safe. */
2535         if (start_request(ra->addr.lba, ra->nframes, 1)) {
2536                 retval = -EIO;
2537                 goto exit_read_audio;
2538         }
2539
2540         /* For every requested frame. */
2541         cframe = 0;
2542         while (cframe < ra->nframes) {
2543                 read_audio_data(readahead_buffer, res_reg, &res_size);
2544                 if ((res_reg[0] & 0xf0) == 0x20) {
2545                         if (res_reg[1] == SONY_BAD_DATA_ERR) {
2546                                 printk
2547                                     ("CDU31A: Data error on audio sector %d\n",
2548                                      ra->addr.lba + cframe);
2549                         } else if (res_reg[1] == SONY_ILL_TRACK_R_ERR) {
2550                                 /* Illegal track type, change track types and start over. */
2551                                 sony_raw_data_mode =
2552                                     (sony_raw_data_mode) ? 0 : 1;
2553
2554                                 /* Set the drive mode. */
2555                                 params[0] = SONY_SD_DECODE_PARAM;
2556                                 params[1] = 0x06 | sony_raw_data_mode;
2557                                 do_sony_cd_cmd(SONY_SET_DRIVE_PARAM_CMD,
2558                                                params,
2559                                                2, res_reg, &res_size);
2560                                 if ((res_size < 2)
2561                                     || ((res_reg[0] & 0xf0) == 0x20)) {
2562                                         printk
2563                                             ("CDU31A: Unable to set decode params: 0x%2.2x\n",
2564                                              res_reg[1]);
2565                                         retval = -EIO;
2566                                         goto exit_read_audio;
2567                                 }
2568
2569                                 /* Restart the request on the current frame. */
2570                                 if (start_request
2571                                     (ra->addr.lba + cframe,
2572                                      ra->nframes - cframe, 1)) {
2573                                         retval = -EIO;
2574                                         goto exit_read_audio;
2575                                 }
2576
2577                                 /* Don't go back to the top because don't want to get into
2578                                    and infinite loop.  A lot of code gets duplicated, but
2579                                    that's no big deal, I don't guess. */
2580                                 read_audio_data(readahead_buffer, res_reg,
2581                                                 &res_size);
2582                                 if ((res_reg[0] & 0xf0) == 0x20) {
2583                                         if (res_reg[1] ==
2584                                             SONY_BAD_DATA_ERR) {
2585                                                 printk
2586                                                     ("CDU31A: Data error on audio sector %d\n",
2587                                                      ra->addr.lba +
2588                                                      cframe);
2589                                         } else {
2590                                                 printk
2591                                                     ("CDU31A: Error reading audio data on sector %d: %s\n",
2592                                                      ra->addr.lba + cframe,
2593                                                      translate_error
2594                                                      (res_reg[1]));
2595                                                 retval = -EIO;
2596                                                 goto exit_read_audio;
2597                                         }
2598                                 } else if (copy_to_user((char *)(ra->buf +
2599                                                                (CD_FRAMESIZE_RAW
2600                                                                 * cframe)),
2601                                                         (char *)
2602                                                                readahead_buffer,
2603                                                         CD_FRAMESIZE_RAW)) {
2604                                         retval = -EFAULT;
2605                                         goto exit_read_audio;
2606                                 }
2607                         } else {
2608                                 printk
2609                                     ("CDU31A: Error reading audio data on sector %d: %s\n",
2610                                      ra->addr.lba + cframe,
2611                                      translate_error(res_reg[1]));
2612                                 retval = -EIO;
2613                                 goto exit_read_audio;
2614                         }
2615                 } else if (copy_to_user((char *)(ra->buf + (CD_FRAMESIZE_RAW *
2616                                                             cframe)),
2617                                         (char *)readahead_buffer,
2618                                         CD_FRAMESIZE_RAW)) {
2619                         retval = -EFAULT;
2620                         goto exit_read_audio;
2621                 }
2622
2623                 cframe++;
2624         }
2625
2626         get_result(res_reg, &res_size);
2627         if ((res_reg[0] & 0xf0) == 0x20) {
2628                 printk("CDU31A: Error return from audio read: %s\n",
2629                        translate_error(res_reg[1]));
2630                 retval = -EIO;
2631                 goto exit_read_audio;
2632         }
2633
2634       exit_read_audio:
2635
2636         /* Set the drive mode back to the proper one for the disk. */
2637         params[0] = SONY_SD_DECODE_PARAM;
2638         if (!sony_xa_mode) {
2639                 params[1] = 0x0f;
2640         } else {
2641                 params[1] = 0x07;
2642         }
2643         do_sony_cd_cmd(SONY_SET_DRIVE_PARAM_CMD,
2644                        params, 2, res_reg, &res_size);
2645         if ((res_size < 2) || ((res_reg[0] & 0xf0) == 0x20)) {
2646                 printk("CDU31A: Unable to reset decode params: 0x%2.2x\n",
2647                        res_reg[1]);
2648                 return -EIO;
2649         }
2650
2651         has_cd_task = NULL;
2652         sony_inuse = 0;
2653         wake_up_interruptible(&sony_wait);
2654
2655         return (retval);
2656 }
2657
2658 static int
2659 do_sony_cd_cmd_chk(const char *name,
2660                    unsigned char cmd,
2661                    unsigned char *params,
2662                    unsigned int num_params,
2663                    unsigned char *result_buffer, unsigned int *result_size)
2664 {
2665         do_sony_cd_cmd(cmd, params, num_params, result_buffer,
2666                        result_size);
2667         if ((*result_size < 2) || ((result_buffer[0] & 0xf0) == 0x20)) {
2668                 printk("Sony CDROM error %s (CDROM%s)\n",
2669                        translate_error(result_buffer[1]), name);
2670                 return -EIO;
2671         }
2672         return 0;
2673 }
2674
2675 /*
2676  * Uniform cdrom interface function
2677  * open the tray
2678  */
2679 static int scd_tray_move(struct cdrom_device_info *cdi, int position)
2680 {
2681         if (position == 1 /* open tray */ ) {
2682                 unsigned char res_reg[12];
2683                 unsigned int res_size;
2684
2685                 do_sony_cd_cmd(SONY_AUDIO_STOP_CMD, NULL, 0, res_reg,
2686                                &res_size);
2687                 do_sony_cd_cmd(SONY_SPIN_DOWN_CMD, NULL, 0, res_reg,
2688                                &res_size);
2689
2690                 sony_audio_status = CDROM_AUDIO_INVALID;
2691                 return do_sony_cd_cmd_chk("EJECT", SONY_EJECT_CMD, NULL, 0,
2692                                           res_reg, &res_size);
2693         } else {
2694                 if (0 == scd_spinup())
2695                         sony_spun_up = 1;
2696                 return 0;
2697         }
2698 }
2699
2700 /*
2701  * The big ugly ioctl handler.
2702  */
2703 static int scd_audio_ioctl(struct cdrom_device_info *cdi,
2704                            unsigned int cmd, void *arg)
2705 {
2706         unsigned char res_reg[12];
2707         unsigned int res_size;
2708         unsigned char params[7];
2709         int i;
2710
2711
2712         switch (cmd) {
2713         case CDROMSTART:        /* Spin up the drive */
2714                 return do_sony_cd_cmd_chk("START", SONY_SPIN_UP_CMD, NULL,
2715                                           0, res_reg, &res_size);
2716                 break;
2717
2718         case CDROMSTOP: /* Spin down the drive */
2719                 do_sony_cd_cmd(SONY_AUDIO_STOP_CMD, NULL, 0, res_reg,
2720                                &res_size);
2721
2722                 /*
2723                  * Spin the drive down, ignoring the error if the disk was
2724                  * already not spinning.
2725                  */
2726                 sony_audio_status = CDROM_AUDIO_NO_STATUS;
2727                 return do_sony_cd_cmd_chk("STOP", SONY_SPIN_DOWN_CMD, NULL,
2728                                           0, res_reg, &res_size);
2729
2730         case CDROMPAUSE:        /* Pause the drive */
2731                 if (do_sony_cd_cmd_chk
2732                     ("PAUSE", SONY_AUDIO_STOP_CMD, NULL, 0, res_reg,
2733                      &res_size))
2734                         return -EIO;
2735                 /* Get the current position and save it for resuming */
2736                 if (read_subcode() < 0) {
2737                         return -EIO;
2738                 }
2739                 cur_pos_msf[0] = last_sony_subcode.abs_msf[0];
2740                 cur_pos_msf[1] = last_sony_subcode.abs_msf[1];
2741                 cur_pos_msf[2] = last_sony_subcode.abs_msf[2];
2742                 sony_audio_status = CDROM_AUDIO_PAUSED;
2743                 return 0;
2744                 break;
2745
2746         case CDROMRESUME:       /* Start the drive after being paused */
2747                 if (sony_audio_status != CDROM_AUDIO_PAUSED) {
2748                         return -EINVAL;
2749                 }
2750
2751                 do_sony_cd_cmd(SONY_SPIN_UP_CMD, NULL, 0, res_reg,
2752                                &res_size);
2753
2754                 /* Start the drive at the saved position. */
2755                 params[1] = int_to_bcd(cur_pos_msf[0]);
2756                 params[2] = int_to_bcd(cur_pos_msf[1]);
2757                 params[3] = int_to_bcd(cur_pos_msf[2]);
2758                 params[4] = int_to_bcd(final_pos_msf[0]);
2759                 params[5] = int_to_bcd(final_pos_msf[1]);
2760                 params[6] = int_to_bcd(final_pos_msf[2]);
2761                 params[0] = 0x03;
2762                 if (do_sony_cd_cmd_chk
2763                     ("RESUME", SONY_AUDIO_PLAYBACK_CMD, params, 7, res_reg,
2764                      &res_size) < 0)
2765                         return -EIO;
2766                 sony_audio_status = CDROM_AUDIO_PLAY;
2767                 return 0;
2768
2769         case CDROMPLAYMSF:      /* Play starting at the given MSF address. */
2770                 do_sony_cd_cmd(SONY_SPIN_UP_CMD, NULL, 0, res_reg,
2771                                &res_size);
2772
2773                 /* The parameters are given in int, must be converted */
2774                 for (i = 1; i < 7; i++) {
2775                         params[i] =
2776                             int_to_bcd(((unsigned char *) arg)[i - 1]);
2777                 }
2778                 params[0] = 0x03;
2779                 if (do_sony_cd_cmd_chk
2780                     ("PLAYMSF", SONY_AUDIO_PLAYBACK_CMD, params, 7,
2781                      res_reg, &res_size) < 0)
2782                         return -EIO;
2783
2784                 /* Save the final position for pauses and resumes */
2785                 final_pos_msf[0] = bcd_to_int(params[4]);
2786                 final_pos_msf[1] = bcd_to_int(params[5]);
2787                 final_pos_msf[2] = bcd_to_int(params[6]);
2788                 sony_audio_status = CDROM_AUDIO_PLAY;
2789                 return 0;
2790
2791         case CDROMREADTOCHDR:   /* Read the table of contents header */
2792                 {
2793                         struct cdrom_tochdr *hdr;
2794
2795                         sony_get_toc();
2796                         if (!sony_toc_read) {
2797                                 return -EIO;
2798                         }
2799
2800                         hdr = (struct cdrom_tochdr *) arg;
2801                         hdr->cdth_trk0 = sony_toc.first_track_num;
2802                         hdr->cdth_trk1 = sony_toc.last_track_num;
2803                 }
2804                 return 0;
2805
2806         case CDROMREADTOCENTRY: /* Read a given table of contents entry */
2807                 {
2808                         struct cdrom_tocentry *entry;
2809                         int track_idx;
2810                         unsigned char *msf_val = NULL;
2811
2812                         sony_get_toc();
2813                         if (!sony_toc_read) {
2814                                 return -EIO;
2815                         }
2816
2817                         entry = (struct cdrom_tocentry *) arg;
2818
2819                         track_idx = find_track(entry->cdte_track);
2820                         if (track_idx < 0) {
2821                                 return -EINVAL;
2822                         }
2823
2824                         entry->cdte_adr =
2825                             sony_toc.tracks[track_idx].address;
2826                         entry->cdte_ctrl =
2827                             sony_toc.tracks[track_idx].control;
2828                         msf_val =
2829                             sony_toc.tracks[track_idx].track_start_msf;
2830
2831                         /* Logical buffer address or MSF format requested? */
2832                         if (entry->cdte_format == CDROM_LBA) {
2833                                 entry->cdte_addr.lba = msf_to_log(msf_val);
2834                         } else if (entry->cdte_format == CDROM_MSF) {
2835                                 entry->cdte_addr.msf.minute = *msf_val;
2836                                 entry->cdte_addr.msf.second =
2837                                     *(msf_val + 1);
2838                                 entry->cdte_addr.msf.frame =
2839                                     *(msf_val + 2);
2840                         }
2841                 }
2842                 return 0;
2843                 break;
2844
2845         case CDROMPLAYTRKIND:   /* Play a track.  This currently ignores index. */
2846                 {
2847                         struct cdrom_ti *ti = (struct cdrom_ti *) arg;
2848                         int track_idx;
2849
2850                         sony_get_toc();
2851                         if (!sony_toc_read) {
2852                                 return -EIO;
2853                         }
2854
2855                         if ((ti->cdti_trk0 < sony_toc.first_track_num)
2856                             || (ti->cdti_trk0 > sony_toc.last_track_num)
2857                             || (ti->cdti_trk1 < ti->cdti_trk0)) {
2858                                 return -EINVAL;
2859                         }
2860
2861                         track_idx = find_track(ti->cdti_trk0);
2862                         if (track_idx < 0) {
2863                                 return -EINVAL;
2864                         }
2865                         params[1] =
2866                             int_to_bcd(sony_toc.tracks[track_idx].
2867                                        track_start_msf[0]);
2868                         params[2] =
2869                             int_to_bcd(sony_toc.tracks[track_idx].
2870                                        track_start_msf[1]);
2871                         params[3] =
2872                             int_to_bcd(sony_toc.tracks[track_idx].
2873                                        track_start_msf[2]);
2874
2875                         /*
2876                          * If we want to stop after the last track, use the lead-out
2877                          * MSF to do that.
2878                          */
2879                         if (ti->cdti_trk1 >= sony_toc.last_track_num) {
2880                                 track_idx = find_track(CDROM_LEADOUT);
2881                         } else {
2882                                 track_idx = find_track(ti->cdti_trk1 + 1);
2883                         }
2884                         if (track_idx < 0) {
2885                                 return -EINVAL;
2886                         }
2887                         params[4] =
2888                             int_to_bcd(sony_toc.tracks[track_idx].
2889                                        track_start_msf[0]);
2890                         params[5] =
2891                             int_to_bcd(sony_toc.tracks[track_idx].
2892                                        track_start_msf[1]);
2893                         params[6] =
2894                             int_to_bcd(sony_toc.tracks[track_idx].
2895                                        track_start_msf[2]);
2896                         params[0] = 0x03;
2897
2898                         do_sony_cd_cmd(SONY_SPIN_UP_CMD, NULL, 0, res_reg,
2899                                        &res_size);
2900
2901                         do_sony_cd_cmd(SONY_AUDIO_PLAYBACK_CMD, params, 7,
2902                                        res_reg, &res_size);
2903
2904                         if ((res_size < 2)
2905                             || ((res_reg[0] & 0xf0) == 0x20)) {
2906                                 printk("Params: %x %x %x %x %x %x %x\n",
2907                                        params[0], params[1], params[2],
2908                                        params[3], params[4], params[5],
2909                                        params[6]);
2910                                 printk
2911                                     ("Sony CDROM error %s (CDROMPLAYTRKIND)\n",
2912                                      translate_error(res_reg[1]));
2913                                 return -EIO;
2914                         }
2915
2916                         /* Save the final position for pauses and resumes */
2917                         final_pos_msf[0] = bcd_to_int(params[4]);
2918                         final_pos_msf[1] = bcd_to_int(params[5]);
2919                         final_pos_msf[2] = bcd_to_int(params[6]);
2920                         sony_audio_status = CDROM_AUDIO_PLAY;
2921                         return 0;
2922                 }
2923
2924         case CDROMVOLCTRL:      /* Volume control.  What volume does this change, anyway? */
2925                 {
2926                         struct cdrom_volctrl *volctrl =
2927                             (struct cdrom_volctrl *) arg;
2928
2929                         params[0] = SONY_SD_AUDIO_VOLUME;
2930                         params[1] = volctrl->channel0;
2931                         params[2] = volctrl->channel1;
2932                         return do_sony_cd_cmd_chk("VOLCTRL",
2933                                                   SONY_SET_DRIVE_PARAM_CMD,
2934                                                   params, 3, res_reg,
2935                                                   &res_size);
2936                 }
2937         case CDROMSUBCHNL:      /* Get subchannel info */
2938                 return sony_get_subchnl_info((struct cdrom_subchnl *) arg);
2939
2940         default:
2941                 return -EINVAL;
2942         }
2943 }
2944
2945 static int scd_dev_ioctl(struct cdrom_device_info *cdi,
2946                          unsigned int cmd, unsigned long arg)
2947 {
2948         int i;
2949
2950         switch (cmd) {
2951         case CDROMREADAUDIO:    /* Read 2352 byte audio tracks and 2340 byte
2952                                    raw data tracks. */
2953                 {
2954                         struct cdrom_read_audio ra;
2955
2956
2957                         sony_get_toc();
2958                         if (!sony_toc_read) {
2959                                 return -EIO;
2960                         }
2961
2962                         if (copy_from_user(&ra, (char *) arg, sizeof(ra)))
2963                                 return -EFAULT;
2964
2965                         if (ra.nframes == 0) {
2966                                 return 0;
2967                         }
2968
2969                         i = verify_area(VERIFY_WRITE, ra.buf,
2970                                         CD_FRAMESIZE_RAW * ra.nframes);
2971                         if (i < 0)
2972                                 return i;
2973
2974                         if (ra.addr_format == CDROM_LBA) {
2975                                 if ((ra.addr.lba >=
2976                                      sony_toc.lead_out_start_lba)
2977                                     || (ra.addr.lba + ra.nframes >=
2978                                         sony_toc.lead_out_start_lba)) {
2979                                         return -EINVAL;
2980                                 }
2981                         } else if (ra.addr_format == CDROM_MSF) {
2982                                 if ((ra.addr.msf.minute >= 75)
2983                                     || (ra.addr.msf.second >= 60)
2984                                     || (ra.addr.msf.frame >= 75)) {
2985                                         return -EINVAL;
2986                                 }
2987
2988                                 ra.addr.lba = ((ra.addr.msf.minute * 4500)
2989                                                + (ra.addr.msf.second * 75)
2990                                                + ra.addr.msf.frame);
2991                                 if ((ra.addr.lba >=
2992                                      sony_toc.lead_out_start_lba)
2993                                     || (ra.addr.lba + ra.nframes >=
2994                                         sony_toc.lead_out_start_lba)) {
2995                                         return -EINVAL;
2996                                 }
2997
2998                                 /* I know, this can go negative on an unsigned.  However,
2999                                    the first thing done to the data is to add this value,
3000                                    so this should compensate and allow direct msf access. */
3001                                 ra.addr.lba -= LOG_START_OFFSET;
3002                         } else {
3003                                 return -EINVAL;
3004                         }
3005
3006                         return (read_audio(&ra));
3007                 }
3008                 return 0;
3009                 break;
3010
3011         default:
3012                 return -EINVAL;
3013         }
3014 }
3015
3016 static int scd_spinup(void)
3017 {
3018         unsigned char res_reg[12];
3019         unsigned int res_size;
3020         int num_spin_ups;
3021
3022         num_spin_ups = 0;
3023
3024       respinup_on_open:
3025         do_sony_cd_cmd(SONY_SPIN_UP_CMD, NULL, 0, res_reg, &res_size);
3026
3027         /* The drive sometimes returns error 0.  I don't know why, but ignore
3028            it.  It seems to mean the drive has already done the operation. */
3029         if ((res_size < 2) || ((res_reg[0] != 0) && (res_reg[1] != 0))) {
3030                 printk("Sony CDROM %s error (scd_open, spin up)\n",
3031                        translate_error(res_reg[1]));
3032                 return 1;
3033         }
3034
3035         do_sony_cd_cmd(SONY_READ_TOC_CMD, NULL, 0, res_reg, &res_size);
3036
3037         /* The drive sometimes returns error 0.  I don't know why, but ignore
3038            it.  It seems to mean the drive has already done the operation. */
3039         if ((res_size < 2) || ((res_reg[0] != 0) && (res_reg[1] != 0))) {
3040                 /* If the drive is already playing, it's ok.  */
3041                 if ((res_reg[1] == SONY_AUDIO_PLAYING_ERR)
3042                     || (res_reg[1] == 0)) {
3043                         return 0;
3044                 }
3045
3046                 /* If the drive says it is not spun up (even though we just did it!)
3047                    then retry the operation at least a few times. */
3048                 if ((res_reg[1] == SONY_NOT_SPIN_ERR)
3049                     && (num_spin_ups < MAX_CDU31A_RETRIES)) {
3050                         num_spin_ups++;
3051                         goto respinup_on_open;
3052                 }
3053
3054                 printk("Sony CDROM error %s (scd_open, read toc)\n",
3055                        translate_error(res_reg[1]));
3056                 do_sony_cd_cmd(SONY_SPIN_DOWN_CMD, NULL, 0, res_reg,
3057                                &res_size);
3058                 return 1;
3059         }
3060         return 0;
3061 }
3062
3063 /*
3064  * Open the drive for operations.  Spin the drive up and read the table of
3065  * contents if these have not already been done.
3066  */
3067 static int scd_open(struct cdrom_device_info *cdi, int openmode)
3068 {
3069         unsigned char res_reg[12];
3070         unsigned int res_size;
3071         unsigned char params[2];
3072
3073         if (sony_usage == 0) {
3074                 if (scd_spinup() != 0)
3075                         return -EIO;
3076                 sony_get_toc();
3077                 if (!sony_toc_read) {
3078                         do_sony_cd_cmd(SONY_SPIN_DOWN_CMD, NULL, 0,
3079                                        res_reg, &res_size);
3080                         return -EIO;
3081                 }
3082
3083                 /* For XA on the CDU31A only, we have to do special reads.
3084                    The CDU33A handles XA automagically. */
3085                 /* if (   (sony_toc.disk_type == SONY_XA_DISK_TYPE) */
3086                 if ((sony_toc.disk_type != 0x00)
3087                     && (!is_double_speed)) {
3088                         params[0] = SONY_SD_DECODE_PARAM;
3089                         params[1] = 0x07;
3090                         do_sony_cd_cmd(SONY_SET_DRIVE_PARAM_CMD,
3091                                        params, 2, res_reg, &res_size);
3092                         if ((res_size < 2)
3093                             || ((res_reg[0] & 0xf0) == 0x20)) {
3094                                 printk
3095                                     ("CDU31A: Unable to set XA params: 0x%2.2x\n",
3096                                      res_reg[1]);
3097                         }
3098                         sony_xa_mode = 1;
3099                 }
3100                 /* A non-XA disk.  Set the parms back if necessary. */
3101                 else if (sony_xa_mode) {
3102                         params[0] = SONY_SD_DECODE_PARAM;
3103                         params[1] = 0x0f;
3104                         do_sony_cd_cmd(SONY_SET_DRIVE_PARAM_CMD,
3105                                        params, 2, res_reg, &res_size);
3106                         if ((res_size < 2)
3107                             || ((res_reg[0] & 0xf0) == 0x20)) {
3108                                 printk
3109                                     ("CDU31A: Unable to reset XA params: 0x%2.2x\n",
3110                                      res_reg[1]);
3111                         }
3112                         sony_xa_mode = 0;
3113                 }
3114
3115                 sony_spun_up = 1;
3116         }
3117
3118         sony_usage++;
3119
3120         return 0;
3121 }
3122
3123
3124 /*
3125  * Close the drive.  Spin it down if no task is using it.  The spin
3126  * down will fail if playing audio, so audio play is OK.
3127  */
3128 static void scd_release(struct cdrom_device_info *cdi)
3129 {
3130         if (sony_usage == 1) {
3131                 unsigned char res_reg[12];
3132                 unsigned int res_size;
3133
3134                 do_sony_cd_cmd(SONY_SPIN_DOWN_CMD, NULL, 0, res_reg,
3135                                &res_size);
3136
3137                 sony_spun_up = 0;
3138         }
3139         sony_usage--;
3140 }
3141
3142 static struct cdrom_device_ops scd_dops = {
3143         .open                   = scd_open,
3144         .release                = scd_release,
3145         .drive_status           = scd_drive_status,
3146         .media_changed          = scd_media_changed,
3147         .tray_move              = scd_tray_move,
3148         .lock_door              = scd_lock_door,
3149         .select_speed           = scd_select_speed,
3150         .get_last_session       = scd_get_last_session,
3151         .get_mcn                = scd_get_mcn,
3152         .reset                  = scd_reset,
3153         .audio_ioctl            = scd_audio_ioctl,
3154         .dev_ioctl              = scd_dev_ioctl,
3155         .capability             = CDC_OPEN_TRAY | CDC_CLOSE_TRAY | CDC_LOCK |
3156                                   CDC_SELECT_SPEED | CDC_MULTI_SESSION |
3157                                   CDC_MULTI_SESSION | CDC_MCN |
3158                                   CDC_MEDIA_CHANGED | CDC_PLAY_AUDIO |
3159                                   CDC_RESET | CDC_IOCTLS | CDC_DRIVE_STATUS,
3160         .n_minors               = 1,
3161 };
3162
3163 static struct cdrom_device_info scd_info = {
3164         .ops            = &scd_dops,
3165         .speed          = 2,
3166         .capacity       = 1,
3167         .name           = "cdu31a"
3168 };
3169
3170 static int scd_block_open(struct inode *inode, struct file *file)
3171 {
3172         return cdrom_open(&scd_info, inode, file);
3173 }
3174
3175 static int scd_block_release(struct inode *inode, struct file *file)
3176 {
3177         return cdrom_release(&scd_info, file);
3178 }
3179
3180 static int scd_block_ioctl(struct inode *inode, struct file *file,
3181                                 unsigned cmd, unsigned long arg)
3182 {
3183         return cdrom_ioctl(&scd_info, inode, cmd, arg);
3184 }
3185
3186 static int scd_block_media_changed(struct gendisk *disk)
3187 {
3188         return cdrom_media_changed(&scd_info);
3189 }
3190
3191 struct block_device_operations scd_bdops =
3192 {
3193         .owner          = THIS_MODULE,
3194         .open           = scd_block_open,
3195         .release        = scd_block_release,
3196         .ioctl          = scd_block_ioctl,
3197         .media_changed  = scd_block_media_changed,
3198 };
3199
3200 static struct gendisk *scd_gendisk;
3201
3202 /* The different types of disc loading mechanisms supported */
3203 static char *load_mech[] __initdata =
3204     { "caddy", "tray", "pop-up", "unknown" };
3205
3206 static int __init
3207 get_drive_configuration(unsigned short base_io,
3208                         unsigned char res_reg[], unsigned int *res_size)
3209 {
3210         unsigned long retry_count;
3211
3212
3213         if (!request_region(base_io, 4, "cdu31a"))
3214                 return 0;
3215
3216         /* Set the base address */
3217         cdu31a_port = base_io;
3218
3219         /* Set up all the register locations */
3220         sony_cd_cmd_reg = cdu31a_port + SONY_CMD_REG_OFFSET;
3221         sony_cd_param_reg = cdu31a_port + SONY_PARAM_REG_OFFSET;
3222         sony_cd_write_reg = cdu31a_port + SONY_WRITE_REG_OFFSET;
3223         sony_cd_control_reg = cdu31a_port + SONY_CONTROL_REG_OFFSET;
3224         sony_cd_status_reg = cdu31a_port + SONY_STATUS_REG_OFFSET;
3225         sony_cd_result_reg = cdu31a_port + SONY_RESULT_REG_OFFSET;
3226         sony_cd_read_reg = cdu31a_port + SONY_READ_REG_OFFSET;
3227         sony_cd_fifost_reg = cdu31a_port + SONY_FIFOST_REG_OFFSET;
3228
3229         /*
3230          * Check to see if anything exists at the status register location.
3231          * I don't know if this is a good way to check, but it seems to work
3232          * ok for me.
3233          */
3234         if (read_status_register() != 0xff) {
3235                 /*
3236                  * Reset the drive and wait for attention from it (to say it's reset).
3237                  * If you don't wait, the next operation will probably fail.
3238                  */
3239                 reset_drive();
3240                 retry_count = jiffies + SONY_RESET_TIMEOUT;
3241                 while (time_before(jiffies, retry_count)
3242                        && (!is_attention())) {
3243                         sony_sleep();
3244                 }
3245
3246 #if 0
3247                 /* If attention is never seen probably not a CDU31a present */
3248                 if (!is_attention()) {
3249                         res_reg[0] = 0x20;
3250                         goto out_err;
3251                 }
3252 #endif
3253
3254                 /*
3255                  * Get the drive configuration.
3256                  */
3257                 do_sony_cd_cmd(SONY_REQ_DRIVE_CONFIG_CMD,
3258                                NULL,
3259                                0, (unsigned char *) res_reg, res_size);
3260                 if (*res_size <= 2 || (res_reg[0] & 0xf0) != 0)
3261                         goto out_err;
3262                 return 1;
3263         }
3264
3265         /* Return an error */
3266         res_reg[0] = 0x20;
3267 out_err:
3268         release_region(cdu31a_port, 4);
3269         cdu31a_port = 0;
3270         return 0;
3271 }
3272
3273 #ifndef MODULE
3274 /*
3275  * Set up base I/O and interrupts, called from main.c.
3276  
3277  */
3278
3279 static int __init cdu31a_setup(char *strings)
3280 {
3281         int ints[4];
3282
3283         (void) get_options(strings, ARRAY_SIZE(ints), ints);
3284
3285         if (ints[0] > 0) {
3286                 cdu31a_port = ints[1];
3287         }
3288         if (ints[0] > 1) {
3289                 cdu31a_irq = ints[2];
3290         }
3291         if ((strings != NULL) && (*strings != '\0')) {
3292                 if (strcmp(strings, "PAS") == 0) {
3293                         sony_pas_init = 1;
3294                 } else {
3295                         printk("CDU31A: Unknown interface type: %s\n",
3296                                strings);
3297                 }
3298         }
3299
3300         return 1;
3301 }
3302
3303 __setup("cdu31a=", cdu31a_setup);
3304
3305 #endif
3306
3307 /*
3308  * Initialize the driver.
3309  */
3310 int __init cdu31a_init(void)
3311 {
3312         struct s_sony_drive_config drive_config;
3313         struct gendisk *disk;
3314         int deficiency = 0;
3315         unsigned int res_size;
3316         char msg[255];
3317         char buf[40];
3318         int i;
3319         int tmp_irq;
3320
3321         /*
3322          * According to Alex Freed (freed@europa.orion.adobe.com), this is
3323          * required for the Fusion CD-16 package.  If the sound driver is
3324          * loaded, it should work fine, but just in case...
3325          *
3326          * The following turn on the CD-ROM interface for a Fusion CD-16.
3327          */
3328         if (sony_pas_init) {
3329                 outb(0xbc, 0x9a01);
3330                 outb(0xe2, 0x9a01);
3331         }
3332
3333         /* Setting the base I/O address to 0xffff will disable it. */
3334         if (cdu31a_port == 0xffff)
3335                 goto errout3;
3336
3337         if (cdu31a_port != 0) {
3338                 /* Need IRQ 0 because we can't sleep here. */
3339                 tmp_irq = cdu31a_irq;
3340                 cdu31a_irq = 0;
3341                 if (!get_drive_configuration(cdu31a_port,
3342                                             drive_config.exec_status,
3343                                             &res_size))
3344                         goto errout3;
3345                 cdu31a_irq = tmp_irq;
3346         } else {
3347                 cdu31a_irq = 0;
3348                 for (i = 0; cdu31a_addresses[i].base; i++) {
3349                         if (get_drive_configuration(cdu31a_addresses[i].base,
3350                                                      drive_config.exec_status,
3351                                                      &res_size)) {
3352                                 cdu31a_irq = cdu31a_addresses[i].int_num;
3353                                 break;
3354                         }
3355                 }
3356                 if (!cdu31a_port)
3357                         goto errout3;
3358         }
3359
3360         if (register_blkdev(MAJOR_NR, "cdu31a"))
3361                 goto errout2;
3362
3363         disk = alloc_disk(1);
3364         if (!disk)
3365                 goto errout1;
3366         disk->major = MAJOR_NR;
3367         disk->first_minor = 0;
3368         sprintf(disk->disk_name, "cdu31a");
3369         disk->fops = &scd_bdops;
3370         disk->flags = GENHD_FL_CD;
3371
3372         if (SONY_HWC_DOUBLE_SPEED(drive_config))
3373                 is_double_speed = 1;
3374
3375         tmp_irq = cdu31a_irq;   /* Need IRQ 0 because we can't sleep here. */
3376         cdu31a_irq = 0;
3377
3378         set_drive_params(sony_speed);
3379
3380         cdu31a_irq = tmp_irq;
3381
3382         if (cdu31a_irq > 0) {
3383                 if (request_irq
3384                     (cdu31a_irq, cdu31a_interrupt, SA_INTERRUPT,
3385                      "cdu31a", NULL)) {
3386                         printk
3387                             ("Unable to grab IRQ%d for the CDU31A driver\n",
3388                              cdu31a_irq);
3389                         cdu31a_irq = 0;
3390                 }
3391         }
3392
3393         sprintf(msg, "Sony I/F CDROM : %8.8s %16.16s %8.8s\n",
3394                 drive_config.vendor_id,
3395                 drive_config.product_id,
3396                 drive_config.product_rev_level);
3397         sprintf(buf, "  Capabilities: %s",
3398                 load_mech[SONY_HWC_GET_LOAD_MECH(drive_config)]);
3399         strcat(msg, buf);
3400         if (SONY_HWC_AUDIO_PLAYBACK(drive_config))
3401                 strcat(msg, ", audio");
3402         else
3403                 deficiency |= CDC_PLAY_AUDIO;
3404         if (SONY_HWC_EJECT(drive_config))
3405                 strcat(msg, ", eject");
3406         else
3407                 deficiency |= CDC_OPEN_TRAY;
3408         if (SONY_HWC_LED_SUPPORT(drive_config))
3409                 strcat(msg, ", LED");
3410         if (SONY_HWC_ELECTRIC_VOLUME(drive_config))
3411                 strcat(msg, ", elec. Vol");
3412         if (SONY_HWC_ELECTRIC_VOLUME_CTL(drive_config))
3413                 strcat(msg, ", sep. Vol");
3414         if (is_double_speed)
3415                 strcat(msg, ", double speed");
3416         else
3417                 deficiency |= CDC_SELECT_SPEED;
3418         if (cdu31a_irq > 0) {
3419                 sprintf(buf, ", irq %d", cdu31a_irq);
3420                 strcat(msg, buf);
3421         }
3422         strcat(msg, "\n");
3423
3424         is_a_cdu31a =
3425             strcmp("CD-ROM CDU31A", drive_config.product_id) == 0;
3426
3427         cdu31a_queue = blk_init_queue(do_cdu31a_request, &cdu31a_lock);
3428         if (!cdu31a_queue)
3429                 goto errout0;
3430
3431         init_timer(&cdu31a_abort_timer);
3432         cdu31a_abort_timer.function = handle_abort_timeout;
3433
3434         scd_info.mask = deficiency;
3435         scd_gendisk = disk;
3436         if (register_cdrom(&scd_info))
3437                 goto err;
3438         disk->queue = cdu31a_queue;
3439         add_disk(disk);
3440
3441         disk_changed = 1;
3442         return (0);
3443
3444 err:
3445         blk_cleanup_queue(cdu31a_queue);
3446 errout0:
3447         if (cdu31a_irq)
3448                 free_irq(cdu31a_irq, NULL);
3449         printk("Unable to register CDU-31a with Uniform cdrom driver\n");
3450         put_disk(disk);
3451 errout1:
3452         if (unregister_blkdev(MAJOR_NR, "cdu31a")) {
3453                 printk("Can't unregister block device for cdu31a\n");
3454         }
3455 errout2:
3456         release_region(cdu31a_port, 4);
3457 errout3:
3458         return -EIO;
3459 }
3460
3461
3462 void __exit cdu31a_exit(void)
3463 {
3464         del_gendisk(scd_gendisk);
3465         put_disk(scd_gendisk);
3466         if (unregister_cdrom(&scd_info)) {
3467                 printk
3468                     ("Can't unregister cdu31a from Uniform cdrom driver\n");
3469                 return;
3470         }
3471         if ((unregister_blkdev(MAJOR_NR, "cdu31a") == -EINVAL)) {
3472                 printk("Can't unregister cdu31a\n");
3473                 return;
3474         }
3475
3476         blk_cleanup_queue(cdu31a_queue);
3477
3478         if (cdu31a_irq > 0)
3479                 free_irq(cdu31a_irq, NULL);
3480
3481         release_region(cdu31a_port, 4);
3482         printk(KERN_INFO "cdu31a module released.\n");
3483 }
3484
3485 #ifdef MODULE
3486 module_init(cdu31a_init);
3487 #endif
3488 module_exit(cdu31a_exit);
3489
3490 MODULE_LICENSE("GPL");
3491 MODULE_ALIAS_BLOCKDEV_MAJOR(CDU31A_CDROM_MAJOR);