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