upgrade to linux 2.6.10-1.12_FC2
[linux-2.6.git] / drivers / cdrom / cdrom.c
1 /* linux/drivers/cdrom/cdrom.c. 
2    Copyright (c) 1996, 1997 David A. van Leeuwen.
3    Copyright (c) 1997, 1998 Erik Andersen <andersee@debian.org>
4    Copyright (c) 1998, 1999 Jens Axboe <axboe@image.dk>
5
6    May be copied or modified under the terms of the GNU General Public
7    License.  See linux/COPYING for more information.
8
9    Uniform CD-ROM driver for Linux.
10    See Documentation/cdrom/cdrom-standard.tex for usage information.
11
12    The routines in the file provide a uniform interface between the
13    software that uses CD-ROMs and the various low-level drivers that
14    actually talk to the hardware. Suggestions are welcome.
15    Patches that work are more welcome though.  ;-)
16
17  To Do List:
18  ----------------------------------
19
20  -- Modify sysctl/proc interface. I plan on having one directory per
21  drive, with entries for outputing general drive information, and sysctl
22  based tunable parameters such as whether the tray should auto-close for
23  that drive. Suggestions (or patches) for this welcome!
24
25
26  Revision History
27  ----------------------------------
28  1.00  Date Unknown -- David van Leeuwen <david@tm.tno.nl>
29  -- Initial version by David A. van Leeuwen. I don't have a detailed
30   changelog for the 1.x series, David?
31
32 2.00  Dec  2, 1997 -- Erik Andersen <andersee@debian.org>
33   -- New maintainer! As David A. van Leeuwen has been too busy to activly
34   maintain and improve this driver, I am now carrying on the torch. If
35   you have a problem with this driver, please feel free to contact me.
36
37   -- Added (rudimentary) sysctl interface. I realize this is really weak
38   right now, and is _very_ badly implemented. It will be improved...
39
40   -- Modified CDROM_DISC_STATUS so that it is now incorporated into
41   the Uniform CD-ROM driver via the cdrom_count_tracks function.
42   The cdrom_count_tracks function helps resolve some of the false
43   assumptions of the CDROM_DISC_STATUS ioctl, and is also used to check
44   for the correct media type when mounting or playing audio from a CD.
45
46   -- Remove the calls to verify_area and only use the copy_from_user and
47   copy_to_user stuff, since these calls now provide their own memory
48   checking with the 2.1.x kernels.
49
50   -- Major update to return codes so that errors from low-level drivers
51   are passed on through (thanks to Gerd Knorr for pointing out this
52   problem).
53
54   -- Made it so if a function isn't implemented in a low-level driver,
55   ENOSYS is now returned instead of EINVAL.
56
57   -- Simplified some complex logic so that the source code is easier to read.
58
59   -- Other stuff I probably forgot to mention (lots of changes).
60
61 2.01 to 2.11 Dec 1997-Jan 1998
62   -- TO-DO!  Write changelogs for 2.01 to 2.12.
63
64 2.12  Jan  24, 1998 -- Erik Andersen <andersee@debian.org>
65   -- Fixed a bug in the IOCTL_IN and IOCTL_OUT macros.  It turns out that
66   copy_*_user does not return EFAULT on error, but instead returns the number 
67   of bytes not copied.  I was returning whatever non-zero stuff came back from 
68   the copy_*_user functions directly, which would result in strange errors.
69
70 2.13  July 17, 1998 -- Erik Andersen <andersee@debian.org>
71   -- Fixed a bug in CDROM_SELECT_SPEED where you couldn't lower the speed
72   of the drive.  Thanks to Tobias Ringstr|m <tori@prosolvia.se> for pointing
73   this out and providing a simple fix.
74   -- Fixed the procfs-unload-module bug with the fill_inode procfs callback.
75   thanks to Andrea Arcangeli
76   -- Fixed it so that the /proc entry now also shows up when cdrom is
77   compiled into the kernel.  Before it only worked when loaded as a module.
78
79   2.14 August 17, 1998 -- Erik Andersen <andersee@debian.org>
80   -- Fixed a bug in cdrom_media_changed and handling of reporting that
81   the media had changed for devices that _don't_ implement media_changed.  
82   Thanks to Grant R. Guenther <grant@torque.net> for spotting this bug.
83   -- Made a few things more pedanticly correct.
84
85 2.50 Oct 19, 1998 - Jens Axboe <axboe@image.dk>
86   -- New maintainers! Erik was too busy to continue the work on the driver,
87   so now Chris Zwilling <chris@cloudnet.com> and Jens Axboe <axboe@image.dk>
88   will do their best to follow in his footsteps
89   
90   2.51 Dec 20, 1998 - Jens Axboe <axboe@image.dk>
91   -- Check if drive is capable of doing what we ask before blindly changing
92   cdi->options in various ioctl.
93   -- Added version to proc entry.
94   
95   2.52 Jan 16, 1999 - Jens Axboe <axboe@image.dk>
96   -- Fixed an error in open_for_data where we would sometimes not return
97   the correct error value. Thanks Huba Gaspar <huba@softcell.hu>.
98   -- Fixed module usage count - usage was based on /proc/sys/dev
99   instead of /proc/sys/dev/cdrom. This could lead to an oops when other
100   modules had entries in dev. Feb 02 - real bug was in sysctl.c where
101   dev would be removed even though it was used. cdrom.c just illuminated
102   that bug.
103   
104   2.53 Feb 22, 1999 - Jens Axboe <axboe@image.dk>
105   -- Fixup of several ioctl calls, in particular CDROM_SET_OPTIONS has
106   been "rewritten" because capabilities and options aren't in sync. They
107   should be...
108   -- Added CDROM_LOCKDOOR ioctl. Locks the door and keeps it that way.
109   -- Added CDROM_RESET ioctl.
110   -- Added CDROM_DEBUG ioctl. Enable debug messages on-the-fly.
111   -- Added CDROM_GET_CAPABILITY ioctl. This relieves userspace programs
112   from parsing /proc/sys/dev/cdrom/info.
113   
114   2.54 Mar 15, 1999 - Jens Axboe <axboe@image.dk>
115   -- Check capability mask from low level driver when counting tracks as
116   per suggestion from Corey J. Scotts <cstotts@blue.weeg.uiowa.edu>.
117   
118   2.55 Apr 25, 1999 - Jens Axboe <axboe@image.dk>
119   -- autoclose was mistakenly checked against CDC_OPEN_TRAY instead of
120   CDC_CLOSE_TRAY.
121   -- proc info didn't mask against capabilities mask.
122   
123   3.00 Aug 5, 1999 - Jens Axboe <axboe@image.dk>
124   -- Unified audio ioctl handling across CD-ROM drivers. A lot of the
125   code was duplicated before. Drives that support the generic packet
126   interface are now being fed packets from here instead.
127   -- First attempt at adding support for MMC2 commands - for DVD and
128   CD-R(W) drives. Only the DVD parts are in now - the interface used is
129   the same as for the audio ioctls.
130   -- ioctl cleanups. if a drive couldn't play audio, it didn't get
131   a change to perform device specific ioctls as well.
132   -- Defined CDROM_CAN(CDC_XXX) for checking the capabilities.
133   -- Put in sysctl files for autoclose, autoeject, check_media, debug,
134   and lock.
135   -- /proc/sys/dev/cdrom/info has been updated to also contain info about
136   CD-Rx and DVD capabilities.
137   -- Now default to checking media type.
138   -- CDROM_SEND_PACKET ioctl added. The infrastructure was in place for
139   doing this anyway, with the generic_packet addition.
140   
141   3.01 Aug 6, 1999 - Jens Axboe <axboe@image.dk>
142   -- Fix up the sysctl handling so that the option flags get set
143   correctly.
144   -- Fix up ioctl handling so the device specific ones actually get
145   called :).
146   
147   3.02 Aug 8, 1999 - Jens Axboe <axboe@image.dk>
148   -- Fixed volume control on SCSI drives (or others with longer audio
149   page).
150   -- Fixed a couple of DVD minors. Thanks to Andrew T. Veliath
151   <andrewtv@usa.net> for telling me and for having defined the various
152   DVD structures and ioctls in the first place! He designed the original
153   DVD patches for ide-cd and while I rearranged and unified them, the
154   interface is still the same.
155   
156   3.03 Sep 1, 1999 - Jens Axboe <axboe@image.dk>
157   -- Moved the rest of the audio ioctls from the CD-ROM drivers here. Only
158   CDROMREADTOCENTRY and CDROMREADTOCHDR are left.
159   -- Moved the CDROMREADxxx ioctls in here.
160   -- Defined the cdrom_get_last_written and cdrom_get_next_block as ioctls
161   and exported functions.
162   -- Erik Andersen <andersen@xmission.com> modified all SCMD_ commands
163   to now read GPCMD_ for the new generic packet interface. All low level
164   drivers are updated as well.
165   -- Various other cleanups.
166
167   3.04 Sep 12, 1999 - Jens Axboe <axboe@image.dk>
168   -- Fixed a couple of possible memory leaks (if an operation failed and
169   we didn't free the buffer before returning the error).
170   -- Integrated Uniform CD Changer handling from Richard Sharman
171   <rsharman@pobox.com>.
172   -- Defined CD_DVD and CD_CHANGER log levels.
173   -- Fixed the CDROMREADxxx ioctls.
174   -- CDROMPLAYTRKIND uses the GPCMD_PLAY_AUDIO_MSF command - too few
175   drives supported it. We lose the index part, however.
176   -- Small modifications to accommodate opens of /dev/hdc1, required
177   for ide-cd to handle multisession discs.
178   -- Export cdrom_mode_sense and cdrom_mode_select.
179   -- init_cdrom_command() for setting up a cgc command.
180   
181   3.05 Oct 24, 1999 - Jens Axboe <axboe@image.dk>
182   -- Changed the interface for CDROM_SEND_PACKET. Before it was virtually
183   impossible to send the drive data in a sensible way.
184   -- Lowered stack usage in mmc_ioctl(), dvd_read_disckey(), and
185   dvd_read_manufact.
186   -- Added setup of write mode for packet writing.
187   -- Fixed CDDA ripping with cdda2wav - accept much larger requests of
188   number of frames and split the reads in blocks of 8.
189
190   3.06 Dec 13, 1999 - Jens Axboe <axboe@image.dk>
191   -- Added support for changing the region of DVD drives.
192   -- Added sense data to generic command.
193
194   3.07 Feb 2, 2000 - Jens Axboe <axboe@suse.de>
195   -- Do same "read header length" trick in cdrom_get_disc_info() as
196   we do in cdrom_get_track_info() -- some drive don't obey specs and
197   fail if they can't supply the full Mt Fuji size table.
198   -- Deleted stuff related to setting up write modes. It has a different
199   home now.
200   -- Clear header length in mode_select unconditionally.
201   -- Removed the register_disk() that was added, not needed here.
202
203   3.08 May 1, 2000 - Jens Axboe <axboe@suse.de>
204   -- Fix direction flag in setup_send_key and setup_report_key. This
205   gave some SCSI adapters problems.
206   -- Always return -EROFS for write opens
207   -- Convert to module_init/module_exit style init and remove some
208   of the #ifdef MODULE stuff
209   -- Fix several dvd errors - DVD_LU_SEND_ASF should pass agid,
210   DVD_HOST_SEND_RPC_STATE did not set buffer size in cdb, and
211   dvd_do_auth passed uninitialized data to drive because init_cdrom_command
212   did not clear a 0 sized buffer.
213   
214   3.09 May 12, 2000 - Jens Axboe <axboe@suse.de>
215   -- Fix Video-CD on SCSI drives that don't support READ_CD command. In
216   that case switch block size and issue plain READ_10 again, then switch
217   back.
218
219   3.10 Jun 10, 2000 - Jens Axboe <axboe@suse.de>
220   -- Fix volume control on CD's - old SCSI-II drives now use their own
221   code, as doing MODE6 stuff in here is really not my intention.
222   -- Use READ_DISC_INFO for more reliable end-of-disc.
223
224   3.11 Jun 12, 2000 - Jens Axboe <axboe@suse.de>
225   -- Fix bug in getting rpc phase 2 region info.
226   -- Reinstate "correct" CDROMPLAYTRKIND
227
228    3.12 Oct 18, 2000 - Jens Axboe <axboe@suse.de>
229   -- Use quiet bit on packet commands not known to work
230
231    3.20 Dec 17, 2003 - Jens Axboe <axboe@suse.de>
232   -- Various fixes and lots of cleanups not listed :-)
233   -- Locking fixes
234   -- Mt Rainier support
235   -- DVD-RAM write open fixes
236
237   Nov 5 2001, Aug 8 2002. Modified by Andy Polyakov
238   <appro@fy.chalmers.se> to support MMC-3 compliant DVD+RW units.
239
240   Modified by Nigel Kukard <nkukard@lbsd.net> - support DVD+RW
241   2.4.x patch by Andy Polyakov <appro@fy.chalmers.se>
242
243 -------------------------------------------------------------------------*/
244
245 #define REVISION "Revision: 3.20"
246 #define VERSION "Id: cdrom.c 3.20 2003/12/17"
247
248 /* I use an error-log mask to give fine grain control over the type of
249    messages dumped to the system logs.  The available masks include: */
250 #define CD_NOTHING      0x0
251 #define CD_WARNING      0x1
252 #define CD_REG_UNREG    0x2
253 #define CD_DO_IOCTL     0x4
254 #define CD_OPEN         0x8
255 #define CD_CLOSE        0x10
256 #define CD_COUNT_TRACKS 0x20
257 #define CD_CHANGER      0x40
258 #define CD_DVD          0x80
259
260 /* Define this to remove _all_ the debugging messages */
261 /* #define ERRLOGMASK CD_NOTHING */
262 #define ERRLOGMASK CD_WARNING
263 /* #define ERRLOGMASK (CD_WARNING|CD_OPEN|CD_COUNT_TRACKS|CD_CLOSE) */
264 /* #define ERRLOGMASK (CD_WARNING|CD_REG_UNREG|CD_DO_IOCTL|CD_OPEN|CD_CLOSE|CD_COUNT_TRACKS) */
265
266 #include <linux/config.h>
267 #include <linux/module.h>
268 #include <linux/fs.h>
269 #include <linux/buffer_head.h>
270 #include <linux/major.h>
271 #include <linux/types.h>
272 #include <linux/errno.h>
273 #include <linux/kernel.h>
274 #include <linux/mm.h>
275 #include <linux/slab.h> 
276 #include <linux/cdrom.h>
277 #include <linux/sysctl.h>
278 #include <linux/proc_fs.h>
279 #include <linux/blkpg.h>
280 #include <linux/init.h>
281 #include <linux/fcntl.h>
282 #include <linux/blkdev.h>
283 #include <linux/times.h>
284
285 #include <asm/uaccess.h>
286
287 /* used to tell the module to turn on full debugging messages */
288 static int debug;
289 /* used to keep tray locked at all times */
290 static int keeplocked;
291 /* default compatibility mode */
292 static int autoclose=1;
293 static int autoeject;
294 static int lockdoor = 1;
295 /* will we ever get to use this... sigh. */
296 static int check_media_type;
297 /* automatically restart mrw format */
298 static int mrw_format_restart = 1;
299 module_param(debug, bool, 0);
300 module_param(autoclose, bool, 0);
301 module_param(autoeject, bool, 0);
302 module_param(lockdoor, bool, 0);
303 module_param(check_media_type, bool, 0);
304 module_param(mrw_format_restart, bool, 0);
305
306 static spinlock_t cdrom_lock = SPIN_LOCK_UNLOCKED;
307
308 static const char *mrw_format_status[] = {
309         "not mrw",
310         "bgformat inactive",
311         "bgformat active",
312         "mrw complete",
313 };
314
315 static const char *mrw_address_space[] = { "DMA", "GAA" };
316
317 #if (ERRLOGMASK!=CD_NOTHING)
318 #define cdinfo(type, fmt, args...) \
319         if ((ERRLOGMASK & type) || debug==1 ) \
320             printk(KERN_INFO "cdrom: " fmt, ## args)
321 #else
322 #define cdinfo(type, fmt, args...) 
323 #endif
324
325 /* These are used to simplify getting data in from and back to user land */
326 #define IOCTL_IN(arg, type, in)                                 \
327         if (copy_from_user(&(in), (type __user *) (arg), sizeof (in)))  \
328                 return -EFAULT;
329
330 #define IOCTL_OUT(arg, type, out) \
331         if (copy_to_user((type __user *) (arg), &(out), sizeof (out)))  \
332                 return -EFAULT;
333
334 /* The (cdo->capability & ~cdi->mask & CDC_XXX) construct was used in
335    a lot of places. This macro makes the code more clear. */
336 #define CDROM_CAN(type) (cdi->ops->capability & ~cdi->mask & (type))
337
338 /* used in the audio ioctls */
339 #define CHECKAUDIO if ((ret=check_for_audio_disc(cdi, cdo))) return ret
340
341 /* Not-exported routines. */
342 static int open_for_data(struct cdrom_device_info * cdi);
343 static int check_for_audio_disc(struct cdrom_device_info * cdi,
344                          struct cdrom_device_ops * cdo);
345 static void sanitize_format(union cdrom_addr *addr, 
346                 u_char * curr, u_char requested);
347 static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd,
348                      unsigned long arg);
349
350 int cdrom_get_last_written(struct cdrom_device_info *, long *);
351 static int cdrom_get_next_writable(struct cdrom_device_info *, long *);
352 static void cdrom_count_tracks(struct cdrom_device_info *, tracktype*);
353
354 static int cdrom_mrw_exit(struct cdrom_device_info *cdi);
355
356 static int cdrom_get_disc_info(struct cdrom_device_info *cdi, disc_information *di);
357
358 #ifdef CONFIG_SYSCTL
359 static void cdrom_sysctl_register(void);
360 #endif /* CONFIG_SYSCTL */ 
361 static struct cdrom_device_info *topCdromPtr;
362
363 static int cdrom_dummy_generic_packet(struct cdrom_device_info *cdi,
364                                       struct packet_command *cgc)
365 {
366         if (cgc->sense) {
367                 cgc->sense->sense_key = 0x05;
368                 cgc->sense->asc = 0x20;
369                 cgc->sense->ascq = 0x00;
370         }
371
372         cgc->stat = -EIO;
373         return -EIO;
374 }
375
376 /* This macro makes sure we don't have to check on cdrom_device_ops
377  * existence in the run-time routines below. Change_capability is a
378  * hack to have the capability flags defined const, while we can still
379  * change it here without gcc complaining at every line.
380  */
381 #define ENSURE(call, bits) if (cdo->call == NULL) *change_capability &= ~(bits)
382
383 int register_cdrom(struct cdrom_device_info *cdi)
384 {
385         static char banner_printed;
386         struct cdrom_device_ops *cdo = cdi->ops;
387         int *change_capability = (int *)&cdo->capability; /* hack */
388
389         cdinfo(CD_OPEN, "entering register_cdrom\n"); 
390
391         if (cdo->open == NULL || cdo->release == NULL)
392                 return -2;
393         if (!banner_printed) {
394                 printk(KERN_INFO "Uniform CD-ROM driver " REVISION "\n");
395                 banner_printed = 1;
396 #ifdef CONFIG_SYSCTL
397                 cdrom_sysctl_register();
398 #endif /* CONFIG_SYSCTL */ 
399         }
400
401         ENSURE(drive_status, CDC_DRIVE_STATUS );
402         ENSURE(media_changed, CDC_MEDIA_CHANGED);
403         ENSURE(tray_move, CDC_CLOSE_TRAY | CDC_OPEN_TRAY);
404         ENSURE(lock_door, CDC_LOCK);
405         ENSURE(select_speed, CDC_SELECT_SPEED);
406         ENSURE(get_last_session, CDC_MULTI_SESSION);
407         ENSURE(get_mcn, CDC_MCN);
408         ENSURE(reset, CDC_RESET);
409         ENSURE(audio_ioctl, CDC_PLAY_AUDIO);
410         ENSURE(dev_ioctl, CDC_IOCTLS);
411         ENSURE(generic_packet, CDC_GENERIC_PACKET);
412         cdi->mc_flags = 0;
413         cdo->n_minors = 0;
414         cdi->options = CDO_USE_FFLAGS;
415         
416         if (autoclose==1 && CDROM_CAN(CDC_CLOSE_TRAY))
417                 cdi->options |= (int) CDO_AUTO_CLOSE;
418         if (autoeject==1 && CDROM_CAN(CDC_OPEN_TRAY))
419                 cdi->options |= (int) CDO_AUTO_EJECT;
420         if (lockdoor==1)
421                 cdi->options |= (int) CDO_LOCK;
422         if (check_media_type==1)
423                 cdi->options |= (int) CDO_CHECK_TYPE;
424
425         if (CDROM_CAN(CDC_MRW_W))
426                 cdi->exit = cdrom_mrw_exit;
427
428         if (cdi->disk)
429                 cdi->cdda_method = CDDA_BPC_FULL;
430         else
431                 cdi->cdda_method = CDDA_OLD;
432
433         if (!cdo->generic_packet)
434                 cdo->generic_packet = cdrom_dummy_generic_packet;
435
436         cdinfo(CD_REG_UNREG, "drive \"/dev/%s\" registered\n", cdi->name);
437         spin_lock(&cdrom_lock);
438         cdi->next = topCdromPtr;        
439         topCdromPtr = cdi;
440         spin_unlock(&cdrom_lock);
441         return 0;
442 }
443 #undef ENSURE
444
445 int unregister_cdrom(struct cdrom_device_info *unreg)
446 {
447         struct cdrom_device_info *cdi, *prev;
448         cdinfo(CD_OPEN, "entering unregister_cdrom\n"); 
449
450         prev = NULL;
451         spin_lock(&cdrom_lock);
452         cdi = topCdromPtr;
453         while (cdi && cdi != unreg) {
454                 prev = cdi;
455                 cdi = cdi->next;
456         }
457
458         if (cdi == NULL) {
459                 spin_unlock(&cdrom_lock);
460                 return -2;
461         }
462         if (prev)
463                 prev->next = cdi->next;
464         else
465                 topCdromPtr = cdi->next;
466
467         spin_unlock(&cdrom_lock);
468
469         if (cdi->exit)
470                 cdi->exit(cdi);
471
472         cdi->ops->n_minors--;
473         cdinfo(CD_REG_UNREG, "drive \"/dev/%s\" unregistered\n", cdi->name);
474         return 0;
475 }
476
477 int cdrom_get_media_event(struct cdrom_device_info *cdi,
478                           struct media_event_desc *med)
479 {
480         struct packet_command cgc;
481         unsigned char buffer[8];
482         struct event_header *eh = (struct event_header *) buffer;
483
484         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
485         cgc.cmd[0] = GPCMD_GET_EVENT_STATUS_NOTIFICATION;
486         cgc.cmd[1] = 1;         /* IMMED */
487         cgc.cmd[4] = 1 << 4;    /* media event */
488         cgc.cmd[8] = sizeof(buffer);
489         cgc.quiet = 1;
490
491         if (cdi->ops->generic_packet(cdi, &cgc))
492                 return 1;
493
494         if (be16_to_cpu(eh->data_len) < sizeof(*med))
495                 return 1;
496
497         if (eh->nea || eh->notification_class != 0x4)
498                 return 1;
499
500         memcpy(med, &buffer[sizeof(*eh)], sizeof(*med));
501         return 0;
502 }
503
504 /*
505  * the first prototypes used 0x2c as the page code for the mrw mode page,
506  * subsequently this was changed to 0x03. probe the one used by this drive
507  */
508 int cdrom_mrw_probe_pc(struct cdrom_device_info *cdi)
509 {
510         struct packet_command cgc;
511         char buffer[16];
512
513         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
514
515         cgc.timeout = HZ;
516         cgc.quiet = 1;
517
518         if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC, 0)) {
519                 cdi->mrw_mode_page = MRW_MODE_PC;
520                 return 0;
521         } else if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC_PRE1, 0)) {
522                 cdi->mrw_mode_page = MRW_MODE_PC_PRE1;
523                 return 0;
524         }
525
526         return 1;
527 }
528
529 int cdrom_is_mrw(struct cdrom_device_info *cdi, int *write)
530 {
531         struct packet_command cgc;
532         struct mrw_feature_desc *mfd;
533         unsigned char buffer[16];
534         int ret;
535
536         *write = 0;
537
538         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
539
540         cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
541         cgc.cmd[3] = CDF_MRW;
542         cgc.cmd[8] = sizeof(buffer);
543         cgc.quiet = 1;
544
545         if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
546                 return ret;
547
548         mfd = (struct mrw_feature_desc *)&buffer[sizeof(struct feature_header)];
549         if (be16_to_cpu(mfd->feature_code) != CDF_MRW)
550                 return 1;
551         *write = mfd->write;
552
553         if ((ret = cdrom_mrw_probe_pc(cdi))) {
554                 *write = 0;
555                 return ret;
556         }
557
558         return 0;
559 }
560
561 static int cdrom_mrw_bgformat(struct cdrom_device_info *cdi, int cont)
562 {
563         struct packet_command cgc;
564         unsigned char buffer[12];
565         int ret;
566
567         printk(KERN_INFO "cdrom: %sstarting format\n", cont ? "Re" : "");
568
569         /*
570          * FmtData bit set (bit 4), format type is 1
571          */
572         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_WRITE);
573         cgc.cmd[0] = GPCMD_FORMAT_UNIT;
574         cgc.cmd[1] = (1 << 4) | 1;
575
576         cgc.timeout = 5 * 60 * HZ;
577
578         /*
579          * 4 byte format list header, 8 byte format list descriptor
580          */
581         buffer[1] = 1 << 1;
582         buffer[3] = 8;
583
584         /*
585          * nr_blocks field
586          */
587         buffer[4] = 0xff;
588         buffer[5] = 0xff;
589         buffer[6] = 0xff;
590         buffer[7] = 0xff;
591
592         buffer[8] = 0x24 << 2;
593         buffer[11] = cont;
594
595         ret = cdi->ops->generic_packet(cdi, &cgc);
596         if (ret)
597                 printk(KERN_INFO "cdrom: bgformat failed\n");
598
599         return ret;
600 }
601
602 static int cdrom_mrw_bgformat_susp(struct cdrom_device_info *cdi, int immed)
603 {
604         struct packet_command cgc;
605
606         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
607         cgc.cmd[0] = GPCMD_CLOSE_TRACK;
608
609         /*
610          * Session = 1, Track = 0
611          */
612         cgc.cmd[1] = !!immed;
613         cgc.cmd[2] = 1 << 1;
614
615         cgc.timeout = 5 * 60 * HZ;
616
617         return cdi->ops->generic_packet(cdi, &cgc);
618 }
619
620 static int cdrom_flush_cache(struct cdrom_device_info *cdi)
621 {
622         struct packet_command cgc;
623
624         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
625         cgc.cmd[0] = GPCMD_FLUSH_CACHE;
626
627         cgc.timeout = 5 * 60 * HZ;
628
629         return cdi->ops->generic_packet(cdi, &cgc);
630 }
631
632 static int cdrom_mrw_exit(struct cdrom_device_info *cdi)
633 {
634         disc_information di;
635         int ret;
636
637         ret = cdrom_get_disc_info(cdi, &di);
638         if (ret < 0 || ret < (int)offsetof(typeof(di),disc_type))
639                 return 1;
640
641         ret = 0;
642         if (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) {
643                 printk(KERN_INFO "cdrom: issuing MRW back ground "
644                                 "format suspend\n");
645                 ret = cdrom_mrw_bgformat_susp(cdi, 0);
646         }
647
648         if (!ret)
649                 ret = cdrom_flush_cache(cdi);
650
651         return ret;
652 }
653
654 static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)
655 {
656         struct packet_command cgc;
657         struct mode_page_header *mph;
658         char buffer[16];
659         int ret, offset, size;
660
661         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
662
663         cgc.buffer = buffer;
664         cgc.buflen = sizeof(buffer);
665
666         if ((ret = cdrom_mode_sense(cdi, &cgc, cdi->mrw_mode_page, 0)))
667                 return ret;
668
669         mph = (struct mode_page_header *) buffer;
670         offset = be16_to_cpu(mph->desc_length);
671         size = be16_to_cpu(mph->mode_data_length) + 2;
672
673         buffer[offset + 3] = space;
674         cgc.buflen = size;
675
676         if ((ret = cdrom_mode_select(cdi, &cgc)))
677                 return ret;
678
679         printk(KERN_INFO "cdrom: %s: mrw address space %s selected\n", cdi->name, mrw_address_space[space]);
680         return 0;
681 }
682
683 int cdrom_get_random_writable(struct cdrom_device_info *cdi,
684                               struct rwrt_feature_desc *rfd)
685 {
686         struct packet_command cgc;
687         char buffer[24];
688         int ret;
689
690         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
691
692         cgc.cmd[0] = GPCMD_GET_CONFIGURATION;   /* often 0x46 */
693         cgc.cmd[3] = CDF_RWRT;                  /* often 0x0020 */
694         cgc.cmd[8] = sizeof(buffer);            /* often 0x18 */
695         cgc.quiet = 1;
696
697         if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
698                 return ret;
699
700         memcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd));
701         return 0;
702 }
703
704 int cdrom_has_defect_mgt(struct cdrom_device_info *cdi)
705 {
706         struct packet_command cgc;
707         char buffer[16];
708         __u16 *feature_code;
709         int ret;
710
711         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
712
713         cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
714         cgc.cmd[3] = CDF_HWDM;
715         cgc.cmd[8] = sizeof(buffer);
716         cgc.quiet = 1;
717
718         if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
719                 return ret;
720
721         feature_code = (__u16 *) &buffer[sizeof(struct feature_header)];
722         if (be16_to_cpu(*feature_code) == CDF_HWDM)
723                 return 0;
724
725         return 1;
726 }
727
728
729 int cdrom_is_random_writable(struct cdrom_device_info *cdi, int *write)
730 {
731         struct rwrt_feature_desc rfd;
732         int ret;
733
734         *write = 0;
735
736         if ((ret = cdrom_get_random_writable(cdi, &rfd)))
737                 return ret;
738
739         if (CDF_RWRT == be16_to_cpu(rfd.feature_code))
740                 *write = 1;
741
742         return 0;
743 }
744
745 static int cdrom_media_erasable(struct cdrom_device_info *cdi)
746 {
747         disc_information di;
748         int ret;
749
750         ret = cdrom_get_disc_info(cdi, &di);
751         if (ret < 0 || ret < offsetof(typeof(di), n_first_track))
752                 return -1;
753
754         return di.erasable;
755 }
756
757 /*
758  * FIXME: check RO bit
759  */
760 static int cdrom_dvdram_open_write(struct cdrom_device_info *cdi)
761 {
762         int ret = cdrom_media_erasable(cdi);
763
764         /*
765          * allow writable open if media info read worked and media is
766          * erasable, _or_ if it fails since not all drives support it
767          */
768         if (!ret)
769                 return 1;
770
771         return 0;
772 }
773
774 static int cdrom_mrw_open_write(struct cdrom_device_info *cdi)
775 {
776         disc_information di;
777         int ret;
778
779         /*
780          * always reset to DMA lba space on open
781          */
782         if (cdrom_mrw_set_lba_space(cdi, MRW_LBA_DMA)) {
783                 printk(KERN_ERR "cdrom: failed setting lba address space\n");
784                 return 1;
785         }
786
787         ret = cdrom_get_disc_info(cdi, &di);
788         if (ret < 0 || ret < offsetof(typeof(di),disc_type))
789                 return 1;
790
791         if (!di.erasable)
792                 return 1;
793
794         /*
795          * mrw_status
796          * 0    -       not MRW formatted
797          * 1    -       MRW bgformat started, but not running or complete
798          * 2    -       MRW bgformat in progress
799          * 3    -       MRW formatting complete
800          */
801         ret = 0;
802         printk(KERN_INFO "cdrom open: mrw_status '%s'\n",
803                         mrw_format_status[di.mrw_status]);
804         if (!di.mrw_status)
805                 ret = 1;
806         else if (di.mrw_status == CDM_MRW_BGFORMAT_INACTIVE &&
807                         mrw_format_restart)
808                 ret = cdrom_mrw_bgformat(cdi, 1);
809
810         return ret;
811 }
812
813 static int mo_open_write(struct cdrom_device_info *cdi)
814 {
815         struct packet_command cgc;
816         char buffer[255];
817         int ret;
818
819         init_cdrom_command(&cgc, &buffer, 4, CGC_DATA_READ);
820         cgc.quiet = 1;
821
822         /*
823          * obtain write protect information as per
824          * drivers/scsi/sd.c:sd_read_write_protect_flag
825          */
826
827         ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);
828         if (ret)
829                 ret = cdrom_mode_sense(cdi, &cgc, GPMODE_VENDOR_PAGE, 0);
830         if (ret) {
831                 cgc.buflen = 255;
832                 ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);
833         }
834
835         /* drive gave us no info, let the user go ahead */
836         if (ret)
837                 return 0;
838
839         return buffer[3] & 0x80;
840 }
841
842 static int cdrom_ram_open_write(struct cdrom_device_info *cdi)
843 {
844         struct rwrt_feature_desc rfd;
845         int ret;
846
847         if ((ret = cdrom_has_defect_mgt(cdi)))
848                 return ret;
849
850         if ((ret = cdrom_get_random_writable(cdi, &rfd)))
851                 return ret;
852         else if (CDF_RWRT == be16_to_cpu(rfd.feature_code))
853                 ret = !rfd.curr;
854
855         cdinfo(CD_OPEN, "can open for random write\n");
856         return ret;
857 }
858
859 static void cdrom_mmc3_profile(struct cdrom_device_info *cdi)
860 {
861         struct packet_command cgc;
862         char buffer[32];
863         int ret, mmc3_profile;
864
865         init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);
866
867         cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
868         cgc.cmd[1] = 0;
869         cgc.cmd[2] = cgc.cmd[3] = 0;            /* Starting Feature Number */
870         cgc.cmd[8] = sizeof(buffer);            /* Allocation Length */
871         cgc.quiet = 1;
872
873         if ((ret = cdi->ops->generic_packet(cdi, &cgc)))
874                 mmc3_profile = 0xffff;
875         else
876                 mmc3_profile = (buffer[6] << 8) | buffer[7];
877
878         cdi->mmc3_profile = mmc3_profile;
879 }
880
881 static int cdrom_is_dvd_rw(struct cdrom_device_info *cdi)
882 {
883         switch (cdi->mmc3_profile) {
884         case 0x12:      /* DVD-RAM      */
885         case 0x1A:      /* DVD+RW       */
886                 return 0;
887         default:
888                 return 1;
889         }
890 }
891
892 /*
893  * returns 0 for ok to open write, non-0 to disallow
894  */
895 static int cdrom_open_write(struct cdrom_device_info *cdi)
896 {
897         int mrw, mrw_write, ram_write;
898         int ret = 1;
899
900         mrw = 0;
901         if (!cdrom_is_mrw(cdi, &mrw_write))
902                 mrw = 1;
903
904         if (CDROM_CAN(CDC_MO_DRIVE))
905                 ram_write = 1;
906         else
907                 (void) cdrom_is_random_writable(cdi, &ram_write);
908         
909         if (mrw)
910                 cdi->mask &= ~CDC_MRW;
911         else
912                 cdi->mask |= CDC_MRW;
913
914         if (mrw_write)
915                 cdi->mask &= ~CDC_MRW_W;
916         else
917                 cdi->mask |= CDC_MRW_W;
918
919         if (ram_write)
920                 cdi->mask &= ~CDC_RAM;
921         else
922                 cdi->mask |= CDC_RAM;
923
924         if (CDROM_CAN(CDC_MRW_W))
925                 ret = cdrom_mrw_open_write(cdi);
926         else if (CDROM_CAN(CDC_DVD_RAM))
927                 ret = cdrom_dvdram_open_write(cdi);
928         else if (CDROM_CAN(CDC_RAM) &&
929                  !CDROM_CAN(CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_MRW|CDC_MO_DRIVE))
930                 ret = cdrom_ram_open_write(cdi);
931         else if (CDROM_CAN(CDC_MO_DRIVE))
932                 ret = mo_open_write(cdi);
933         else if (!cdrom_is_dvd_rw(cdi))
934                 ret = 0;
935
936         return ret;
937 }
938
939 static void cdrom_dvd_rw_close_write(struct cdrom_device_info *cdi)
940 {
941         struct packet_command cgc;
942
943         if (cdi->mmc3_profile != 0x1a) {
944                 cdinfo(CD_CLOSE, "%s: No DVD+RW\n", cdi->name);
945                 return;
946         }
947
948         if (!cdi->media_written) {
949                 cdinfo(CD_CLOSE, "%s: DVD+RW media clean\n", cdi->name);
950                 return;
951         }
952
953         printk(KERN_INFO "cdrom: %s: dirty DVD+RW media, \"finalizing\"\n",
954                cdi->name);
955
956         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
957         cgc.cmd[0] = GPCMD_FLUSH_CACHE;
958         cgc.timeout = 30*HZ;
959         cdi->ops->generic_packet(cdi, &cgc);
960
961         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
962         cgc.cmd[0] = GPCMD_CLOSE_TRACK;
963         cgc.timeout = 3000*HZ;
964         cgc.quiet = 1;
965         cdi->ops->generic_packet(cdi, &cgc);
966
967         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
968         cgc.cmd[0] = GPCMD_CLOSE_TRACK;
969         cgc.cmd[2] = 2;  /* Close session */
970         cgc.quiet = 1;
971         cgc.timeout = 3000*HZ;
972         cdi->ops->generic_packet(cdi, &cgc);
973
974         cdi->media_written = 0;
975 }
976
977 static int cdrom_close_write(struct cdrom_device_info *cdi)
978 {
979 #if 0
980         return cdrom_flush_cache(cdi);
981 #else
982         return 0;
983 #endif
984 }
985
986 /* We use the open-option O_NONBLOCK to indicate that the
987  * purpose of opening is only for subsequent ioctl() calls; no device
988  * integrity checks are performed.
989  *
990  * We hope that all cd-player programs will adopt this convention. It
991  * is in their own interest: device control becomes a lot easier
992  * this way.
993  */
994 int cdrom_open(struct cdrom_device_info *cdi, struct inode *ip, struct file *fp)
995 {
996         int ret;
997
998         cdinfo(CD_OPEN, "entering cdrom_open\n"); 
999
1000         /* if this was a O_NONBLOCK open and we should honor the flags,
1001          * do a quick open without drive/disc integrity checks. */
1002         cdi->use_count++;
1003         if ((fp->f_flags & O_NONBLOCK) && (cdi->options & CDO_USE_FFLAGS)) {
1004                 ret = cdi->ops->open(cdi, 1);
1005         } else {
1006                 ret = open_for_data(cdi);
1007                 if (ret)
1008                         goto err;
1009                 cdrom_mmc3_profile(cdi);
1010                 if (fp->f_mode & FMODE_WRITE) {
1011                         ret = -EROFS;
1012                         if (cdrom_open_write(cdi))
1013                                 goto err;
1014                         if (!CDROM_CAN(CDC_RAM))
1015                                 goto err;
1016                         ret = 0;
1017                         cdi->media_written = 0;
1018                 }
1019         }
1020
1021         if (ret)
1022                 goto err;
1023
1024         cdinfo(CD_OPEN, "Use count for \"/dev/%s\" now %d\n",
1025                         cdi->name, cdi->use_count);
1026         /* Do this on open.  Don't wait for mount, because they might
1027             not be mounting, but opening with O_NONBLOCK */
1028         check_disk_change(ip->i_bdev);
1029         return 0;
1030 err:
1031         cdi->use_count--;
1032         return ret;
1033 }
1034
1035 static
1036 int open_for_data(struct cdrom_device_info * cdi)
1037 {
1038         int ret;
1039         struct cdrom_device_ops *cdo = cdi->ops;
1040         tracktype tracks;
1041         cdinfo(CD_OPEN, "entering open_for_data\n");
1042         /* Check if the driver can report drive status.  If it can, we
1043            can do clever things.  If it can't, well, we at least tried! */
1044         if (cdo->drive_status != NULL) {
1045                 ret = cdo->drive_status(cdi, CDSL_CURRENT);
1046                 cdinfo(CD_OPEN, "drive_status=%d\n", ret); 
1047                 if (ret == CDS_TRAY_OPEN) {
1048                         cdinfo(CD_OPEN, "the tray is open...\n"); 
1049                         /* can/may i close it? */
1050                         if (CDROM_CAN(CDC_CLOSE_TRAY) &&
1051                             cdi->options & CDO_AUTO_CLOSE) {
1052                                 cdinfo(CD_OPEN, "trying to close the tray.\n"); 
1053                                 ret=cdo->tray_move(cdi,0);
1054                                 if (ret) {
1055                                         cdinfo(CD_OPEN, "bummer. tried to close the tray but failed.\n"); 
1056                                         /* Ignore the error from the low
1057                                         level driver.  We don't care why it
1058                                         couldn't close the tray.  We only care 
1059                                         that there is no disc in the drive, 
1060                                         since that is the _REAL_ problem here.*/
1061                                         ret=-ENOMEDIUM;
1062                                         goto clean_up_and_return;
1063                                 }
1064                         } else {
1065                                 cdinfo(CD_OPEN, "bummer. this drive can't close the tray.\n"); 
1066                                 ret=-ENOMEDIUM;
1067                                 goto clean_up_and_return;
1068                         }
1069                         /* Ok, the door should be closed now.. Check again */
1070                         ret = cdo->drive_status(cdi, CDSL_CURRENT);
1071                         if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {
1072                                 cdinfo(CD_OPEN, "bummer. the tray is still not closed.\n"); 
1073                                 cdinfo(CD_OPEN, "tray might not contain a medium.\n");
1074                                 ret=-ENOMEDIUM;
1075                                 goto clean_up_and_return;
1076                         }
1077                         cdinfo(CD_OPEN, "the tray is now closed.\n"); 
1078                 }
1079                 /* the door should be closed now, check for the disc */
1080                 ret = cdo->drive_status(cdi, CDSL_CURRENT);
1081                 if (ret!=CDS_DISC_OK) {
1082                         ret = -ENOMEDIUM;
1083                         goto clean_up_and_return;
1084                 }
1085         }
1086         cdrom_count_tracks(cdi, &tracks);
1087         if (tracks.error == CDS_NO_DISC) {
1088                 cdinfo(CD_OPEN, "bummer. no disc.\n");
1089                 ret=-ENOMEDIUM;
1090                 goto clean_up_and_return;
1091         }
1092         /* CD-Players which don't use O_NONBLOCK, workman
1093          * for example, need bit CDO_CHECK_TYPE cleared! */
1094         if (tracks.data==0) {
1095                 if (cdi->options & CDO_CHECK_TYPE) {
1096                     /* give people a warning shot, now that CDO_CHECK_TYPE
1097                        is the default case! */
1098                     cdinfo(CD_OPEN, "bummer. wrong media type.\n"); 
1099                     cdinfo(CD_WARNING, "pid %d must open device O_NONBLOCK!\n",
1100                                         (unsigned int)current->pid); 
1101                     ret=-EMEDIUMTYPE;
1102                     goto clean_up_and_return;
1103                 }
1104                 else {
1105                     cdinfo(CD_OPEN, "wrong media type, but CDO_CHECK_TYPE not set.\n");
1106                 }
1107         }
1108
1109         cdinfo(CD_OPEN, "all seems well, opening the device.\n"); 
1110
1111         /* all seems well, we can open the device */
1112         ret = cdo->open(cdi, 0); /* open for data */
1113         cdinfo(CD_OPEN, "opening the device gave me %d.\n", ret); 
1114         /* After all this careful checking, we shouldn't have problems
1115            opening the device, but we don't want the device locked if 
1116            this somehow fails... */
1117         if (ret) {
1118                 cdinfo(CD_OPEN, "open device failed.\n"); 
1119                 goto clean_up_and_return;
1120         }
1121         if (CDROM_CAN(CDC_LOCK) && (cdi->options & CDO_LOCK)) {
1122                         cdo->lock_door(cdi, 1);
1123                         cdinfo(CD_OPEN, "door locked.\n");
1124         }
1125         cdinfo(CD_OPEN, "device opened successfully.\n"); 
1126         return ret;
1127
1128         /* Something failed.  Try to unlock the drive, because some drivers
1129         (notably ide-cd) lock the drive after every command.  This produced
1130         a nasty bug where after mount failed, the drive would remain locked!  
1131         This ensures that the drive gets unlocked after a mount fails.  This 
1132         is a goto to avoid bloating the driver with redundant code. */ 
1133 clean_up_and_return:
1134         /* Don't log this, its a perfectly normal user occurence */
1135         /* cdinfo(CD_WARNING, "open failed.\n");  */
1136         if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {
1137                         cdo->lock_door(cdi, 0);
1138                         cdinfo(CD_OPEN, "door unlocked.\n");
1139         }
1140         return ret;
1141 }
1142
1143 /* This code is similar to that in open_for_data. The routine is called
1144    whenever an audio play operation is requested.
1145 */
1146 int check_for_audio_disc(struct cdrom_device_info * cdi,
1147                          struct cdrom_device_ops * cdo)
1148 {
1149         int ret;
1150         tracktype tracks;
1151         cdinfo(CD_OPEN, "entering check_for_audio_disc\n");
1152         if (!(cdi->options & CDO_CHECK_TYPE))
1153                 return 0;
1154         if (cdo->drive_status != NULL) {
1155                 ret = cdo->drive_status(cdi, CDSL_CURRENT);
1156                 cdinfo(CD_OPEN, "drive_status=%d\n", ret); 
1157                 if (ret == CDS_TRAY_OPEN) {
1158                         cdinfo(CD_OPEN, "the tray is open...\n"); 
1159                         /* can/may i close it? */
1160                         if (CDROM_CAN(CDC_CLOSE_TRAY) &&
1161                             cdi->options & CDO_AUTO_CLOSE) {
1162                                 cdinfo(CD_OPEN, "trying to close the tray.\n"); 
1163                                 ret=cdo->tray_move(cdi,0);
1164                                 if (ret) {
1165                                         cdinfo(CD_OPEN, "bummer. tried to close tray but failed.\n"); 
1166                                         /* Ignore the error from the low
1167                                         level driver.  We don't care why it
1168                                         couldn't close the tray.  We only care 
1169                                         that there is no disc in the drive, 
1170                                         since that is the _REAL_ problem here.*/
1171                                         return -ENOMEDIUM;
1172                                 }
1173                         } else {
1174                                 cdinfo(CD_OPEN, "bummer. this driver can't close the tray.\n"); 
1175                                 return -ENOMEDIUM;
1176                         }
1177                         /* Ok, the door should be closed now.. Check again */
1178                         ret = cdo->drive_status(cdi, CDSL_CURRENT);
1179                         if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {
1180                                 cdinfo(CD_OPEN, "bummer. the tray is still not closed.\n"); 
1181                                 return -ENOMEDIUM;
1182                         }       
1183                         if (ret!=CDS_DISC_OK) {
1184                                 cdinfo(CD_OPEN, "bummer. disc isn't ready.\n"); 
1185                                 return -EIO;
1186                         }       
1187                         cdinfo(CD_OPEN, "the tray is now closed.\n"); 
1188                 }       
1189         }
1190         cdrom_count_tracks(cdi, &tracks);
1191         if (tracks.error) 
1192                 return(tracks.error);
1193
1194         if (tracks.audio==0)
1195                 return -EMEDIUMTYPE;
1196
1197         return 0;
1198 }
1199
1200 /* Admittedly, the logic below could be performed in a nicer way. */
1201 int cdrom_release(struct cdrom_device_info *cdi, struct file *fp)
1202 {
1203         struct cdrom_device_ops *cdo = cdi->ops;
1204         int opened_for_data;
1205
1206         cdinfo(CD_CLOSE, "entering cdrom_release\n"); 
1207
1208         if (cdi->use_count > 0)
1209                 cdi->use_count--;
1210         if (cdi->use_count == 0)
1211                 cdinfo(CD_CLOSE, "Use count for \"/dev/%s\" now zero\n", cdi->name);
1212         if (cdi->use_count == 0)
1213                 cdrom_dvd_rw_close_write(cdi);
1214         if (cdi->use_count == 0 &&
1215             (cdo->capability & CDC_LOCK) && !keeplocked) {
1216                 cdinfo(CD_CLOSE, "Unlocking door!\n");
1217                 cdo->lock_door(cdi, 0);
1218         }
1219         opened_for_data = !(cdi->options & CDO_USE_FFLAGS) ||
1220                 !(fp && fp->f_flags & O_NONBLOCK);
1221
1222         /*
1223          * flush cache on last write release
1224          */
1225         if (CDROM_CAN(CDC_RAM) && !cdi->use_count && cdi->for_data)
1226                 cdrom_close_write(cdi);
1227
1228         cdo->release(cdi);
1229         if (cdi->use_count == 0) {      /* last process that closes dev*/
1230                 if (opened_for_data &&
1231                     cdi->options & CDO_AUTO_EJECT && CDROM_CAN(CDC_OPEN_TRAY))
1232                         cdo->tray_move(cdi, 1);
1233         }
1234         return 0;
1235 }
1236
1237 static int cdrom_read_mech_status(struct cdrom_device_info *cdi, 
1238                                   struct cdrom_changer_info *buf)
1239 {
1240         struct packet_command cgc;
1241         struct cdrom_device_ops *cdo = cdi->ops;
1242         int length;
1243
1244         /*
1245          * Sanyo changer isn't spec compliant (doesn't use regular change
1246          * LOAD_UNLOAD command, and it doesn't implement the mech status
1247          * command below
1248          */
1249         if (cdi->sanyo_slot) {
1250                 buf->hdr.nslots = 3;
1251                 buf->hdr.curslot = cdi->sanyo_slot == 3 ? 0 : cdi->sanyo_slot;
1252                 for (length = 0; length < 3; length++) {
1253                         buf->slots[length].disc_present = 1;
1254                         buf->slots[length].change = 0;
1255                 }
1256                 return 0;
1257         }
1258
1259         length = sizeof(struct cdrom_mechstat_header) +
1260                  cdi->capacity * sizeof(struct cdrom_slot);
1261
1262         init_cdrom_command(&cgc, buf, length, CGC_DATA_READ);
1263         cgc.cmd[0] = GPCMD_MECHANISM_STATUS;
1264         cgc.cmd[8] = (length >> 8) & 0xff;
1265         cgc.cmd[9] = length & 0xff;
1266         return cdo->generic_packet(cdi, &cgc);
1267 }
1268
1269 static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot)
1270 {
1271         struct cdrom_changer_info *info;
1272         int ret;
1273
1274         cdinfo(CD_CHANGER, "entering cdrom_slot_status()\n"); 
1275         if (cdi->sanyo_slot)
1276                 return CDS_NO_INFO;
1277         
1278         info = kmalloc(sizeof(*info), GFP_KERNEL);
1279         if (!info)
1280                 return -ENOMEM;
1281
1282         if ((ret = cdrom_read_mech_status(cdi, info)))
1283                 goto out_free;
1284
1285         if (info->slots[slot].disc_present)
1286                 ret = CDS_DISC_OK;
1287         else
1288                 ret = CDS_NO_DISC;
1289
1290 out_free:
1291         kfree(info);
1292         return ret;
1293 }
1294
1295 /* Return the number of slots for an ATAPI/SCSI cdrom, 
1296  * return 1 if not a changer. 
1297  */
1298 int cdrom_number_of_slots(struct cdrom_device_info *cdi) 
1299 {
1300         int status;
1301         int nslots = 1;
1302         struct cdrom_changer_info *info;
1303
1304         cdinfo(CD_CHANGER, "entering cdrom_number_of_slots()\n"); 
1305         /* cdrom_read_mech_status requires a valid value for capacity: */
1306         cdi->capacity = 0; 
1307
1308         info = kmalloc(sizeof(*info), GFP_KERNEL);
1309         if (!info)
1310                 return -ENOMEM;
1311
1312         if ((status = cdrom_read_mech_status(cdi, info)) == 0)
1313                 nslots = info->hdr.nslots;
1314
1315         kfree(info);
1316         return nslots;
1317 }
1318
1319
1320 /* If SLOT < 0, unload the current slot.  Otherwise, try to load SLOT. */
1321 static int cdrom_load_unload(struct cdrom_device_info *cdi, int slot) 
1322 {
1323         struct packet_command cgc;
1324
1325         cdinfo(CD_CHANGER, "entering cdrom_load_unload()\n"); 
1326         if (cdi->sanyo_slot && slot < 0)
1327                 return 0;
1328
1329         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
1330         cgc.cmd[0] = GPCMD_LOAD_UNLOAD;
1331         cgc.cmd[4] = 2 + (slot >= 0);
1332         cgc.cmd[8] = slot;
1333         cgc.timeout = 60 * HZ;
1334
1335         /* The Sanyo 3 CD changer uses byte 7 of the 
1336         GPCMD_TEST_UNIT_READY to command to switch CDs instead of
1337         using the GPCMD_LOAD_UNLOAD opcode. */
1338         if (cdi->sanyo_slot && -1 < slot) {
1339                 cgc.cmd[0] = GPCMD_TEST_UNIT_READY;
1340                 cgc.cmd[7] = slot;
1341                 cgc.cmd[4] = cgc.cmd[8] = 0;
1342                 cdi->sanyo_slot = slot ? slot : 3;
1343         }
1344
1345         return cdi->ops->generic_packet(cdi, &cgc);
1346 }
1347
1348 static int cdrom_select_disc(struct cdrom_device_info *cdi, int slot)
1349 {
1350         struct cdrom_changer_info *info;
1351         int curslot;
1352         int ret;
1353
1354         cdinfo(CD_CHANGER, "entering cdrom_select_disc()\n"); 
1355         if (!CDROM_CAN(CDC_SELECT_DISC))
1356                 return -EDRIVE_CANT_DO_THIS;
1357
1358         (void) cdi->ops->media_changed(cdi, slot);
1359
1360         if (slot == CDSL_NONE) {
1361                 /* set media changed bits, on both queues */
1362                 cdi->mc_flags = 0x3;
1363                 return cdrom_load_unload(cdi, -1);
1364         }
1365
1366         info = kmalloc(sizeof(*info), GFP_KERNEL);
1367         if (!info)
1368                 return -ENOMEM;
1369
1370         if ((ret = cdrom_read_mech_status(cdi, info))) {
1371                 kfree(info);
1372                 return ret;
1373         }
1374
1375         curslot = info->hdr.curslot;
1376         kfree(info);
1377
1378         if (cdi->use_count > 1 || keeplocked) {
1379                 if (slot == CDSL_CURRENT) {
1380                         return curslot;
1381                 } else {
1382                         return -EBUSY;
1383                 }
1384         }
1385
1386         /* Specifying CDSL_CURRENT will attempt to load the currnet slot,
1387         which is useful if it had been previously unloaded.
1388         Whether it can or not, it returns the current slot. 
1389         Similarly,  if slot happens to be the current one, we still
1390         try and load it. */
1391         if (slot == CDSL_CURRENT)
1392                 slot = curslot;
1393
1394         /* set media changed bits on both queues */
1395         cdi->mc_flags = 0x3;
1396         if ((ret = cdrom_load_unload(cdi, slot)))
1397                 return ret;
1398
1399         return slot;
1400 }
1401
1402 /* We want to make media_changed accessible to the user through an
1403  * ioctl. The main problem now is that we must double-buffer the
1404  * low-level implementation, to assure that the VFS and the user both
1405  * see a medium change once.
1406  */
1407
1408 static
1409 int media_changed(struct cdrom_device_info *cdi, int queue)
1410 {
1411         unsigned int mask = (1 << (queue & 1));
1412         int ret = !!(cdi->mc_flags & mask);
1413
1414         if (!CDROM_CAN(CDC_MEDIA_CHANGED))
1415             return ret;
1416         /* changed since last call? */
1417         if (cdi->ops->media_changed(cdi, CDSL_CURRENT)) {
1418                 cdi->mc_flags = 0x3;    /* set bit on both queues */
1419                 ret |= 1;
1420                 cdi->media_written = 0;
1421         }
1422         cdi->mc_flags &= ~mask;         /* clear bit */
1423         return ret;
1424 }
1425
1426 int cdrom_media_changed(struct cdrom_device_info *cdi)
1427 {
1428         /* This talks to the VFS, which doesn't like errors - just 1 or 0.  
1429          * Returning "0" is always safe (media hasn't been changed). Do that 
1430          * if the low-level cdrom driver dosn't support media changed. */ 
1431         if (cdi == NULL || cdi->ops->media_changed == NULL)
1432                 return 0;
1433         if (!CDROM_CAN(CDC_MEDIA_CHANGED))
1434                 return 0;
1435         return media_changed(cdi, 0);
1436 }
1437
1438 /* badly broken, I know. Is due for a fixup anytime. */
1439 static void cdrom_count_tracks(struct cdrom_device_info *cdi, tracktype* tracks)
1440 {
1441         struct cdrom_tochdr header;
1442         struct cdrom_tocentry entry;
1443         int ret, i;
1444         tracks->data=0;
1445         tracks->audio=0;
1446         tracks->cdi=0;
1447         tracks->xa=0;
1448         tracks->error=0;
1449         cdinfo(CD_COUNT_TRACKS, "entering cdrom_count_tracks\n"); 
1450         if (!CDROM_CAN(CDC_PLAY_AUDIO)) { 
1451                 tracks->error=CDS_NO_INFO;
1452                 return;
1453         }        
1454         /* Grab the TOC header so we can see how many tracks there are */
1455         if ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header))) {
1456                 if (ret == -ENOMEDIUM)
1457                         tracks->error = CDS_NO_DISC;
1458                 else
1459                         tracks->error = CDS_NO_INFO;
1460                 return;
1461         }       
1462         /* check what type of tracks are on this disc */
1463         entry.cdte_format = CDROM_MSF;
1464         for (i = header.cdth_trk0; i <= header.cdth_trk1; i++) {
1465                 entry.cdte_track  = i;
1466                 if (cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry)) {
1467                         tracks->error=CDS_NO_INFO;
1468                         return;
1469                 }       
1470                 if (entry.cdte_ctrl & CDROM_DATA_TRACK) {
1471                     if (entry.cdte_format == 0x10)
1472                         tracks->cdi++;
1473                     else if (entry.cdte_format == 0x20) 
1474                         tracks->xa++;
1475                     else
1476                         tracks->data++;
1477                 } else
1478                     tracks->audio++;
1479                 cdinfo(CD_COUNT_TRACKS, "track %d: format=%d, ctrl=%d\n",
1480                        i, entry.cdte_format, entry.cdte_ctrl);
1481         }       
1482         cdinfo(CD_COUNT_TRACKS, "disc has %d tracks: %d=audio %d=data %d=Cd-I %d=XA\n", 
1483                 header.cdth_trk1, tracks->audio, tracks->data, 
1484                 tracks->cdi, tracks->xa);
1485 }       
1486
1487 /* Requests to the low-level drivers will /always/ be done in the
1488    following format convention:
1489
1490    CDROM_LBA: all data-related requests.
1491    CDROM_MSF: all audio-related requests.
1492
1493    However, a low-level implementation is allowed to refuse this
1494    request, and return information in its own favorite format.
1495
1496    It doesn't make sense /at all/ to ask for a play_audio in LBA
1497    format, or ask for multi-session info in MSF format. However, for
1498    backward compatibility these format requests will be satisfied, but
1499    the requests to the low-level drivers will be sanitized in the more
1500    meaningful format indicated above.
1501  */
1502
1503 static
1504 void sanitize_format(union cdrom_addr *addr,
1505                      u_char * curr, u_char requested)
1506 {
1507         if (*curr == requested)
1508                 return;                 /* nothing to be done! */
1509         if (requested == CDROM_LBA) {
1510                 addr->lba = (int) addr->msf.frame +
1511                         75 * (addr->msf.second - 2 + 60 * addr->msf.minute);
1512         } else {                        /* CDROM_MSF */
1513                 int lba = addr->lba;
1514                 addr->msf.frame = lba % 75;
1515                 lba /= 75;
1516                 lba += 2;
1517                 addr->msf.second = lba % 60;
1518                 addr->msf.minute = lba / 60;
1519         }
1520         *curr = requested;
1521 }
1522
1523 void init_cdrom_command(struct packet_command *cgc, void *buf, int len,
1524                         int type)
1525 {
1526         memset(cgc, 0, sizeof(struct packet_command));
1527         if (buf)
1528                 memset(buf, 0, len);
1529         cgc->buffer = (char *) buf;
1530         cgc->buflen = len;
1531         cgc->data_direction = type;
1532         cgc->timeout = 5*HZ;
1533 }
1534
1535 /* DVD handling */
1536
1537 #define copy_key(dest,src)      memcpy((dest), (src), sizeof(dvd_key))
1538 #define copy_chal(dest,src)     memcpy((dest), (src), sizeof(dvd_challenge))
1539
1540 static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type)
1541 {
1542         cgc->cmd[0] = GPCMD_REPORT_KEY;
1543         cgc->cmd[10] = type | (agid << 6);
1544         switch (type) {
1545                 case 0: case 8: case 5: {
1546                         cgc->buflen = 8;
1547                         break;
1548                 }
1549                 case 1: {
1550                         cgc->buflen = 16;
1551                         break;
1552                 }
1553                 case 2: case 4: {
1554                         cgc->buflen = 12;
1555                         break;
1556                 }
1557         }
1558         cgc->cmd[9] = cgc->buflen;
1559         cgc->data_direction = CGC_DATA_READ;
1560 }
1561
1562 static void setup_send_key(struct packet_command *cgc, unsigned agid, unsigned type)
1563 {
1564         cgc->cmd[0] = GPCMD_SEND_KEY;
1565         cgc->cmd[10] = type | (agid << 6);
1566         switch (type) {
1567                 case 1: {
1568                         cgc->buflen = 16;
1569                         break;
1570                 }
1571                 case 3: {
1572                         cgc->buflen = 12;
1573                         break;
1574                 }
1575                 case 6: {
1576                         cgc->buflen = 8;
1577                         break;
1578                 }
1579         }
1580         cgc->cmd[9] = cgc->buflen;
1581         cgc->data_direction = CGC_DATA_WRITE;
1582 }
1583
1584 static int dvd_do_auth(struct cdrom_device_info *cdi, dvd_authinfo *ai)
1585 {
1586         int ret;
1587         u_char buf[20];
1588         struct packet_command cgc;
1589         struct cdrom_device_ops *cdo = cdi->ops;
1590         rpc_state_t rpc_state;
1591
1592         memset(buf, 0, sizeof(buf));
1593         init_cdrom_command(&cgc, buf, 0, CGC_DATA_READ);
1594
1595         switch (ai->type) {
1596         /* LU data send */
1597         case DVD_LU_SEND_AGID:
1598                 cdinfo(CD_DVD, "entering DVD_LU_SEND_AGID\n"); 
1599                 cgc.quiet = 1;
1600                 setup_report_key(&cgc, ai->lsa.agid, 0);
1601
1602                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1603                         return ret;
1604
1605                 ai->lsa.agid = buf[7] >> 6;
1606                 /* Returning data, let host change state */
1607                 break;
1608
1609         case DVD_LU_SEND_KEY1:
1610                 cdinfo(CD_DVD, "entering DVD_LU_SEND_KEY1\n"); 
1611                 setup_report_key(&cgc, ai->lsk.agid, 2);
1612
1613                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1614                         return ret;
1615
1616                 copy_key(ai->lsk.key, &buf[4]);
1617                 /* Returning data, let host change state */
1618                 break;
1619
1620         case DVD_LU_SEND_CHALLENGE:
1621                 cdinfo(CD_DVD, "entering DVD_LU_SEND_CHALLENGE\n"); 
1622                 setup_report_key(&cgc, ai->lsc.agid, 1);
1623
1624                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1625                         return ret;
1626
1627                 copy_chal(ai->lsc.chal, &buf[4]);
1628                 /* Returning data, let host change state */
1629                 break;
1630
1631         /* Post-auth key */
1632         case DVD_LU_SEND_TITLE_KEY:
1633                 cdinfo(CD_DVD, "entering DVD_LU_SEND_TITLE_KEY\n"); 
1634                 cgc.quiet = 1;
1635                 setup_report_key(&cgc, ai->lstk.agid, 4);
1636                 cgc.cmd[5] = ai->lstk.lba;
1637                 cgc.cmd[4] = ai->lstk.lba >> 8;
1638                 cgc.cmd[3] = ai->lstk.lba >> 16;
1639                 cgc.cmd[2] = ai->lstk.lba >> 24;
1640
1641                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1642                         return ret;
1643
1644                 ai->lstk.cpm = (buf[4] >> 7) & 1;
1645                 ai->lstk.cp_sec = (buf[4] >> 6) & 1;
1646                 ai->lstk.cgms = (buf[4] >> 4) & 3;
1647                 copy_key(ai->lstk.title_key, &buf[5]);
1648                 /* Returning data, let host change state */
1649                 break;
1650
1651         case DVD_LU_SEND_ASF:
1652                 cdinfo(CD_DVD, "entering DVD_LU_SEND_ASF\n"); 
1653                 setup_report_key(&cgc, ai->lsasf.agid, 5);
1654                 
1655                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1656                         return ret;
1657
1658                 ai->lsasf.asf = buf[7] & 1;
1659                 break;
1660
1661         /* LU data receive (LU changes state) */
1662         case DVD_HOST_SEND_CHALLENGE:
1663                 cdinfo(CD_DVD, "entering DVD_HOST_SEND_CHALLENGE\n"); 
1664                 setup_send_key(&cgc, ai->hsc.agid, 1);
1665                 buf[1] = 0xe;
1666                 copy_chal(&buf[4], ai->hsc.chal);
1667
1668                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1669                         return ret;
1670
1671                 ai->type = DVD_LU_SEND_KEY1;
1672                 break;
1673
1674         case DVD_HOST_SEND_KEY2:
1675                 cdinfo(CD_DVD, "entering DVD_HOST_SEND_KEY2\n"); 
1676                 setup_send_key(&cgc, ai->hsk.agid, 3);
1677                 buf[1] = 0xa;
1678                 copy_key(&buf[4], ai->hsk.key);
1679
1680                 if ((ret = cdo->generic_packet(cdi, &cgc))) {
1681                         ai->type = DVD_AUTH_FAILURE;
1682                         return ret;
1683                 }
1684                 ai->type = DVD_AUTH_ESTABLISHED;
1685                 break;
1686
1687         /* Misc */
1688         case DVD_INVALIDATE_AGID:
1689                 cgc.quiet = 1;
1690                 cdinfo(CD_DVD, "entering DVD_INVALIDATE_AGID\n"); 
1691                 setup_report_key(&cgc, ai->lsa.agid, 0x3f);
1692                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1693                         return ret;
1694                 break;
1695
1696         /* Get region settings */
1697         case DVD_LU_SEND_RPC_STATE:
1698                 cdinfo(CD_DVD, "entering DVD_LU_SEND_RPC_STATE\n");
1699                 setup_report_key(&cgc, 0, 8);
1700                 memset(&rpc_state, 0, sizeof(rpc_state_t));
1701                 cgc.buffer = (char *) &rpc_state;
1702
1703                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1704                         return ret;
1705
1706                 ai->lrpcs.type = rpc_state.type_code;
1707                 ai->lrpcs.vra = rpc_state.vra;
1708                 ai->lrpcs.ucca = rpc_state.ucca;
1709                 ai->lrpcs.region_mask = rpc_state.region_mask;
1710                 ai->lrpcs.rpc_scheme = rpc_state.rpc_scheme;
1711                 break;
1712
1713         /* Set region settings */
1714         case DVD_HOST_SEND_RPC_STATE:
1715                 cdinfo(CD_DVD, "entering DVD_HOST_SEND_RPC_STATE\n");
1716                 setup_send_key(&cgc, 0, 6);
1717                 buf[1] = 6;
1718                 buf[4] = ai->hrpcs.pdrc;
1719
1720                 if ((ret = cdo->generic_packet(cdi, &cgc)))
1721                         return ret;
1722                 break;
1723
1724         default:
1725                 cdinfo(CD_WARNING, "Invalid DVD key ioctl (%d)\n", ai->type);
1726                 return -ENOTTY;
1727         }
1728
1729         return 0;
1730 }
1731
1732 static int dvd_read_physical(struct cdrom_device_info *cdi, dvd_struct *s)
1733 {
1734         unsigned char buf[21], *base;
1735         struct dvd_layer *layer;
1736         struct packet_command cgc;
1737         struct cdrom_device_ops *cdo = cdi->ops;
1738         int ret, layer_num = s->physical.layer_num;
1739
1740         if (layer_num >= DVD_LAYERS)
1741                 return -EINVAL;
1742
1743         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1744         cgc.cmd[0] = GPCMD_READ_DVD_STRUCTURE;
1745         cgc.cmd[6] = layer_num;
1746         cgc.cmd[7] = s->type;
1747         cgc.cmd[9] = cgc.buflen & 0xff;
1748
1749         /*
1750          * refrain from reporting errors on non-existing layers (mainly)
1751          */
1752         cgc.quiet = 1;
1753
1754         if ((ret = cdo->generic_packet(cdi, &cgc)))
1755                 return ret;
1756
1757         base = &buf[4];
1758         layer = &s->physical.layer[layer_num];
1759
1760         /*
1761          * place the data... really ugly, but at least we won't have to
1762          * worry about endianess in userspace.
1763          */
1764         memset(layer, 0, sizeof(*layer));
1765         layer->book_version = base[0] & 0xf;
1766         layer->book_type = base[0] >> 4;
1767         layer->min_rate = base[1] & 0xf;
1768         layer->disc_size = base[1] >> 4;
1769         layer->layer_type = base[2] & 0xf;
1770         layer->track_path = (base[2] >> 4) & 1;
1771         layer->nlayers = (base[2] >> 5) & 3;
1772         layer->track_density = base[3] & 0xf;
1773         layer->linear_density = base[3] >> 4;
1774         layer->start_sector = base[5] << 16 | base[6] << 8 | base[7];
1775         layer->end_sector = base[9] << 16 | base[10] << 8 | base[11];
1776         layer->end_sector_l0 = base[13] << 16 | base[14] << 8 | base[15];
1777         layer->bca = base[16] >> 7;
1778
1779         return 0;
1780 }
1781
1782 static int dvd_read_copyright(struct cdrom_device_info *cdi, dvd_struct *s)
1783 {
1784         int ret;
1785         u_char buf[8];
1786         struct packet_command cgc;
1787         struct cdrom_device_ops *cdo = cdi->ops;
1788
1789         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1790         cgc.cmd[0] = GPCMD_READ_DVD_STRUCTURE;
1791         cgc.cmd[6] = s->copyright.layer_num;
1792         cgc.cmd[7] = s->type;
1793         cgc.cmd[8] = cgc.buflen >> 8;
1794         cgc.cmd[9] = cgc.buflen & 0xff;
1795
1796         if ((ret = cdo->generic_packet(cdi, &cgc)))
1797                 return ret;
1798
1799         s->copyright.cpst = buf[4];
1800         s->copyright.rmi = buf[5];
1801
1802         return 0;
1803 }
1804
1805 static int dvd_read_disckey(struct cdrom_device_info *cdi, dvd_struct *s)
1806 {
1807         int ret, size;
1808         u_char *buf;
1809         struct packet_command cgc;
1810         struct cdrom_device_ops *cdo = cdi->ops;
1811
1812         size = sizeof(s->disckey.value) + 4;
1813
1814         if ((buf = (u_char *) kmalloc(size, GFP_KERNEL)) == NULL)
1815                 return -ENOMEM;
1816
1817         init_cdrom_command(&cgc, buf, size, CGC_DATA_READ);
1818         cgc.cmd[0] = GPCMD_READ_DVD_STRUCTURE;
1819         cgc.cmd[7] = s->type;
1820         cgc.cmd[8] = size >> 8;
1821         cgc.cmd[9] = size & 0xff;
1822         cgc.cmd[10] = s->disckey.agid << 6;
1823
1824         if (!(ret = cdo->generic_packet(cdi, &cgc)))
1825                 memcpy(s->disckey.value, &buf[4], sizeof(s->disckey.value));
1826
1827         kfree(buf);
1828         return ret;
1829 }
1830
1831 static int dvd_read_bca(struct cdrom_device_info *cdi, dvd_struct *s)
1832 {
1833         int ret;
1834         u_char buf[4 + 188];
1835         struct packet_command cgc;
1836         struct cdrom_device_ops *cdo = cdi->ops;
1837
1838         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1839         cgc.cmd[0] = GPCMD_READ_DVD_STRUCTURE;
1840         cgc.cmd[7] = s->type;
1841         cgc.cmd[9] = cgc.buflen = 0xff;
1842
1843         if ((ret = cdo->generic_packet(cdi, &cgc)))
1844                 return ret;
1845
1846         s->bca.len = buf[0] << 8 | buf[1];
1847         if (s->bca.len < 12 || s->bca.len > 188) {
1848                 cdinfo(CD_WARNING, "Received invalid BCA length (%d)\n", s->bca.len);
1849                 return -EIO;
1850         }
1851         memcpy(s->bca.value, &buf[4], s->bca.len);
1852
1853         return 0;
1854 }
1855
1856 static int dvd_read_manufact(struct cdrom_device_info *cdi, dvd_struct *s)
1857 {
1858         int ret = 0, size;
1859         u_char *buf;
1860         struct packet_command cgc;
1861         struct cdrom_device_ops *cdo = cdi->ops;
1862
1863         size = sizeof(s->manufact.value) + 4;
1864
1865         if ((buf = (u_char *) kmalloc(size, GFP_KERNEL)) == NULL)
1866                 return -ENOMEM;
1867
1868         init_cdrom_command(&cgc, buf, size, CGC_DATA_READ);
1869         cgc.cmd[0] = GPCMD_READ_DVD_STRUCTURE;
1870         cgc.cmd[7] = s->type;
1871         cgc.cmd[8] = size >> 8;
1872         cgc.cmd[9] = size & 0xff;
1873
1874         if ((ret = cdo->generic_packet(cdi, &cgc))) {
1875                 kfree(buf);
1876                 return ret;
1877         }
1878
1879         s->manufact.len = buf[0] << 8 | buf[1];
1880         if (s->manufact.len < 0 || s->manufact.len > 2048) {
1881                 cdinfo(CD_WARNING, "Received invalid manufacture info length"
1882                                    " (%d)\n", s->manufact.len);
1883                 ret = -EIO;
1884         } else {
1885                 memcpy(s->manufact.value, &buf[4], s->manufact.len);
1886         }
1887
1888         kfree(buf);
1889         return ret;
1890 }
1891
1892 static int dvd_read_struct(struct cdrom_device_info *cdi, dvd_struct *s)
1893 {
1894         switch (s->type) {
1895         case DVD_STRUCT_PHYSICAL:
1896                 return dvd_read_physical(cdi, s);
1897
1898         case DVD_STRUCT_COPYRIGHT:
1899                 return dvd_read_copyright(cdi, s);
1900
1901         case DVD_STRUCT_DISCKEY:
1902                 return dvd_read_disckey(cdi, s);
1903
1904         case DVD_STRUCT_BCA:
1905                 return dvd_read_bca(cdi, s);
1906
1907         case DVD_STRUCT_MANUFACT:
1908                 return dvd_read_manufact(cdi, s);
1909                 
1910         default:
1911                 cdinfo(CD_WARNING, ": Invalid DVD structure read requested (%d)\n",
1912                                         s->type);
1913                 return -EINVAL;
1914         }
1915 }
1916
1917 int cdrom_mode_sense(struct cdrom_device_info *cdi,
1918                      struct packet_command *cgc,
1919                      int page_code, int page_control)
1920 {
1921         struct cdrom_device_ops *cdo = cdi->ops;
1922
1923         memset(cgc->cmd, 0, sizeof(cgc->cmd));
1924
1925         cgc->cmd[0] = GPCMD_MODE_SENSE_10;
1926         cgc->cmd[2] = page_code | (page_control << 6);
1927         cgc->cmd[7] = cgc->buflen >> 8;
1928         cgc->cmd[8] = cgc->buflen & 0xff;
1929         cgc->data_direction = CGC_DATA_READ;
1930         return cdo->generic_packet(cdi, cgc);
1931 }
1932
1933 int cdrom_mode_select(struct cdrom_device_info *cdi,
1934                       struct packet_command *cgc)
1935 {
1936         struct cdrom_device_ops *cdo = cdi->ops;
1937
1938         memset(cgc->cmd, 0, sizeof(cgc->cmd));
1939         memset(cgc->buffer, 0, 2);
1940         cgc->cmd[0] = GPCMD_MODE_SELECT_10;
1941         cgc->cmd[1] = 0x10;             /* PF */
1942         cgc->cmd[7] = cgc->buflen >> 8;
1943         cgc->cmd[8] = cgc->buflen & 0xff;
1944         cgc->data_direction = CGC_DATA_WRITE;
1945         return cdo->generic_packet(cdi, cgc);
1946 }
1947
1948 static int cdrom_read_subchannel(struct cdrom_device_info *cdi,
1949                                  struct cdrom_subchnl *subchnl, int mcn)
1950 {
1951         struct cdrom_device_ops *cdo = cdi->ops;
1952         struct packet_command cgc;
1953         char buffer[32];
1954         int ret;
1955
1956         init_cdrom_command(&cgc, buffer, 16, CGC_DATA_READ);
1957         cgc.cmd[0] = GPCMD_READ_SUBCHANNEL;
1958         cgc.cmd[1] = 2;     /* MSF addressing */
1959         cgc.cmd[2] = 0x40;  /* request subQ data */
1960         cgc.cmd[3] = mcn ? 2 : 1;
1961         cgc.cmd[8] = 16;
1962
1963         if ((ret = cdo->generic_packet(cdi, &cgc)))
1964                 return ret;
1965
1966         subchnl->cdsc_audiostatus = cgc.buffer[1];
1967         subchnl->cdsc_format = CDROM_MSF;
1968         subchnl->cdsc_ctrl = cgc.buffer[5] & 0xf;
1969         subchnl->cdsc_trk = cgc.buffer[6];
1970         subchnl->cdsc_ind = cgc.buffer[7];
1971
1972         subchnl->cdsc_reladdr.msf.minute = cgc.buffer[13];
1973         subchnl->cdsc_reladdr.msf.second = cgc.buffer[14];
1974         subchnl->cdsc_reladdr.msf.frame = cgc.buffer[15];
1975         subchnl->cdsc_absaddr.msf.minute = cgc.buffer[9];
1976         subchnl->cdsc_absaddr.msf.second = cgc.buffer[10];
1977         subchnl->cdsc_absaddr.msf.frame = cgc.buffer[11];
1978
1979         return 0;
1980 }
1981
1982 /*
1983  * Specific READ_10 interface
1984  */
1985 static int cdrom_read_cd(struct cdrom_device_info *cdi,
1986                          struct packet_command *cgc, int lba,
1987                          int blocksize, int nblocks)
1988 {
1989         struct cdrom_device_ops *cdo = cdi->ops;
1990
1991         memset(&cgc->cmd, 0, sizeof(cgc->cmd));
1992         cgc->cmd[0] = GPCMD_READ_10;
1993         cgc->cmd[2] = (lba >> 24) & 0xff;
1994         cgc->cmd[3] = (lba >> 16) & 0xff;
1995         cgc->cmd[4] = (lba >>  8) & 0xff;
1996         cgc->cmd[5] = lba & 0xff;
1997         cgc->cmd[6] = (nblocks >> 16) & 0xff;
1998         cgc->cmd[7] = (nblocks >>  8) & 0xff;
1999         cgc->cmd[8] = nblocks & 0xff;
2000         cgc->buflen = blocksize * nblocks;
2001         return cdo->generic_packet(cdi, cgc);
2002 }
2003
2004 /* very generic interface for reading the various types of blocks */
2005 static int cdrom_read_block(struct cdrom_device_info *cdi,
2006                             struct packet_command *cgc,
2007                             int lba, int nblocks, int format, int blksize)
2008 {
2009         struct cdrom_device_ops *cdo = cdi->ops;
2010
2011         memset(&cgc->cmd, 0, sizeof(cgc->cmd));
2012         cgc->cmd[0] = GPCMD_READ_CD;
2013         /* expected sector size - cdda,mode1,etc. */
2014         cgc->cmd[1] = format << 2;
2015         /* starting address */
2016         cgc->cmd[2] = (lba >> 24) & 0xff;
2017         cgc->cmd[3] = (lba >> 16) & 0xff;
2018         cgc->cmd[4] = (lba >>  8) & 0xff;
2019         cgc->cmd[5] = lba & 0xff;
2020         /* number of blocks */
2021         cgc->cmd[6] = (nblocks >> 16) & 0xff;
2022         cgc->cmd[7] = (nblocks >>  8) & 0xff;
2023         cgc->cmd[8] = nblocks & 0xff;
2024         cgc->buflen = blksize * nblocks;
2025         
2026         /* set the header info returned */
2027         switch (blksize) {
2028         case CD_FRAMESIZE_RAW0  : cgc->cmd[9] = 0x58; break;
2029         case CD_FRAMESIZE_RAW1  : cgc->cmd[9] = 0x78; break;
2030         case CD_FRAMESIZE_RAW   : cgc->cmd[9] = 0xf8; break;
2031         default                 : cgc->cmd[9] = 0x10;
2032         }
2033         
2034         return cdo->generic_packet(cdi, cgc);
2035 }
2036
2037 static int cdrom_read_cdda_old(struct cdrom_device_info *cdi, __u8 __user *ubuf,
2038                                int lba, int nframes)
2039 {
2040         struct packet_command cgc;
2041         int ret = 0;
2042         int nr;
2043
2044         cdi->last_sense = 0;
2045
2046         memset(&cgc, 0, sizeof(cgc));
2047
2048         /*
2049          * start with will ra.nframes size, back down if alloc fails
2050          */
2051         nr = nframes;
2052         do {
2053                 cgc.buffer = kmalloc(CD_FRAMESIZE_RAW * nr, GFP_KERNEL);
2054                 if (cgc.buffer)
2055                         break;
2056
2057                 nr >>= 1;
2058         } while (nr);
2059
2060         if (!nr)
2061                 return -ENOMEM;
2062
2063         if (!access_ok(VERIFY_WRITE, ubuf, nframes * CD_FRAMESIZE_RAW)) {
2064                 ret = -EFAULT;
2065                 goto out;
2066         }
2067
2068         cgc.data_direction = CGC_DATA_READ;
2069         while (nframes > 0) {
2070                 if (nr > nframes)
2071                         nr = nframes;
2072
2073                 ret = cdrom_read_block(cdi, &cgc, lba, nr, 1, CD_FRAMESIZE_RAW);
2074                 if (ret)
2075                         break;
2076                 if (__copy_to_user(ubuf, cgc.buffer, CD_FRAMESIZE_RAW * nr)) {
2077                         ret = -EFAULT;
2078                         break;
2079                 }
2080                 ubuf += CD_FRAMESIZE_RAW * nr;
2081                 nframes -= nr;
2082                 lba += nr;
2083         }
2084 out:
2085         kfree(cgc.buffer);
2086         return ret;
2087 }
2088
2089 static int cdrom_read_cdda_bpc(struct cdrom_device_info *cdi, __u8 __user *ubuf,
2090                                int lba, int nframes)
2091 {
2092         request_queue_t *q = cdi->disk->queue;
2093         struct request *rq;
2094         struct bio *bio;
2095         unsigned int len;
2096         int nr, ret = 0;
2097
2098         if (!q)
2099                 return -ENXIO;
2100
2101         cdi->last_sense = 0;
2102
2103         while (nframes) {
2104                 nr = nframes;
2105                 if (cdi->cdda_method == CDDA_BPC_SINGLE)
2106                         nr = 1;
2107                 if (nr * CD_FRAMESIZE_RAW > (q->max_sectors << 9))
2108                         nr = (q->max_sectors << 9) / CD_FRAMESIZE_RAW;
2109
2110                 len = nr * CD_FRAMESIZE_RAW;
2111
2112                 rq = blk_rq_map_user(q, READ, ubuf, len);
2113                 if (IS_ERR(rq))
2114                         return PTR_ERR(rq);
2115
2116                 memset(rq->cmd, 0, sizeof(rq->cmd));
2117                 rq->cmd[0] = GPCMD_READ_CD;
2118                 rq->cmd[1] = 1 << 2;
2119                 rq->cmd[2] = (lba >> 24) & 0xff;
2120                 rq->cmd[3] = (lba >> 16) & 0xff;
2121                 rq->cmd[4] = (lba >>  8) & 0xff;
2122                 rq->cmd[5] = lba & 0xff;
2123                 rq->cmd[6] = (nr >> 16) & 0xff;
2124                 rq->cmd[7] = (nr >>  8) & 0xff;
2125                 rq->cmd[8] = nr & 0xff;
2126                 rq->cmd[9] = 0xf8;
2127
2128                 rq->cmd_len = 12;
2129                 rq->flags |= REQ_BLOCK_PC;
2130                 rq->timeout = 60 * HZ;
2131                 bio = rq->bio;
2132
2133                 if (rq->bio)
2134                         blk_queue_bounce(q, &rq->bio);
2135
2136                 if (blk_execute_rq(q, cdi->disk, rq)) {
2137                         struct request_sense *s = rq->sense;
2138                         ret = -EIO;
2139                         cdi->last_sense = s->sense_key;
2140                 }
2141
2142                 if (blk_rq_unmap_user(rq, bio, len))
2143                         ret = -EFAULT;
2144
2145                 if (ret)
2146                         break;
2147
2148                 nframes -= nr;
2149                 lba += nr;
2150                 ubuf += len;
2151         }
2152
2153         return ret;
2154 }
2155
2156 static int cdrom_read_cdda(struct cdrom_device_info *cdi, __u8 __user *ubuf,
2157                            int lba, int nframes)
2158 {
2159         int ret;
2160
2161         if (cdi->cdda_method == CDDA_OLD)
2162                 return cdrom_read_cdda_old(cdi, ubuf, lba, nframes);
2163
2164 retry:
2165         /*
2166          * for anything else than success and io error, we need to retry
2167          */
2168         ret = cdrom_read_cdda_bpc(cdi, ubuf, lba, nframes);
2169         if (!ret || ret != -EIO)
2170                 return ret;
2171
2172         /*
2173          * I've seen drives get sense 4/8/3 udma crc errors on multi
2174          * frame dma, so drop to single frame dma if we need to
2175          */
2176         if (cdi->cdda_method == CDDA_BPC_FULL && nframes > 1) {
2177                 printk("cdrom: dropping to single frame dma\n");
2178                 cdi->cdda_method = CDDA_BPC_SINGLE;
2179                 goto retry;
2180         }
2181
2182         /*
2183          * so we have an io error of some sort with multi frame dma. if the
2184          * condition wasn't a hardware error
2185          * problems, not for any error
2186          */
2187         if (cdi->last_sense != 0x04 && cdi->last_sense != 0x0b)
2188                 return ret;
2189
2190         printk("cdrom: dropping to old style cdda (sense=%x)\n", cdi->last_sense);
2191         cdi->cdda_method = CDDA_OLD;
2192         return cdrom_read_cdda_old(cdi, ubuf, lba, nframes);    
2193 }
2194
2195 /* Just about every imaginable ioctl is supported in the Uniform layer
2196  * these days. ATAPI / SCSI specific code now mainly resides in
2197  * mmc_ioct().
2198  */
2199 int cdrom_ioctl(struct file * file, struct cdrom_device_info *cdi,
2200                 struct inode *ip, unsigned int cmd, unsigned long arg)
2201 {
2202         struct cdrom_device_ops *cdo = cdi->ops;
2203         int ret;
2204
2205         /* Try the generic SCSI command ioctl's first.. */
2206         ret = scsi_cmd_ioctl(file, ip->i_bdev->bd_disk, cmd, (void __user *)arg);
2207         if (ret != -ENOTTY)
2208                 return ret;
2209
2210         /* the first few commands do not deal with audio drive_info, but
2211            only with routines in cdrom device operations. */
2212         switch (cmd) {
2213         case CDROMMULTISESSION: {
2214                 struct cdrom_multisession ms_info;
2215                 u_char requested_format;
2216                 cdinfo(CD_DO_IOCTL, "entering CDROMMULTISESSION\n"); 
2217                 if (!(cdo->capability & CDC_MULTI_SESSION))
2218                         return -ENOSYS;
2219                 IOCTL_IN(arg, struct cdrom_multisession, ms_info);
2220                 requested_format = ms_info.addr_format;
2221                 if (!((requested_format == CDROM_MSF) ||
2222                         (requested_format == CDROM_LBA)))
2223                                 return -EINVAL;
2224                 ms_info.addr_format = CDROM_LBA;
2225                 if ((ret=cdo->get_last_session(cdi, &ms_info)))
2226                         return ret;
2227                 sanitize_format(&ms_info.addr, &ms_info.addr_format,
2228                                 requested_format);
2229                 IOCTL_OUT(arg, struct cdrom_multisession, ms_info);
2230                 cdinfo(CD_DO_IOCTL, "CDROMMULTISESSION successful\n"); 
2231                 return 0;
2232                 }
2233
2234         case CDROMEJECT: {
2235                 cdinfo(CD_DO_IOCTL, "entering CDROMEJECT\n"); 
2236                 if (!CDROM_CAN(CDC_OPEN_TRAY))
2237                         return -ENOSYS;
2238                 if (cdi->use_count != 1 || keeplocked)
2239                         return -EBUSY;
2240                 if (CDROM_CAN(CDC_LOCK))
2241                         if ((ret=cdo->lock_door(cdi, 0)))
2242                                 return ret;
2243
2244                 return cdo->tray_move(cdi, 1);
2245                 }
2246
2247         case CDROMCLOSETRAY: {
2248                 cdinfo(CD_DO_IOCTL, "entering CDROMCLOSETRAY\n"); 
2249                 if (!CDROM_CAN(CDC_CLOSE_TRAY))
2250                         return -ENOSYS;
2251                 return cdo->tray_move(cdi, 0);
2252                 }
2253
2254         case CDROMEJECT_SW: {
2255                 cdinfo(CD_DO_IOCTL, "entering CDROMEJECT_SW\n"); 
2256                 if (!CDROM_CAN(CDC_OPEN_TRAY))
2257                         return -ENOSYS;
2258                 if (keeplocked)
2259                         return -EBUSY;
2260                 cdi->options &= ~(CDO_AUTO_CLOSE | CDO_AUTO_EJECT);
2261                 if (arg)
2262                         cdi->options |= CDO_AUTO_CLOSE | CDO_AUTO_EJECT;
2263                 return 0;
2264                 }
2265
2266         case CDROM_MEDIA_CHANGED: {
2267                 struct cdrom_changer_info *info;
2268                 int changed;
2269
2270                 cdinfo(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n"); 
2271                 if (!CDROM_CAN(CDC_MEDIA_CHANGED))
2272                         return -ENOSYS;
2273
2274                 /* cannot select disc or select current disc */
2275                 if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)
2276                         return media_changed(cdi, 1);
2277
2278                 if ((unsigned int)arg >= cdi->capacity)
2279                         return -EINVAL;
2280
2281                 info = kmalloc(sizeof(*info), GFP_KERNEL);
2282                 if (!info)
2283                         return -ENOMEM;
2284
2285                 if ((ret = cdrom_read_mech_status(cdi, info))) {
2286                         kfree(info);
2287                         return ret;
2288                 }
2289
2290                 changed = info->slots[arg].change;
2291                 kfree(info);
2292                 return changed;
2293                 }
2294
2295         case CDROM_SET_OPTIONS: {
2296                 cdinfo(CD_DO_IOCTL, "entering CDROM_SET_OPTIONS\n"); 
2297                 /* options need to be in sync with capability. too late for
2298                    that, so we have to check each one separately... */
2299                 switch (arg) {
2300                 case CDO_USE_FFLAGS:
2301                 case CDO_CHECK_TYPE:
2302                         break;
2303                 case CDO_LOCK:
2304                         if (!CDROM_CAN(CDC_LOCK))
2305                                 return -ENOSYS;
2306                         break;
2307                 case 0:
2308                         return cdi->options;
2309                 /* default is basically CDO_[AUTO_CLOSE|AUTO_EJECT] */
2310                 default:
2311                         if (!CDROM_CAN(arg))
2312                                 return -ENOSYS;
2313                 }
2314                 cdi->options |= (int) arg;
2315                 return cdi->options;
2316                 }
2317
2318         case CDROM_CLEAR_OPTIONS: {
2319                 cdinfo(CD_DO_IOCTL, "entering CDROM_CLEAR_OPTIONS\n"); 
2320                 cdi->options &= ~(int) arg;
2321                 return cdi->options;
2322                 }
2323
2324         case CDROM_SELECT_SPEED: {
2325                 cdinfo(CD_DO_IOCTL, "entering CDROM_SELECT_SPEED\n"); 
2326                 if (!CDROM_CAN(CDC_SELECT_SPEED))
2327                         return -ENOSYS;
2328                 return cdo->select_speed(cdi, arg);
2329                 }
2330
2331         case CDROM_SELECT_DISC: {
2332                 cdinfo(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n"); 
2333                 if (!CDROM_CAN(CDC_SELECT_DISC))
2334                         return -ENOSYS;
2335
2336                 if ((arg != CDSL_CURRENT) && (arg != CDSL_NONE))
2337                         if ((int)arg >= cdi->capacity)
2338                                 return -EINVAL;
2339
2340                 /* cdo->select_disc is a hook to allow a driver-specific
2341                  * way of seleting disc.  However, since there is no
2342                  * equiv hook for cdrom_slot_status this may not 
2343                  * actually be useful...
2344                  */
2345                 if (cdo->select_disc != NULL)
2346                         return cdo->select_disc(cdi, arg);
2347
2348                 /* no driver specific select_disc(), call our own */
2349                 cdinfo(CD_CHANGER, "Using generic cdrom_select_disc()\n"); 
2350                 return cdrom_select_disc(cdi, arg);
2351                 }
2352
2353         case CDROMRESET: {
2354                 if (!capable(CAP_SYS_ADMIN))
2355                         return -EACCES;
2356                 cdinfo(CD_DO_IOCTL, "entering CDROM_RESET\n");
2357                 if (!CDROM_CAN(CDC_RESET))
2358                         return -ENOSYS;
2359                 invalidate_bdev(ip->i_bdev, 0);
2360                 return cdo->reset(cdi);
2361                 }
2362
2363         case CDROM_LOCKDOOR: {
2364                 cdinfo(CD_DO_IOCTL, "%socking door.\n", arg ? "L" : "Unl");
2365                 if (!CDROM_CAN(CDC_LOCK))
2366                         return -EDRIVE_CANT_DO_THIS;
2367                 keeplocked = arg ? 1 : 0;
2368                 /* don't unlock the door on multiple opens,but allow root
2369                  * to do so */
2370                 if ((cdi->use_count != 1) && !arg && !capable(CAP_SYS_ADMIN))
2371                         return -EBUSY;
2372                 return cdo->lock_door(cdi, arg);
2373                 }
2374
2375         case CDROM_DEBUG: {
2376                 if (!capable(CAP_SYS_ADMIN))
2377                         return -EACCES;
2378                 cdinfo(CD_DO_IOCTL, "%sabling debug.\n", arg ? "En" : "Dis");
2379                 debug = arg ? 1 : 0;
2380                 return debug;
2381                 }
2382
2383         case CDROM_GET_CAPABILITY: {
2384                 cdinfo(CD_DO_IOCTL, "entering CDROM_GET_CAPABILITY\n");
2385                 return (cdo->capability & ~cdi->mask);
2386                 }
2387
2388 /* The following function is implemented, although very few audio
2389  * discs give Universal Product Code information, which should just be
2390  * the Medium Catalog Number on the box.  Note, that the way the code
2391  * is written on the CD is /not/ uniform across all discs!
2392  */
2393         case CDROM_GET_MCN: {
2394                 struct cdrom_mcn mcn;
2395                 cdinfo(CD_DO_IOCTL, "entering CDROM_GET_MCN\n"); 
2396                 if (!(cdo->capability & CDC_MCN))
2397                         return -ENOSYS;
2398                 if ((ret=cdo->get_mcn(cdi, &mcn)))
2399                         return ret;
2400                 IOCTL_OUT(arg, struct cdrom_mcn, mcn);
2401                 cdinfo(CD_DO_IOCTL, "CDROM_GET_MCN successful\n"); 
2402                 return 0;
2403                 }
2404
2405         case CDROM_DRIVE_STATUS: {
2406                 cdinfo(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); 
2407                 if (!(cdo->capability & CDC_DRIVE_STATUS))
2408                         return -ENOSYS;
2409                 if (!CDROM_CAN(CDC_SELECT_DISC))
2410                         return cdo->drive_status(cdi, CDSL_CURRENT);
2411                 if ((arg == CDSL_CURRENT) || (arg == CDSL_NONE)) 
2412                         return cdo->drive_status(cdi, CDSL_CURRENT);
2413                 if (((int)arg >= cdi->capacity))
2414                         return -EINVAL;
2415                 return cdrom_slot_status(cdi, arg);
2416                 }
2417
2418         /* Ok, this is where problems start.  The current interface for the
2419            CDROM_DISC_STATUS ioctl is flawed.  It makes the false assumption
2420            that CDs are all CDS_DATA_1 or all CDS_AUDIO, etc.  Unfortunatly,
2421            while this is often the case, it is also very common for CDs to
2422            have some tracks with data, and some tracks with audio.  Just 
2423            because I feel like it, I declare the following to be the best
2424            way to cope.  If the CD has ANY data tracks on it, it will be
2425            returned as a data CD.  If it has any XA tracks, I will return
2426            it as that.  Now I could simplify this interface by combining these 
2427            returns with the above, but this more clearly demonstrates
2428            the problem with the current interface.  Too bad this wasn't 
2429            designed to use bitmasks...         -Erik 
2430
2431            Well, now we have the option CDS_MIXED: a mixed-type CD. 
2432            User level programmers might feel the ioctl is not very useful.
2433                                                 ---david
2434         */
2435         case CDROM_DISC_STATUS: {
2436                 tracktype tracks;
2437                 cdinfo(CD_DO_IOCTL, "entering CDROM_DISC_STATUS\n"); 
2438                 cdrom_count_tracks(cdi, &tracks);
2439                 if (tracks.error) 
2440                         return(tracks.error);
2441
2442                 /* Policy mode on */
2443                 if (tracks.audio > 0) {
2444                         if (tracks.data==0 && tracks.cdi==0 && tracks.xa==0) 
2445                                 return CDS_AUDIO;
2446                         else
2447                                 return CDS_MIXED;
2448                 }
2449                 if (tracks.cdi > 0) return CDS_XA_2_2;
2450                 if (tracks.xa > 0) return CDS_XA_2_1;
2451                 if (tracks.data > 0) return CDS_DATA_1;
2452                 /* Policy mode off */
2453
2454                 cdinfo(CD_WARNING,"This disc doesn't have any tracks I recognize!\n");
2455                 return CDS_NO_INFO;
2456                 }
2457
2458         case CDROM_CHANGER_NSLOTS: {
2459                 cdinfo(CD_DO_IOCTL, "entering CDROM_CHANGER_NSLOTS\n"); 
2460                 return cdi->capacity;
2461                 }
2462         }
2463
2464         /* use the ioctls that are implemented through the generic_packet()
2465            interface. this may look at bit funny, but if -ENOTTY is
2466            returned that particular ioctl is not implemented and we
2467            let it go through the device specific ones. */
2468         if (CDROM_CAN(CDC_GENERIC_PACKET)) {
2469                 ret = mmc_ioctl(cdi, cmd, arg);
2470                 if (ret != -ENOTTY) {
2471                         return ret;
2472                 }
2473         }
2474
2475         /* note: most of the cdinfo() calls are commented out here,
2476            because they fill up the sys log when CD players poll
2477            the drive. */
2478         switch (cmd) {
2479         case CDROMSUBCHNL: {
2480                 struct cdrom_subchnl q;
2481                 u_char requested, back;
2482                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2483                         return -ENOSYS;
2484                 /* cdinfo(CD_DO_IOCTL,"entering CDROMSUBCHNL\n");*/ 
2485                 IOCTL_IN(arg, struct cdrom_subchnl, q);
2486                 requested = q.cdsc_format;
2487                 if (!((requested == CDROM_MSF) ||
2488                       (requested == CDROM_LBA)))
2489                         return -EINVAL;
2490                 q.cdsc_format = CDROM_MSF;
2491                 if ((ret=cdo->audio_ioctl(cdi, cmd, &q)))
2492                         return ret;
2493                 back = q.cdsc_format; /* local copy */
2494                 sanitize_format(&q.cdsc_absaddr, &back, requested);
2495                 sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);
2496                 IOCTL_OUT(arg, struct cdrom_subchnl, q);
2497                 /* cdinfo(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */ 
2498                 return 0;
2499                 }
2500         case CDROMREADTOCHDR: {
2501                 struct cdrom_tochdr header;
2502                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2503                         return -ENOSYS;
2504                 /* cdinfo(CD_DO_IOCTL, "entering CDROMREADTOCHDR\n"); */ 
2505                 IOCTL_IN(arg, struct cdrom_tochdr, header);
2506                 if ((ret=cdo->audio_ioctl(cdi, cmd, &header)))
2507                         return ret;
2508                 IOCTL_OUT(arg, struct cdrom_tochdr, header);
2509                 /* cdinfo(CD_DO_IOCTL, "CDROMREADTOCHDR successful\n"); */ 
2510                 return 0;
2511                 }
2512         case CDROMREADTOCENTRY: {
2513                 struct cdrom_tocentry entry;
2514                 u_char requested_format;
2515                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2516                         return -ENOSYS;
2517                 /* cdinfo(CD_DO_IOCTL, "entering CDROMREADTOCENTRY\n"); */ 
2518                 IOCTL_IN(arg, struct cdrom_tocentry, entry);
2519                 requested_format = entry.cdte_format;
2520                 if (!((requested_format == CDROM_MSF) || 
2521                         (requested_format == CDROM_LBA)))
2522                                 return -EINVAL;
2523                 /* make interface to low-level uniform */
2524                 entry.cdte_format = CDROM_MSF;
2525                 if ((ret=cdo->audio_ioctl(cdi, cmd, &entry)))
2526                         return ret;
2527                 sanitize_format(&entry.cdte_addr,
2528                 &entry.cdte_format, requested_format);
2529                 IOCTL_OUT(arg, struct cdrom_tocentry, entry);
2530                 /* cdinfo(CD_DO_IOCTL, "CDROMREADTOCENTRY successful\n"); */ 
2531                 return 0;
2532                 }
2533         case CDROMPLAYMSF: {
2534                 struct cdrom_msf msf;
2535                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2536                         return -ENOSYS;
2537                 cdinfo(CD_DO_IOCTL, "entering CDROMPLAYMSF\n"); 
2538                 IOCTL_IN(arg, struct cdrom_msf, msf);
2539                 return cdo->audio_ioctl(cdi, cmd, &msf);
2540                 }
2541         case CDROMPLAYTRKIND: {
2542                 struct cdrom_ti ti;
2543                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2544                         return -ENOSYS;
2545                 cdinfo(CD_DO_IOCTL, "entering CDROMPLAYTRKIND\n"); 
2546                 IOCTL_IN(arg, struct cdrom_ti, ti);
2547                 CHECKAUDIO;
2548                 return cdo->audio_ioctl(cdi, cmd, &ti);
2549                 }
2550         case CDROMVOLCTRL: {
2551                 struct cdrom_volctrl volume;
2552                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2553                         return -ENOSYS;
2554                 cdinfo(CD_DO_IOCTL, "entering CDROMVOLCTRL\n"); 
2555                 IOCTL_IN(arg, struct cdrom_volctrl, volume);
2556                 return cdo->audio_ioctl(cdi, cmd, &volume);
2557                 }
2558         case CDROMVOLREAD: {
2559                 struct cdrom_volctrl volume;
2560                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2561                         return -ENOSYS;
2562                 cdinfo(CD_DO_IOCTL, "entering CDROMVOLREAD\n"); 
2563                 if ((ret=cdo->audio_ioctl(cdi, cmd, &volume)))
2564                         return ret;
2565                 IOCTL_OUT(arg, struct cdrom_volctrl, volume);
2566                 return 0;
2567                 }
2568         case CDROMSTART:
2569         case CDROMSTOP:
2570         case CDROMPAUSE:
2571         case CDROMRESUME: {
2572                 if (!CDROM_CAN(CDC_PLAY_AUDIO))
2573                         return -ENOSYS;
2574                 cdinfo(CD_DO_IOCTL, "doing audio ioctl (start/stop/pause/resume)\n"); 
2575                 CHECKAUDIO;
2576                 return cdo->audio_ioctl(cdi, cmd, NULL);
2577                 }
2578         } /* switch */
2579
2580         /* do the device specific ioctls */
2581         if (CDROM_CAN(CDC_IOCTLS))
2582                 return cdo->dev_ioctl(cdi, cmd, arg);
2583         
2584         return -ENOSYS;
2585 }
2586
2587 static inline
2588 int msf_to_lba(char m, char s, char f)
2589 {
2590         return (((m * CD_SECS) + s) * CD_FRAMES + f) - CD_MSF_OFFSET;
2591 }
2592
2593 /*
2594  * Required when we need to use READ_10 to issue other than 2048 block
2595  * reads
2596  */
2597 static int cdrom_switch_blocksize(struct cdrom_device_info *cdi, int size)
2598 {
2599         struct cdrom_device_ops *cdo = cdi->ops;
2600         struct packet_command cgc;
2601         struct modesel_head mh;
2602
2603         memset(&mh, 0, sizeof(mh));
2604         mh.block_desc_length = 0x08;
2605         mh.block_length_med = (size >> 8) & 0xff;
2606         mh.block_length_lo = size & 0xff;
2607
2608         memset(&cgc, 0, sizeof(cgc));
2609         cgc.cmd[0] = 0x15;
2610         cgc.cmd[1] = 1 << 4;
2611         cgc.cmd[4] = 12;
2612         cgc.buflen = sizeof(mh);
2613         cgc.buffer = (char *) &mh;
2614         cgc.data_direction = CGC_DATA_WRITE;
2615         mh.block_desc_length = 0x08;
2616         mh.block_length_med = (size >> 8) & 0xff;
2617         mh.block_length_lo = size & 0xff;
2618
2619         return cdo->generic_packet(cdi, &cgc);
2620 }
2621
2622 static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd,
2623                      unsigned long arg)
2624 {               
2625         struct cdrom_device_ops *cdo = cdi->ops;
2626         struct packet_command cgc;
2627         struct request_sense sense;
2628         unsigned char buffer[32];
2629         int ret = 0;
2630
2631         memset(&cgc, 0, sizeof(cgc));
2632
2633         /* build a unified command and queue it through
2634            cdo->generic_packet() */
2635         switch (cmd) {
2636         case CDROMREADRAW:
2637         case CDROMREADMODE1:
2638         case CDROMREADMODE2: {
2639                 struct cdrom_msf msf;
2640                 int blocksize = 0, format = 0, lba;
2641                 
2642                 switch (cmd) {
2643                 case CDROMREADRAW:
2644                         blocksize = CD_FRAMESIZE_RAW;
2645                         break;
2646                 case CDROMREADMODE1:
2647                         blocksize = CD_FRAMESIZE;
2648                         format = 2;
2649                         break;
2650                 case CDROMREADMODE2:
2651                         blocksize = CD_FRAMESIZE_RAW0;
2652                         break;
2653                 }
2654                 IOCTL_IN(arg, struct cdrom_msf, msf);
2655                 lba = msf_to_lba(msf.cdmsf_min0,msf.cdmsf_sec0,msf.cdmsf_frame0);
2656                 /* FIXME: we need upper bound checking, too!! */
2657                 if (lba < 0)
2658                         return -EINVAL;
2659                 cgc.buffer = (char *) kmalloc(blocksize, GFP_KERNEL);
2660                 if (cgc.buffer == NULL)
2661                         return -ENOMEM;
2662                 memset(&sense, 0, sizeof(sense));
2663                 cgc.sense = &sense;
2664                 cgc.data_direction = CGC_DATA_READ;
2665                 ret = cdrom_read_block(cdi, &cgc, lba, 1, format, blocksize);
2666                 if (ret && sense.sense_key==0x05 && sense.asc==0x20 && sense.ascq==0x00) {
2667                         /*
2668                          * SCSI-II devices are not required to support
2669                          * READ_CD, so let's try switching block size
2670                          */
2671                         /* FIXME: switch back again... */
2672                         if ((ret = cdrom_switch_blocksize(cdi, blocksize))) {
2673                                 kfree(cgc.buffer);
2674                                 return ret;
2675                         }
2676                         cgc.sense = NULL;
2677                         ret = cdrom_read_cd(cdi, &cgc, lba, blocksize, 1);
2678                         ret |= cdrom_switch_blocksize(cdi, blocksize);
2679                 }
2680                 if (!ret && copy_to_user((char __user *)arg, cgc.buffer, blocksize))
2681                         ret = -EFAULT;
2682                 kfree(cgc.buffer);
2683                 return ret;
2684                 }
2685         case CDROMREADAUDIO: {
2686                 struct cdrom_read_audio ra;
2687                 int lba;
2688
2689                 IOCTL_IN(arg, struct cdrom_read_audio, ra);
2690
2691                 if (ra.addr_format == CDROM_MSF)
2692                         lba = msf_to_lba(ra.addr.msf.minute,
2693                                          ra.addr.msf.second,
2694                                          ra.addr.msf.frame);
2695                 else if (ra.addr_format == CDROM_LBA)
2696                         lba = ra.addr.lba;
2697                 else
2698                         return -EINVAL;
2699
2700                 /* FIXME: we need upper bound checking, too!! */
2701                 if (lba < 0 || ra.nframes <= 0 || ra.nframes > CD_FRAMES)
2702                         return -EINVAL;
2703
2704                 return cdrom_read_cdda(cdi, ra.buf, lba, ra.nframes);
2705                 }
2706         case CDROMSUBCHNL: {
2707                 struct cdrom_subchnl q;
2708                 u_char requested, back;
2709                 IOCTL_IN(arg, struct cdrom_subchnl, q);
2710                 requested = q.cdsc_format;
2711                 if (!((requested == CDROM_MSF) ||
2712                       (requested == CDROM_LBA)))
2713                         return -EINVAL;
2714                 q.cdsc_format = CDROM_MSF;
2715                 if ((ret = cdrom_read_subchannel(cdi, &q, 0)))
2716                         return ret;
2717                 back = q.cdsc_format; /* local copy */
2718                 sanitize_format(&q.cdsc_absaddr, &back, requested);
2719                 sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);
2720                 IOCTL_OUT(arg, struct cdrom_subchnl, q);
2721                 /* cdinfo(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */ 
2722                 return 0;
2723                 }
2724         case CDROMPLAYMSF: {
2725                 struct cdrom_msf msf;
2726                 cdinfo(CD_DO_IOCTL, "entering CDROMPLAYMSF\n");
2727                 IOCTL_IN(arg, struct cdrom_msf, msf);
2728                 cgc.cmd[0] = GPCMD_PLAY_AUDIO_MSF;
2729                 cgc.cmd[3] = msf.cdmsf_min0;
2730                 cgc.cmd[4] = msf.cdmsf_sec0;
2731                 cgc.cmd[5] = msf.cdmsf_frame0;
2732                 cgc.cmd[6] = msf.cdmsf_min1;
2733                 cgc.cmd[7] = msf.cdmsf_sec1;
2734                 cgc.cmd[8] = msf.cdmsf_frame1;
2735                 cgc.data_direction = CGC_DATA_NONE;
2736                 return cdo->generic_packet(cdi, &cgc);
2737                 }
2738         case CDROMPLAYBLK: {
2739                 struct cdrom_blk blk;
2740                 cdinfo(CD_DO_IOCTL, "entering CDROMPLAYBLK\n");
2741                 IOCTL_IN(arg, struct cdrom_blk, blk);
2742                 cgc.cmd[0] = GPCMD_PLAY_AUDIO_10;
2743                 cgc.cmd[2] = (blk.from >> 24) & 0xff;
2744                 cgc.cmd[3] = (blk.from >> 16) & 0xff;
2745                 cgc.cmd[4] = (blk.from >>  8) & 0xff;
2746                 cgc.cmd[5] = blk.from & 0xff;
2747                 cgc.cmd[7] = (blk.len >> 8) & 0xff;
2748                 cgc.cmd[8] = blk.len & 0xff;
2749                 cgc.data_direction = CGC_DATA_NONE;
2750                 return cdo->generic_packet(cdi, &cgc);
2751                 }
2752         case CDROMVOLCTRL:
2753         case CDROMVOLREAD: {
2754                 struct cdrom_volctrl volctrl;
2755                 char mask[sizeof(buffer)];
2756                 unsigned short offset;
2757
2758                 cdinfo(CD_DO_IOCTL, "entering CDROMVOLUME\n");
2759
2760                 IOCTL_IN(arg, struct cdrom_volctrl, volctrl);
2761
2762                 cgc.buffer = buffer;
2763                 cgc.buflen = 24;
2764                 if ((ret = cdrom_mode_sense(cdi, &cgc, GPMODE_AUDIO_CTL_PAGE, 0)))
2765                     return ret;
2766                 
2767                 /* originally the code depended on buffer[1] to determine
2768                    how much data is available for transfer. buffer[1] is
2769                    unfortunately ambigious and the only reliable way seem
2770                    to be to simply skip over the block descriptor... */
2771                 offset = 8 + be16_to_cpu(*(unsigned short *)(buffer+6));
2772
2773                 if (offset + 16 > sizeof(buffer))
2774                         return -E2BIG;
2775
2776                 if (offset + 16 > cgc.buflen) {
2777                         cgc.buflen = offset+16;
2778                         ret = cdrom_mode_sense(cdi, &cgc,
2779                                                 GPMODE_AUDIO_CTL_PAGE, 0);
2780                         if (ret)
2781                                 return ret;
2782                 }
2783
2784                 /* sanity check */
2785                 if ((buffer[offset] & 0x3f) != GPMODE_AUDIO_CTL_PAGE ||
2786                                 buffer[offset+1] < 14)
2787                         return -EINVAL;
2788
2789                 /* now we have the current volume settings. if it was only
2790                    a CDROMVOLREAD, return these values */
2791                 if (cmd == CDROMVOLREAD) {
2792                         volctrl.channel0 = buffer[offset+9];
2793                         volctrl.channel1 = buffer[offset+11];
2794                         volctrl.channel2 = buffer[offset+13];
2795                         volctrl.channel3 = buffer[offset+15];
2796                         IOCTL_OUT(arg, struct cdrom_volctrl, volctrl);
2797                         return 0;
2798                 }
2799                 
2800                 /* get the volume mask */
2801                 cgc.buffer = mask;
2802                 if ((ret = cdrom_mode_sense(cdi, &cgc, 
2803                                 GPMODE_AUDIO_CTL_PAGE, 1)))
2804                         return ret;
2805
2806                 buffer[offset+9] = volctrl.channel0 & mask[offset+9];
2807                 buffer[offset+11] = volctrl.channel1 & mask[offset+11];
2808                 buffer[offset+13] = volctrl.channel2 & mask[offset+13];
2809                 buffer[offset+15] = volctrl.channel3 & mask[offset+15];
2810
2811                 /* set volume */
2812                 cgc.buffer = buffer + offset - 8;
2813                 memset(cgc.buffer, 0, 8);
2814                 return cdrom_mode_select(cdi, &cgc);
2815                 }
2816
2817         case CDROMSTART:
2818         case CDROMSTOP: {
2819                 cdinfo(CD_DO_IOCTL, "entering CDROMSTART/CDROMSTOP\n"); 
2820                 cgc.cmd[0] = GPCMD_START_STOP_UNIT;
2821                 cgc.cmd[1] = 1;
2822                 cgc.cmd[4] = (cmd == CDROMSTART) ? 1 : 0;
2823                 cgc.data_direction = CGC_DATA_NONE;
2824                 return cdo->generic_packet(cdi, &cgc);
2825                 }
2826
2827         case CDROMPAUSE:
2828         case CDROMRESUME: {
2829                 cdinfo(CD_DO_IOCTL, "entering CDROMPAUSE/CDROMRESUME\n"); 
2830                 cgc.cmd[0] = GPCMD_PAUSE_RESUME;
2831                 cgc.cmd[8] = (cmd == CDROMRESUME) ? 1 : 0;
2832                 cgc.data_direction = CGC_DATA_NONE;
2833                 return cdo->generic_packet(cdi, &cgc);
2834                 }
2835
2836         case DVD_READ_STRUCT: {
2837                 dvd_struct *s;
2838                 int size = sizeof(dvd_struct);
2839                 if (!CDROM_CAN(CDC_DVD))
2840                         return -ENOSYS;
2841                 if ((s = (dvd_struct *) kmalloc(size, GFP_KERNEL)) == NULL)
2842                         return -ENOMEM;
2843                 cdinfo(CD_DO_IOCTL, "entering DVD_READ_STRUCT\n"); 
2844                 if (copy_from_user(s, (dvd_struct __user *)arg, size)) {
2845                         kfree(s);
2846                         return -EFAULT;
2847                 }
2848                 if ((ret = dvd_read_struct(cdi, s))) {
2849                         kfree(s);
2850                         return ret;
2851                 }
2852                 if (copy_to_user((dvd_struct __user *)arg, s, size))
2853                         ret = -EFAULT;
2854                 kfree(s);
2855                 return ret;
2856                 }
2857
2858         case DVD_AUTH: {
2859                 dvd_authinfo ai;
2860                 if (!CDROM_CAN(CDC_DVD))
2861                         return -ENOSYS;
2862                 cdinfo(CD_DO_IOCTL, "entering DVD_AUTH\n"); 
2863                 IOCTL_IN(arg, dvd_authinfo, ai);
2864                 if ((ret = dvd_do_auth (cdi, &ai)))
2865                         return ret;
2866                 IOCTL_OUT(arg, dvd_authinfo, ai);
2867                 return 0;
2868                 }
2869
2870         case CDROM_NEXT_WRITABLE: {
2871                 long next = 0;
2872                 cdinfo(CD_DO_IOCTL, "entering CDROM_NEXT_WRITABLE\n"); 
2873                 if ((ret = cdrom_get_next_writable(cdi, &next)))
2874                         return ret;
2875                 IOCTL_OUT(arg, long, next);
2876                 return 0;
2877                 }
2878         case CDROM_LAST_WRITTEN: {
2879                 long last = 0;
2880                 cdinfo(CD_DO_IOCTL, "entering CDROM_LAST_WRITTEN\n"); 
2881                 if ((ret = cdrom_get_last_written(cdi, &last)))
2882                         return ret;
2883                 IOCTL_OUT(arg, long, last);
2884                 return 0;
2885                 }
2886         } /* switch */
2887
2888         return -ENOTTY;
2889 }
2890
2891 static int cdrom_get_track_info(struct cdrom_device_info *cdi, __u16 track, __u8 type,
2892                          track_information *ti)
2893 {
2894         struct cdrom_device_ops *cdo = cdi->ops;
2895         struct packet_command cgc;
2896         int ret, buflen;
2897
2898         init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);
2899         cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;
2900         cgc.cmd[1] = type & 3;
2901         cgc.cmd[4] = (track & 0xff00) >> 8;
2902         cgc.cmd[5] = track & 0xff;
2903         cgc.cmd[8] = 8;
2904         cgc.quiet = 1;
2905
2906         if ((ret = cdo->generic_packet(cdi, &cgc)))
2907                 return ret;
2908         
2909         buflen = be16_to_cpu(ti->track_information_length) +
2910                      sizeof(ti->track_information_length);
2911
2912         if (buflen > sizeof(track_information))
2913                 buflen = sizeof(track_information);
2914
2915         cgc.cmd[8] = cgc.buflen = buflen;
2916         if ((ret = cdo->generic_packet(cdi, &cgc)))
2917                 return ret;
2918
2919         /* return actual fill size */
2920         return buflen;
2921 }
2922
2923 /* requires CD R/RW */
2924 static int cdrom_get_disc_info(struct cdrom_device_info *cdi, disc_information *di)
2925 {
2926         struct cdrom_device_ops *cdo = cdi->ops;
2927         struct packet_command cgc;
2928         int ret, buflen;
2929
2930         /* set up command and get the disc info */
2931         init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);
2932         cgc.cmd[0] = GPCMD_READ_DISC_INFO;
2933         cgc.cmd[8] = cgc.buflen = 2;
2934         cgc.quiet = 1;
2935
2936         if ((ret = cdo->generic_packet(cdi, &cgc)))
2937                 return ret;
2938
2939         /* not all drives have the same disc_info length, so requeue
2940          * packet with the length the drive tells us it can supply
2941          */
2942         buflen = be16_to_cpu(di->disc_information_length) +
2943                      sizeof(di->disc_information_length);
2944
2945         if (buflen > sizeof(disc_information))
2946                 buflen = sizeof(disc_information);
2947
2948         cgc.cmd[8] = cgc.buflen = buflen;
2949         if ((ret = cdo->generic_packet(cdi, &cgc)))
2950                 return ret;
2951
2952         /* return actual fill size */
2953         return buflen;
2954 }
2955
2956 /* return the last written block on the CD-R media. this is for the udf
2957    file system. */
2958 int cdrom_get_last_written(struct cdrom_device_info *cdi, long *last_written)
2959 {
2960         struct cdrom_tocentry toc;
2961         disc_information di;
2962         track_information ti;
2963         __u32 last_track;
2964         int ret = -1, ti_size;
2965
2966         if (!CDROM_CAN(CDC_GENERIC_PACKET))
2967                 goto use_toc;
2968
2969         ret = cdrom_get_disc_info(cdi, &di);
2970         if (ret < (int)(offsetof(typeof(di), last_track_lsb)
2971                         + sizeof(di.last_track_lsb)))
2972                 goto use_toc;
2973
2974         /* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */
2975         last_track = (di.last_track_msb << 8) | di.last_track_lsb;
2976         ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
2977         if (ti_size < (int)offsetof(typeof(ti), track_start))
2978                 goto use_toc;
2979
2980         /* if this track is blank, try the previous. */
2981         if (ti.blank) {
2982                 if (last_track==1)
2983                         goto use_toc;
2984                 last_track--;
2985                 ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
2986         }
2987
2988         if (ti_size < (int)(offsetof(typeof(ti), track_size)
2989                                 + sizeof(ti.track_size)))
2990                 goto use_toc;
2991
2992         /* if last recorded field is valid, return it. */
2993         if (ti.lra_v && ti_size >= (int)(offsetof(typeof(ti), last_rec_address)
2994                                 + sizeof(ti.last_rec_address))) {
2995                 *last_written = be32_to_cpu(ti.last_rec_address);
2996         } else {
2997                 /* make it up instead */
2998                 *last_written = be32_to_cpu(ti.track_start) +
2999                                 be32_to_cpu(ti.track_size);
3000                 if (ti.free_blocks)
3001                         *last_written -= (be32_to_cpu(ti.free_blocks) + 7);
3002         }
3003         return 0;
3004
3005         /* this is where we end up if the drive either can't do a
3006            GPCMD_READ_DISC_INFO or GPCMD_READ_TRACK_RZONE_INFO or if
3007            it doesn't give enough information or fails. then we return
3008            the toc contents. */
3009 use_toc:
3010         toc.cdte_format = CDROM_MSF;
3011         toc.cdte_track = CDROM_LEADOUT;
3012         if ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &toc)))
3013                 return ret;
3014         sanitize_format(&toc.cdte_addr, &toc.cdte_format, CDROM_LBA);
3015         *last_written = toc.cdte_addr.lba;
3016         return 0;
3017 }
3018
3019 /* return the next writable block. also for udf file system. */
3020 static int cdrom_get_next_writable(struct cdrom_device_info *cdi, long *next_writable)
3021 {
3022         disc_information di;
3023         track_information ti;
3024         __u16 last_track;
3025         int ret, ti_size;
3026
3027         if (!CDROM_CAN(CDC_GENERIC_PACKET))
3028                 goto use_last_written;
3029
3030         ret = cdrom_get_disc_info(cdi, &di);
3031         if (ret < 0 || ret < offsetof(typeof(di), last_track_lsb)
3032                                 + sizeof(di.last_track_lsb))
3033                 goto use_last_written;
3034
3035         /* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */
3036         last_track = (di.last_track_msb << 8) | di.last_track_lsb;
3037         ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
3038         if (ti_size < 0 || ti_size < offsetof(typeof(ti), track_start))
3039                 goto use_last_written;
3040
3041         /* if this track is blank, try the previous. */
3042         if (ti.blank) {
3043                 if (last_track == 1)
3044                         goto use_last_written;
3045                 last_track--;
3046                 ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);
3047                 if (ti_size < 0)
3048                         goto use_last_written;
3049         }
3050
3051         /* if next recordable address field is valid, use it. */
3052         if (ti.nwa_v && ti_size >= offsetof(typeof(ti), next_writable)
3053                                 + sizeof(ti.next_writable)) {
3054                 *next_writable = be32_to_cpu(ti.next_writable);
3055                 return 0;
3056         }
3057
3058 use_last_written:
3059         if ((ret = cdrom_get_last_written(cdi, next_writable))) {
3060                 *next_writable = 0;
3061                 return ret;
3062         } else {
3063                 *next_writable += 7;
3064                 return 0;
3065         }
3066 }
3067
3068 EXPORT_SYMBOL(cdrom_get_last_written);
3069 EXPORT_SYMBOL(register_cdrom);
3070 EXPORT_SYMBOL(unregister_cdrom);
3071 EXPORT_SYMBOL(cdrom_open);
3072 EXPORT_SYMBOL(cdrom_release);
3073 EXPORT_SYMBOL(cdrom_ioctl);
3074 EXPORT_SYMBOL(cdrom_media_changed);
3075 EXPORT_SYMBOL(cdrom_number_of_slots);
3076 EXPORT_SYMBOL(cdrom_mode_select);
3077 EXPORT_SYMBOL(cdrom_mode_sense);
3078 EXPORT_SYMBOL(init_cdrom_command);
3079 EXPORT_SYMBOL(cdrom_get_media_event);
3080 EXPORT_SYMBOL(cdrom_is_mrw);
3081 EXPORT_SYMBOL(cdrom_is_random_writable);
3082
3083 #ifdef CONFIG_SYSCTL
3084
3085 #define CDROM_STR_SIZE 1000
3086
3087 struct cdrom_sysctl_settings {
3088         char    info[CDROM_STR_SIZE];   /* general info */
3089         int     autoclose;              /* close tray upon mount, etc */
3090         int     autoeject;              /* eject on umount */
3091         int     debug;                  /* turn on debugging messages */
3092         int     lock;                   /* lock the door on device open */
3093         int     check;                  /* check media type */
3094 } cdrom_sysctl_settings;
3095
3096 int cdrom_sysctl_info(ctl_table *ctl, int write, struct file * filp,
3097                            void __user *buffer, size_t *lenp, loff_t *ppos)
3098 {
3099         int pos;
3100         struct cdrom_device_info *cdi;
3101         char *info = cdrom_sysctl_settings.info;
3102         
3103         if (!*lenp || (*ppos && !write)) {
3104                 *lenp = 0;
3105                 return 0;
3106         }
3107
3108         pos = sprintf(info, "CD-ROM information, " VERSION "\n");
3109         
3110         pos += sprintf(info+pos, "\ndrive name:\t");
3111         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3112             pos += sprintf(info+pos, "\t%s", cdi->name);
3113
3114         pos += sprintf(info+pos, "\ndrive speed:\t");
3115         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3116             pos += sprintf(info+pos, "\t%d", cdi->speed);
3117
3118         pos += sprintf(info+pos, "\ndrive # of slots:");
3119         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3120             pos += sprintf(info+pos, "\t%d", cdi->capacity);
3121
3122         pos += sprintf(info+pos, "\nCan close tray:\t");
3123         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3124             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_CLOSE_TRAY) != 0);
3125
3126         pos += sprintf(info+pos, "\nCan open tray:\t");
3127         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3128             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_OPEN_TRAY) != 0);
3129
3130         pos += sprintf(info+pos, "\nCan lock tray:\t");
3131         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3132             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_LOCK) != 0);
3133
3134         pos += sprintf(info+pos, "\nCan change speed:");
3135         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3136             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_SELECT_SPEED) != 0);
3137
3138         pos += sprintf(info+pos, "\nCan select disk:");
3139         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3140             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_SELECT_DISC) != 0);
3141
3142         pos += sprintf(info+pos, "\nCan read multisession:");
3143         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3144             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_MULTI_SESSION) != 0);
3145
3146         pos += sprintf(info+pos, "\nCan read MCN:\t");
3147         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3148             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_MCN) != 0);
3149
3150         pos += sprintf(info+pos, "\nReports media changed:");
3151         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3152             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_MEDIA_CHANGED) != 0);
3153
3154         pos += sprintf(info+pos, "\nCan play audio:\t");
3155         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3156             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_PLAY_AUDIO) != 0);
3157
3158         pos += sprintf(info+pos, "\nCan write CD-R:\t");
3159         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3160             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_CD_R) != 0);
3161
3162         pos += sprintf(info+pos, "\nCan write CD-RW:");
3163         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3164             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_CD_RW) != 0);
3165
3166         pos += sprintf(info+pos, "\nCan read DVD:\t");
3167         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3168             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_DVD) != 0);
3169
3170         pos += sprintf(info+pos, "\nCan write DVD-R:");
3171         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3172             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_DVD_R) != 0);
3173
3174         pos += sprintf(info+pos, "\nCan write DVD-RAM:");
3175         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3176             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_DVD_RAM) != 0);
3177
3178         pos += sprintf(info+pos, "\nCan read MRW:\t");
3179         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3180             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_MRW) != 0);
3181
3182         pos += sprintf(info+pos, "\nCan write MRW:\t");
3183         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3184             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_MRW_W) != 0);
3185
3186         pos += sprintf(info+pos, "\nCan write RAM:\t");
3187         for (cdi=topCdromPtr;cdi!=NULL;cdi=cdi->next)
3188             pos += sprintf(info+pos, "\t%d", CDROM_CAN(CDC_RAM) != 0);
3189
3190         strcpy(info+pos,"\n\n");
3191                 
3192         return proc_dostring(ctl, write, filp, buffer, lenp, ppos);
3193 }
3194
3195 /* Unfortunately, per device settings are not implemented through
3196    procfs/sysctl yet. When they are, this will naturally disappear. For now
3197    just update all drives. Later this will become the template on which
3198    new registered drives will be based. */
3199 void cdrom_update_settings(void)
3200 {
3201         struct cdrom_device_info *cdi;
3202
3203         for (cdi = topCdromPtr; cdi != NULL; cdi = cdi->next) {
3204                 if (autoclose && CDROM_CAN(CDC_CLOSE_TRAY))
3205                         cdi->options |= CDO_AUTO_CLOSE;
3206                 else if (!autoclose)
3207                         cdi->options &= ~CDO_AUTO_CLOSE;
3208                 if (autoeject && CDROM_CAN(CDC_OPEN_TRAY))
3209                         cdi->options |= CDO_AUTO_EJECT;
3210                 else if (!autoeject)
3211                         cdi->options &= ~CDO_AUTO_EJECT;
3212                 if (lockdoor && CDROM_CAN(CDC_LOCK))
3213                         cdi->options |= CDO_LOCK;
3214                 else if (!lockdoor)
3215                         cdi->options &= ~CDO_LOCK;
3216                 if (check_media_type)
3217                         cdi->options |= CDO_CHECK_TYPE;
3218                 else
3219                         cdi->options &= ~CDO_CHECK_TYPE;
3220         }
3221 }
3222
3223 static int cdrom_sysctl_handler(ctl_table *ctl, int write, struct file * filp,
3224                                 void __user *buffer, size_t *lenp, loff_t *ppos)
3225 {
3226         int *valp = ctl->data;
3227         int val = *valp;
3228         int ret;
3229         
3230         ret = proc_dointvec(ctl, write, filp, buffer, lenp, ppos);
3231
3232         if (write && *valp != val) {
3233         
3234                 /* we only care for 1 or 0. */
3235                 if (*valp)
3236                         *valp = 1;
3237                 else
3238                         *valp = 0;
3239
3240                 switch (ctl->ctl_name) {
3241                 case DEV_CDROM_AUTOCLOSE: {
3242                         if (valp == &cdrom_sysctl_settings.autoclose)
3243                                 autoclose = cdrom_sysctl_settings.autoclose;
3244                         break;
3245                         }
3246                 case DEV_CDROM_AUTOEJECT: {
3247                         if (valp == &cdrom_sysctl_settings.autoeject)
3248                                 autoeject = cdrom_sysctl_settings.autoeject;
3249                         break;
3250                         }
3251                 case DEV_CDROM_DEBUG: {
3252                         if (valp == &cdrom_sysctl_settings.debug)
3253                                 debug = cdrom_sysctl_settings.debug;
3254                         break;
3255                         }
3256                 case DEV_CDROM_LOCK: {
3257                         if (valp == &cdrom_sysctl_settings.lock)
3258                                 lockdoor = cdrom_sysctl_settings.lock;
3259                         break;
3260                         }
3261                 case DEV_CDROM_CHECK_MEDIA: {
3262                         if (valp == &cdrom_sysctl_settings.check)
3263                                 check_media_type = cdrom_sysctl_settings.check;
3264                         break;
3265                         }
3266                 }
3267                 /* update the option flags according to the changes. we
3268                    don't have per device options through sysctl yet,
3269                    but we will have and then this will disappear. */
3270                 cdrom_update_settings();
3271         }
3272
3273         return ret;
3274 }
3275
3276 /* Place files in /proc/sys/dev/cdrom */
3277 ctl_table cdrom_table[] = {
3278         {
3279                 .ctl_name       = DEV_CDROM_INFO,
3280                 .procname       = "info",
3281                 .data           = &cdrom_sysctl_settings.info, 
3282                 .maxlen         = CDROM_STR_SIZE,
3283                 .mode           = 0444,
3284                 .proc_handler   = &cdrom_sysctl_info,
3285         },
3286         {
3287                 .ctl_name       = DEV_CDROM_AUTOCLOSE,
3288                 .procname       = "autoclose",
3289                 .data           = &cdrom_sysctl_settings.autoclose,
3290                 .maxlen         = sizeof(int),
3291                 .mode           = 0644,
3292                 .proc_handler   = &cdrom_sysctl_handler,
3293         },
3294         {
3295                 .ctl_name       = DEV_CDROM_AUTOEJECT,
3296                 .procname       = "autoeject",
3297                 .data           = &cdrom_sysctl_settings.autoeject,
3298                 .maxlen         = sizeof(int),
3299                 .mode           = 0644,
3300                 .proc_handler   = &cdrom_sysctl_handler,
3301         },
3302         {
3303                 .ctl_name       = DEV_CDROM_DEBUG,
3304                 .procname       = "debug",
3305                 .data           = &cdrom_sysctl_settings.debug,
3306                 .maxlen         = sizeof(int),
3307                 .mode           = 0644,
3308                 .proc_handler   = &cdrom_sysctl_handler,
3309         },
3310         {
3311                 .ctl_name       = DEV_CDROM_LOCK,
3312                 .procname       = "lock",
3313                 .data           = &cdrom_sysctl_settings.lock,
3314                 .maxlen         = sizeof(int),
3315                 .mode           = 0644,
3316                 .proc_handler   = &cdrom_sysctl_handler,
3317         },
3318         {
3319                 .ctl_name       = DEV_CDROM_CHECK_MEDIA,
3320                 .procname       = "check_media",
3321                 .data           = &cdrom_sysctl_settings.check,
3322                 .maxlen         = sizeof(int),
3323                 .mode           = 0644,
3324                 .proc_handler   = &cdrom_sysctl_handler
3325         },
3326         { .ctl_name = 0 }
3327 };
3328
3329 ctl_table cdrom_cdrom_table[] = {
3330         {
3331                 .ctl_name       = DEV_CDROM,
3332                 .procname       = "cdrom",
3333                 .maxlen         = 0,
3334                 .mode           = 0555,
3335                 .child          = cdrom_table,
3336         },
3337         { .ctl_name = 0 }
3338 };
3339
3340 /* Make sure that /proc/sys/dev is there */
3341 ctl_table cdrom_root_table[] = {
3342         {
3343                 .ctl_name       = CTL_DEV,
3344                 .procname       = "dev",
3345                 .maxlen         = 0,
3346                 .mode           = 0555,
3347                 .child          = cdrom_cdrom_table,
3348         },
3349         { .ctl_name = 0 }
3350 };
3351 static struct ctl_table_header *cdrom_sysctl_header;
3352
3353 static void cdrom_sysctl_register(void)
3354 {
3355         static int initialized;
3356
3357         if (initialized == 1)
3358                 return;
3359
3360         cdrom_sysctl_header = register_sysctl_table(cdrom_root_table, 1);
3361         if (cdrom_root_table->ctl_name && cdrom_root_table->child->de)
3362                 cdrom_root_table->child->de->owner = THIS_MODULE;
3363
3364         /* set the defaults */
3365         cdrom_sysctl_settings.autoclose = autoclose;
3366         cdrom_sysctl_settings.autoeject = autoeject;
3367         cdrom_sysctl_settings.debug = debug;
3368         cdrom_sysctl_settings.lock = lockdoor;
3369         cdrom_sysctl_settings.check = check_media_type;
3370
3371         initialized = 1;
3372 }
3373
3374 static void cdrom_sysctl_unregister(void)
3375 {
3376         if (cdrom_sysctl_header)
3377                 unregister_sysctl_table(cdrom_sysctl_header);
3378 }
3379
3380 #endif /* CONFIG_SYSCTL */
3381
3382 static int __init cdrom_init(void)
3383 {
3384 #ifdef CONFIG_SYSCTL
3385         cdrom_sysctl_register();
3386 #endif
3387         return 0;
3388 }
3389
3390 static void __exit cdrom_exit(void)
3391 {
3392         printk(KERN_INFO "Uniform CD-ROM driver unloaded\n");
3393 #ifdef CONFIG_SYSCTL
3394         cdrom_sysctl_unregister();
3395 #endif
3396 }
3397
3398 module_init(cdrom_init);
3399 module_exit(cdrom_exit);
3400 MODULE_LICENSE("GPL");