ntdll: Implement RtlWriteRegistryValue and forward ntoskrnl to it.
[wine] / dlls / ntdll / cdrom.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /* Main file for CD-ROM support
3  *
4  * Copyright 1994 Martin Ayotte
5  * Copyright 1999, 2001, 2003 Eric Pouech
6  * Copyright 2000 Andreas Mohr
7  * Copyright 2005 Ivan Leo Puoti
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <errno.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #ifdef HAVE_IO_H
32 # include <io.h>
33 #endif
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37 #include <fcntl.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #include <sys/types.h>
42
43 #ifdef HAVE_SYS_IOCTL_H
44 #include <sys/ioctl.h>
45 #endif
46 #ifdef HAVE_SCSI_SG_H
47 # include <scsi/sg.h>
48 #endif
49 #ifdef HAVE_SCSI_SCSI_H
50 # include <scsi/scsi.h>
51 # undef REASSIGN_BLOCKS  /* avoid conflict with winioctl.h */
52 #endif
53 #ifdef HAVE_SCSI_SCSI_IOCTL_H
54 # include <scsi/scsi_ioctl.h>
55 #endif
56 #ifdef HAVE_LINUX_MAJOR_H
57 # include <linux/major.h>
58 #endif
59 #ifdef HAVE_LINUX_HDREG_H
60 # include <linux/hdreg.h>
61 #endif
62 #ifdef HAVE_LINUX_PARAM_H
63 # include <linux/param.h>
64 #endif
65 #ifdef HAVE_LINUX_CDROM_H
66 # include <linux/cdrom.h>
67 #endif
68 #ifdef HAVE_LINUX_UCDROM_H
69 # include <linux/ucdrom.h>
70 #endif
71 #ifdef HAVE_SYS_CDIO_H
72 # include <sys/cdio.h>
73 #endif
74 #ifdef HAVE_SYS_SCSIIO_H
75 # include <sys/scsiio.h>
76 #endif
77
78 #ifdef HAVE_IOKIT_IOKITLIB_H
79 # ifndef SENSEBUFLEN
80 #  include <sys/disk.h>
81 #  include <IOKit/IOKitLib.h>
82 #  include <IOKit/storage/IOMedia.h>
83 #  include <IOKit/scsi/SCSICmds_REQUEST_SENSE_Defs.h>
84 #  define SENSEBUFLEN kSenseDefaultSize
85 # endif
86 #endif
87
88 #define NONAMELESSUNION
89 #define NONAMELESSSTRUCT
90 #include "ntstatus.h"
91 #define WIN32_NO_STATUS
92 #include "windef.h"
93 #include "winternl.h"
94 #include "winioctl.h"
95 #include "ntddstor.h"
96 #include "ntddcdrm.h"
97 #include "ddk/ntddcdvd.h"
98 #include "ntddscsi.h"
99 #include "ntdll_misc.h"
100 #include "wine/server.h"
101 #include "wine/library.h"
102 #include "wine/debug.h"
103
104 WINE_DEFAULT_DEBUG_CHANNEL(cdrom);
105
106 /* Non-Linux systems do not have linux/cdrom.h and the like, and thus
107    lack the following constants. */
108
109 #ifndef CD_SECS
110 # define CD_SECS              60 /* seconds per minute */
111 #endif
112 #ifndef CD_FRAMES
113 # define CD_FRAMES            75 /* frames per second */
114 #endif
115
116 static const struct iocodexs
117 {
118   DWORD code;
119   const char *codex;
120 } iocodextable[] = {
121 #define X(x) { x, #x },
122 X(IOCTL_CDROM_CHECK_VERIFY)
123 X(IOCTL_CDROM_CURRENT_POSITION)
124 X(IOCTL_CDROM_DISK_TYPE)
125 X(IOCTL_CDROM_GET_CONTROL)
126 X(IOCTL_CDROM_GET_DRIVE_GEOMETRY)
127 X(IOCTL_CDROM_GET_VOLUME)
128 X(IOCTL_CDROM_LOAD_MEDIA)
129 X(IOCTL_CDROM_MEDIA_CATALOG)
130 X(IOCTL_CDROM_MEDIA_REMOVAL)
131 X(IOCTL_CDROM_PAUSE_AUDIO)
132 X(IOCTL_CDROM_PLAY_AUDIO_MSF)
133 X(IOCTL_CDROM_RAW_READ)
134 X(IOCTL_CDROM_READ_Q_CHANNEL)
135 X(IOCTL_CDROM_READ_TOC)
136 X(IOCTL_CDROM_RESUME_AUDIO)
137 X(IOCTL_CDROM_SEEK_AUDIO_MSF)
138 X(IOCTL_CDROM_SET_VOLUME)
139 X(IOCTL_CDROM_STOP_AUDIO)
140 X(IOCTL_CDROM_TRACK_ISRC)
141 X(IOCTL_DISK_MEDIA_REMOVAL)
142 X(IOCTL_DVD_END_SESSION)
143 X(IOCTL_DVD_GET_REGION)
144 X(IOCTL_DVD_READ_KEY)
145 X(IOCTL_DVD_READ_STRUCTURE)
146 X(IOCTL_DVD_SEND_KEY)
147 X(IOCTL_DVD_START_SESSION)
148 X(IOCTL_SCSI_GET_ADDRESS)
149 X(IOCTL_SCSI_GET_CAPABILITIES)
150 X(IOCTL_SCSI_GET_INQUIRY_DATA)
151 X(IOCTL_SCSI_PASS_THROUGH)
152 X(IOCTL_SCSI_PASS_THROUGH_DIRECT)
153 X(IOCTL_STORAGE_CHECK_VERIFY)
154 X(IOCTL_STORAGE_EJECTION_CONTROL)
155 X(IOCTL_STORAGE_EJECT_MEDIA)
156 X(IOCTL_STORAGE_GET_DEVICE_NUMBER)
157 X(IOCTL_STORAGE_LOAD_MEDIA)
158 X(IOCTL_STORAGE_MEDIA_REMOVAL)
159 X(IOCTL_STORAGE_RESET_DEVICE)
160 #undef X
161 };
162 static const char *iocodex(DWORD code)
163 {
164    unsigned int i;
165    static char buffer[25];
166    for(i=0; i<sizeof(iocodextable)/sizeof(struct iocodexs); i++)
167       if (code==iocodextable[i].code)
168          return iocodextable[i].codex;
169    sprintf(buffer, "IOCTL_CODE_%x", (int)code);
170    return buffer;
171 }
172
173 #define INQ_REPLY_LEN 36
174 #define INQ_CMD_LEN 6
175
176 #define FRAME_OF_ADDR(a) (((int)(a)[1] * CD_SECS + (a)[2]) * CD_FRAMES + (a)[3])
177 #define FRAME_OF_MSF(a) (((int)(a).M * CD_SECS + (a).S) * CD_FRAMES + (a).F)
178 #define FRAME_OF_TOC(toc, idx)  FRAME_OF_ADDR((toc).TrackData[idx - (toc).FirstTrack].Address)
179 #define MSF_OF_FRAME(m,fr) {int f=(fr); ((UCHAR *)&(m))[2]=f%CD_FRAMES;f/=CD_FRAMES;((UCHAR *)&(m))[1]=f%CD_SECS;((UCHAR *)&(m))[0]=f/CD_SECS;}
180
181 /* The documented format of DVD_LAYER_DESCRIPTOR is wrong. Even the format in the
182  * DDK's header is wrong. There are four bytes at the start which always seem to
183  * follow the sequence "02 08 00 00".
184  */
185 typedef struct
186 {
187     UCHAR MagicHeader[4];
188     UCHAR BookVersion : 4;
189     UCHAR BookType : 4;
190     UCHAR MinimumRate : 4;
191     UCHAR DiskSize : 4;
192     UCHAR LayerType : 4;
193     UCHAR TrackPath : 1;
194     UCHAR NumberOfLayers : 2;
195     UCHAR Reserved1 : 1;
196     UCHAR TrackDensity : 4;
197     UCHAR LinearDensity : 4;
198     ULONG StartingDataSector;
199     ULONG EndDataSector;
200     ULONG EndLayerZeroSector;
201     UCHAR Reserved5 : 7;
202     UCHAR BCAFlag : 1;
203     UCHAR Reserved6;
204 } internal_dvd_layer_descriptor;
205
206
207 static NTSTATUS CDROM_ReadTOC(int, int, CDROM_TOC*);
208 static NTSTATUS CDROM_GetStatusCode(int);
209
210
211 #ifdef linux
212
213 # ifndef IDE6_MAJOR
214 #  define IDE6_MAJOR 88
215 # endif
216 # ifndef IDE7_MAJOR
217 #  define IDE7_MAJOR 89
218 # endif
219
220 # ifdef CDROM_SEND_PACKET
221 /* structure for CDROM_PACKET_COMMAND ioctl */
222 /* not all Linux versions have all the fields, so we define the
223  * structure ourselves to make sure */
224 struct linux_cdrom_generic_command
225 {
226     unsigned char          cmd[CDROM_PACKET_SIZE];
227     unsigned char         *buffer;
228     unsigned int           buflen;
229     int                    stat;
230     struct request_sense  *sense;
231     unsigned char          data_direction;
232     int                    quiet;
233     int                    timeout;
234     void                  *reserved[1];
235 };
236 # endif  /* CDROM_SEND_PACKET */
237
238 #endif  /* linux */
239
240 /* FIXME: this is needed because we can't open simultaneously several times /dev/cdrom
241  * this should be removed when a proper device interface is implemented
242  * 
243  * (WS) We need this to keep track of current position and to safely
244  * detect media changes. Besides this should provide a great speed up
245  * for toc inquiries.
246  */
247 struct cdrom_cache {
248     dev_t       device;
249     ino_t       inode;
250     char        toc_good; /* if false, will reread TOC from disk */
251     CDROM_TOC   toc;
252     SUB_Q_CURRENT_POSITION CurrentPosition;
253 };
254 /* who has more than 5 cdroms on his/her machine ?? */
255 /* FIXME: this should grow depending on the number of cdroms we install/configure 
256  * at startup
257  */
258 #define MAX_CACHE_ENTRIES       5
259 static struct cdrom_cache cdrom_cache[MAX_CACHE_ENTRIES];
260
261 static RTL_CRITICAL_SECTION cache_section;
262 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
263 {
264     0, 0, &cache_section,
265     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
266       0, 0, { (DWORD_PTR)(__FILE__ ": cache_section") }
267 };
268 static RTL_CRITICAL_SECTION cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
269
270 /* Proposed media change function: not really needed at this time */
271 /* This is a 1 or 0 type of function */
272 #if 0
273 static int CDROM_MediaChanged(int dev)
274 {
275    int i;
276
277    struct cdrom_tochdr  hdr;
278    struct cdrom_tocentry entry;
279
280    if (dev < 0 || dev >= MAX_CACHE_ENTRIES)
281       return 0;
282    if ( ioctl(cdrom_cache[dev].fd, CDROMREADTOCHDR, &hdr) == -1 )
283       return 0;
284
285    if ( memcmp(&hdr, &cdrom_cache[dev].hdr, sizeof(struct cdrom_tochdr)) )
286       return 1;
287
288    for (i=hdr.cdth_trk0; i<=hdr.cdth_trk1+1; i++)
289    {
290       if (i == hdr.cdth_trk1 + 1)
291       {
292          entry.cdte_track = CDROM_LEADOUT;
293       } else {
294          entry.cdte_track = i;
295       }
296       entry.cdte_format = CDROM_MSF;
297       if ( ioctl(cdrom_cache[dev].fd, CDROMREADTOCENTRY, &entry) == -1)
298          return 0;
299       if ( memcmp(&entry, cdrom_cache[dev].entry+i-hdr.cdth_trk0,
300                               sizeof(struct cdrom_tocentry)) )
301          return 1;
302    }
303    return 0;
304 }
305 #endif
306
307
308 /******************************************************************
309  *              open_parent_device
310  *
311  * On Mac OS, open the device for the whole disk from a fd that points to a partition.
312  * This is ugly and inefficient, but we have no choice since the partition fd doesn't
313  * support the eject ioctl.
314  */
315 #ifdef __APPLE__
316 static int open_parent_device( int fd )
317 {
318     struct stat st;
319     int i, parent_fd = -1;
320     io_service_t service;
321     CFMutableDictionaryRef dict;
322     CFTypeRef val;
323
324     if (fstat( fd, &st ) == -1) return -1;
325     if (!S_ISCHR( st.st_mode )) return -1;
326
327     /* create a dictionary with the right major/minor numbers */
328
329     if (!(dict = IOServiceMatching( kIOMediaClass ))) return -1;
330
331     i = major( st.st_rdev );
332     val = CFNumberCreate( NULL, kCFNumberIntType, &i );
333     CFDictionaryAddValue( dict, CFSTR( "BSD Major" ), val );
334     CFRelease( val );
335
336     i = minor( st.st_rdev );
337     val = CFNumberCreate( NULL, kCFNumberIntType, &i );
338     CFDictionaryAddValue( dict, CFSTR( "BSD Minor" ), val );
339     CFRelease( val );
340
341     CFDictionaryAddValue( dict, CFSTR("Removable"), kCFBooleanTrue );
342
343     service = IOServiceGetMatchingService( kIOMasterPortDefault, dict );
344
345     /* now look for the parent that has the "Whole" attribute set to TRUE */
346
347     while (service)
348     {
349         io_service_t parent = 0;
350         CFBooleanRef whole;
351         CFStringRef str;
352         int ok;
353
354         if (!IOObjectConformsTo( service, kIOMediaClass ))
355             goto next;
356         if (!(whole = IORegistryEntryCreateCFProperty( service, CFSTR("Whole"), NULL, 0 )))
357             goto next;
358         ok = (whole == kCFBooleanTrue);
359         CFRelease( whole );
360         if (!ok) goto next;
361
362         if ((str = IORegistryEntryCreateCFProperty( service, CFSTR("BSD Name"), NULL, 0 )))
363         {
364             char name[100];
365             strcpy( name, "/dev/r" );
366             CFStringGetCString( str, name + 6, sizeof(name) - 6, kCFStringEncodingUTF8 );
367             CFRelease( str );
368             parent_fd = open( name, O_RDONLY );
369         }
370         IOObjectRelease( service );
371         break;
372
373 next:
374         IORegistryEntryGetParentEntry( service, kIOServicePlane, &parent );
375         IOObjectRelease( service );
376         service = parent;
377     }
378     return parent_fd;
379 }
380 #endif
381
382
383 /******************************************************************
384  *              CDROM_SyncCache                          [internal]
385  *
386  * Read the TOC in and store it in the cdrom_cache structure.
387  * Further requests for the TOC will be copied from the cache
388  * unless certain events like disk ejection is detected, in which
389  * case the cache will be cleared, causing it to be resynced.
390  * The cache section must be held by caller.
391  */
392 static NTSTATUS CDROM_SyncCache(int dev, int fd)
393 {
394 #ifdef linux
395    int i, tsz;
396    struct cdrom_tochdr          hdr;
397    struct cdrom_tocentry        entry;
398
399    CDROM_TOC *toc = &cdrom_cache[dev].toc;
400    cdrom_cache[dev].toc_good = 0;
401
402    if (ioctl(fd, CDROMREADTOCHDR, &hdr) == -1)
403    {
404       WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
405       return FILE_GetNtStatus();
406    }
407
408    toc->FirstTrack = hdr.cdth_trk0;
409    toc->LastTrack  = hdr.cdth_trk1;
410    tsz = sizeof(toc->FirstTrack) + sizeof(toc->LastTrack)
411        + sizeof(TRACK_DATA) * (toc->LastTrack-toc->FirstTrack+2);
412    toc->Length[0] = tsz >> 8;
413    toc->Length[1] = tsz;
414
415    TRACE("caching toc from=%d to=%d\n", toc->FirstTrack, toc->LastTrack );
416
417    for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
418    {
419      if (i == toc->LastTrack + 1)
420        entry.cdte_track = CDROM_LEADOUT;
421      else 
422        entry.cdte_track = i;
423      entry.cdte_format = CDROM_MSF;
424      if (ioctl(fd, CDROMREADTOCENTRY, &entry) == -1)
425      {
426        WARN("error read entry (%s)\n", strerror(errno));
427        return FILE_GetNtStatus();
428      }
429      toc->TrackData[i - toc->FirstTrack].Control = entry.cdte_ctrl;
430      toc->TrackData[i - toc->FirstTrack].Adr = entry.cdte_adr;
431      /* marking last track with leadout value as index */
432      toc->TrackData[i - toc->FirstTrack].TrackNumber = entry.cdte_track;
433      toc->TrackData[i - toc->FirstTrack].Address[0] = 0;
434      toc->TrackData[i - toc->FirstTrack].Address[1] = entry.cdte_addr.msf.minute;
435      toc->TrackData[i - toc->FirstTrack].Address[2] = entry.cdte_addr.msf.second;
436      toc->TrackData[i - toc->FirstTrack].Address[3] = entry.cdte_addr.msf.frame;
437    }
438    cdrom_cache[dev].toc_good = 1;
439    return STATUS_SUCCESS;
440
441 #elif defined(__FreeBSD__) || defined(__NetBSD__)
442
443    int i, tsz;
444    struct ioc_toc_header hdr;
445    struct ioc_read_toc_entry entry;
446    struct cd_toc_entry toc_buffer;
447
448    CDROM_TOC *toc = &cdrom_cache[dev].toc;
449    cdrom_cache[dev].toc_good = 0;
450
451     if (ioctl(fd, CDIOREADTOCHEADER, &hdr) == -1)
452     {
453         WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
454         return FILE_GetNtStatus();
455     }
456     toc->FirstTrack = hdr.starting_track;
457     toc->LastTrack  = hdr.ending_track;
458     tsz = sizeof(toc->FirstTrack) + sizeof(toc->LastTrack)
459         + sizeof(TRACK_DATA) * (toc->LastTrack-toc->FirstTrack+2);
460     toc->Length[0] = tsz >> 8;
461     toc->Length[1] = tsz;
462
463     TRACE("caching toc from=%d to=%d\n", toc->FirstTrack, toc->LastTrack );
464
465     for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
466     {
467         if (i == toc->LastTrack + 1)
468         {
469 #define LEADOUT 0xaa
470             entry.starting_track = LEADOUT;
471         } else {
472             entry.starting_track = i;
473         }
474         memset((char *)&toc_buffer, 0, sizeof(toc_buffer));
475         entry.address_format = CD_MSF_FORMAT;
476         entry.data_len = sizeof(toc_buffer);
477         entry.data = &toc_buffer;
478         if (ioctl(fd, CDIOREADTOCENTRYS, &entry) == -1)
479         {
480             WARN("error read entry (%s)\n", strerror(errno));
481             return FILE_GetNtStatus();
482         }
483         toc->TrackData[i - toc->FirstTrack].Control = toc_buffer.control;
484         toc->TrackData[i - toc->FirstTrack].Adr = toc_buffer.addr_type;
485         /* marking last track with leadout value as index */
486         toc->TrackData[i - toc->FirstTrack].TrackNumber = entry.starting_track;
487         toc->TrackData[i - toc->FirstTrack].Address[0] = 0;
488         toc->TrackData[i - toc->FirstTrack].Address[1] = toc_buffer.addr.msf.minute;
489         toc->TrackData[i - toc->FirstTrack].Address[2] = toc_buffer.addr.msf.second;
490         toc->TrackData[i - toc->FirstTrack].Address[3] = toc_buffer.addr.msf.frame;
491     }
492     cdrom_cache[dev].toc_good = 1;
493     return STATUS_SUCCESS;
494 #else
495     return STATUS_NOT_SUPPORTED;
496 #endif
497 }
498
499 static void CDROM_ClearCacheEntry(int dev)
500 {
501     RtlEnterCriticalSection( &cache_section );
502     cdrom_cache[dev].toc_good = 0;
503     RtlLeaveCriticalSection( &cache_section );
504 }
505
506
507
508 /******************************************************************
509  *              CDROM_GetInterfaceInfo
510  *
511  * Determines the ide interface (the number after the ide), and the
512  * number of the device on that interface for ide cdroms (*iface <= 1).
513  * Determines the scsi information for scsi cdroms (*iface >= 2).
514  * Returns false if the info cannot not be obtained.
515  */
516 static int CDROM_GetInterfaceInfo(int fd, UCHAR* iface, UCHAR* port, UCHAR* device, UCHAR* lun)
517 {
518 #if defined(linux)
519     struct stat st;
520     if ( fstat(fd, &st) == -1 || ! S_ISBLK(st.st_mode)) return 0;
521     *port = 0;
522     *iface = 0;
523     *device = 0;
524     *lun = 0;
525     switch (major(st.st_rdev)) {
526     case IDE0_MAJOR: *iface = 0; break;
527     case IDE1_MAJOR: *iface = 1; break;
528     case IDE2_MAJOR: *iface = 2; break;
529     case IDE3_MAJOR: *iface = 3; break;
530     case IDE4_MAJOR: *iface = 4; break;
531     case IDE5_MAJOR: *iface = 5; break;
532     case IDE6_MAJOR: *iface = 6; break;
533     case IDE7_MAJOR: *iface = 7; break;
534     default: *port = 1; break;
535     }
536
537     if (*port == 0)
538         *device = (minor(st.st_rdev) >> 6);
539     else
540     {
541 #ifdef SCSI_IOCTL_GET_IDLUN
542         UINT32 idlun[2];
543         if (ioctl(fd, SCSI_IOCTL_GET_IDLUN, &idlun) != -1)
544         {
545             *port = (idlun[0] >> 24) & 0xff;
546             *iface = ((idlun[0] >> 16) & 0xff) + 2;
547             *device = idlun[0] & 0xff;
548             *lun = (idlun[0] >> 8) & 0xff;
549         }
550         else
551 #endif
552         {
553             WARN("CD-ROM device (%d, %d) not supported\n", major(st.st_rdev), minor(st.st_rdev));
554             return 0;
555         }
556     }
557     return 1;
558 #elif defined(__NetBSD__)
559     struct scsi_addr addr;
560     if (ioctl(fd, SCIOCIDENTIFY, &addr) != -1)
561     {
562         switch (addr.type) 
563         {
564         case TYPE_SCSI:  *port = 1;
565             *iface = addr.addr.scsi.scbus;
566             *device = addr.addr.scsi.target;
567             *lun = addr.addr.scsi.lun;
568             break;
569         case TYPE_ATAPI: *port = 0;
570             *iface = addr.addr.atapi.atbus;
571             *device = addr.addr.atapi.drive;
572             *lun = 0;
573             break;
574         }
575         return 1;
576     }
577     return 0;
578 #elif defined(__FreeBSD__)
579     FIXME("not implemented for BSD\n");
580     return 0;
581 #else
582     FIXME("not implemented for nonlinux\n");
583     return 0;
584 #endif
585 }
586
587
588 /******************************************************************
589  *              CDROM_Open
590  *
591  */
592 static NTSTATUS CDROM_Open(int fd, int* dev)
593 {
594     struct stat st;
595     NTSTATUS ret = STATUS_SUCCESS;
596     int         empty = -1;
597
598     fstat(fd, &st);
599
600     RtlEnterCriticalSection( &cache_section );
601     for (*dev = 0; *dev < MAX_CACHE_ENTRIES; (*dev)++)
602     {
603         if (empty == -1 &&
604             cdrom_cache[*dev].device == 0 &&
605             cdrom_cache[*dev].inode == 0)
606             empty = *dev;
607         else if (cdrom_cache[*dev].device == st.st_dev &&
608                  cdrom_cache[*dev].inode == st.st_ino)
609             break;
610     }
611     if (*dev == MAX_CACHE_ENTRIES)
612     {
613         if (empty == -1) ret = STATUS_NOT_IMPLEMENTED;
614         else
615         {
616             *dev = empty;
617             cdrom_cache[*dev].device  = st.st_dev;
618             cdrom_cache[*dev].inode   = st.st_ino;
619         }
620     }
621     RtlLeaveCriticalSection( &cache_section );
622
623     TRACE("%d, %d\n", *dev, fd);
624     return ret;
625 }
626
627 /******************************************************************
628  *              CDROM_GetStatusCode
629  *
630  *
631  */
632 static NTSTATUS CDROM_GetStatusCode(int io)
633 {
634     if (io == 0) return STATUS_SUCCESS;
635     return FILE_GetNtStatus();
636 }
637
638 /******************************************************************
639  *              CDROM_GetControl
640  *
641  */
642 static NTSTATUS CDROM_GetControl(int dev, CDROM_AUDIO_CONTROL* cac)
643 {
644     cac->LbaFormat = 0; /* FIXME */
645     cac->LogicalBlocksPerSecond = 1; /* FIXME */
646     return  STATUS_NOT_SUPPORTED;
647 }
648
649 /******************************************************************
650  *              CDROM_GetDeviceNumber
651  *
652  */
653 static NTSTATUS CDROM_GetDeviceNumber(int dev, STORAGE_DEVICE_NUMBER* devnum)
654 {
655     return STATUS_NOT_SUPPORTED;
656 }
657
658 /******************************************************************
659  *              CDROM_GetDriveGeometry
660  *
661  */
662 static NTSTATUS CDROM_GetDriveGeometry(int dev, int fd, DISK_GEOMETRY* dg)
663 {
664   CDROM_TOC     toc;
665   NTSTATUS      ret = 0;
666   int           fsize = 0;
667
668   if ((ret = CDROM_ReadTOC(dev, fd, &toc)) != 0) return ret;
669
670   fsize = FRAME_OF_TOC(toc, toc.LastTrack+1)
671         - FRAME_OF_TOC(toc, 1); /* Total size in frames */
672   
673   dg->Cylinders.u.LowPart = fsize / (64 * 32); 
674   dg->Cylinders.u.HighPart = 0; 
675   dg->MediaType = RemovableMedia;  
676   dg->TracksPerCylinder = 64; 
677   dg->SectorsPerTrack = 32;  
678   dg->BytesPerSector= 2048; 
679   return ret;
680 }
681
682 /**************************************************************************
683  *                              CDROM_Reset                     [internal]
684  */
685 static NTSTATUS CDROM_ResetAudio(int fd)
686 {
687 #if defined(linux)
688     return CDROM_GetStatusCode(ioctl(fd, CDROMRESET));
689 #elif defined(__FreeBSD__) || defined(__NetBSD__)
690     return CDROM_GetStatusCode(ioctl(fd, CDIOCRESET, NULL));
691 #else
692     return STATUS_NOT_SUPPORTED;
693 #endif
694 }
695
696 /******************************************************************
697  *              CDROM_SetTray
698  *
699  *
700  */
701 static NTSTATUS CDROM_SetTray(int fd, BOOL doEject)
702 {
703 #if defined(linux)
704     return CDROM_GetStatusCode(ioctl(fd, doEject ? CDROMEJECT : CDROMCLOSETRAY));
705 #elif defined(__FreeBSD__) || defined(__NetBSD__)
706     return CDROM_GetStatusCode((ioctl(fd, CDIOCALLOW, NULL)) ||
707                                (ioctl(fd, doEject ? CDIOCEJECT : CDIOCCLOSE, NULL)) ||
708                                (ioctl(fd, CDIOCPREVENT, NULL)));
709 #elif defined(__APPLE__)
710     if (doEject) return CDROM_GetStatusCode( ioctl( fd, DKIOCEJECT, NULL ) );
711     else return STATUS_NOT_SUPPORTED;
712 #else
713     return STATUS_NOT_SUPPORTED;
714 #endif
715 }
716
717 /******************************************************************
718  *              CDROM_ControlEjection
719  *
720  *
721  */
722 static NTSTATUS CDROM_ControlEjection(int fd, const PREVENT_MEDIA_REMOVAL* rmv)
723 {
724 #if defined(linux)
725     return CDROM_GetStatusCode(ioctl(fd, CDROM_LOCKDOOR, rmv->PreventMediaRemoval));
726 #elif defined(__FreeBSD__) || defined(__NetBSD__)
727     return CDROM_GetStatusCode(ioctl(fd, (rmv->PreventMediaRemoval) ? CDIOCPREVENT : CDIOCALLOW, NULL));
728 #else
729     return STATUS_NOT_SUPPORTED;
730 #endif
731 }
732
733 /******************************************************************
734  *              CDROM_ReadTOC
735  *
736  *
737  */
738 static NTSTATUS CDROM_ReadTOC(int dev, int fd, CDROM_TOC* toc)
739 {
740     NTSTATUS       ret = STATUS_NOT_SUPPORTED;
741
742     if (dev < 0 || dev >= MAX_CACHE_ENTRIES)
743         return STATUS_INVALID_PARAMETER;
744
745     RtlEnterCriticalSection( &cache_section );
746     if (cdrom_cache[dev].toc_good || !(ret = CDROM_SyncCache(dev, fd)))
747     {
748         *toc = cdrom_cache[dev].toc;
749         ret = STATUS_SUCCESS;
750     }
751     RtlLeaveCriticalSection( &cache_section );
752     return ret;
753 }
754
755 /******************************************************************
756  *              CDROM_GetDiskData
757  *
758  *
759  */
760 static NTSTATUS CDROM_GetDiskData(int dev, int fd, CDROM_DISK_DATA* data)
761 {
762     CDROM_TOC   toc;
763     NTSTATUS    ret;
764     int         i;
765
766     if ((ret = CDROM_ReadTOC(dev, fd, &toc)) != 0) return ret;
767     data->DiskData = 0;
768     for (i = toc.FirstTrack; i <= toc.LastTrack; i++) {
769         if (toc.TrackData[i-toc.FirstTrack].Control & 0x04)
770             data->DiskData |= CDROM_DISK_DATA_TRACK;
771         else
772             data->DiskData |= CDROM_DISK_AUDIO_TRACK;
773     }
774     return STATUS_SUCCESS;
775 }
776
777 /******************************************************************
778  *              CDROM_ReadQChannel
779  *
780  *
781  */
782 static NTSTATUS CDROM_ReadQChannel(int dev, int fd, const CDROM_SUB_Q_DATA_FORMAT* fmt,
783                                    SUB_Q_CHANNEL_DATA* data)
784 {
785     NTSTATUS            ret = STATUS_NOT_SUPPORTED;
786 #ifdef linux
787     unsigned            size;
788     SUB_Q_HEADER*       hdr = (SUB_Q_HEADER*)data;
789     int                 io;
790     struct cdrom_subchnl        sc;
791     sc.cdsc_format = CDROM_MSF;
792
793     io = ioctl(fd, CDROMSUBCHNL, &sc);
794     if (io == -1)
795     {
796         TRACE("opened or no_media (%s)!\n", strerror(errno));
797         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
798         CDROM_ClearCacheEntry(dev);
799         goto end;
800     }
801
802     hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
803
804     switch (sc.cdsc_audiostatus) {
805     case CDROM_AUDIO_INVALID:
806         CDROM_ClearCacheEntry(dev);
807         hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
808         break;
809     case CDROM_AUDIO_NO_STATUS:
810         CDROM_ClearCacheEntry(dev);
811         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
812         break;
813     case CDROM_AUDIO_PLAY:
814         hdr->AudioStatus = AUDIO_STATUS_IN_PROGRESS;
815         break;
816     case CDROM_AUDIO_PAUSED:
817         hdr->AudioStatus = AUDIO_STATUS_PAUSED;
818         break;
819     case CDROM_AUDIO_COMPLETED:
820         hdr->AudioStatus = AUDIO_STATUS_PLAY_COMPLETE;
821         break;
822     case CDROM_AUDIO_ERROR:
823         hdr->AudioStatus = AUDIO_STATUS_PLAY_ERROR;
824         break;
825     default:
826         TRACE("status=%02X !\n", sc.cdsc_audiostatus);
827         break;
828     }
829     switch (fmt->Format)
830     {
831     case IOCTL_CDROM_CURRENT_POSITION:
832         size = sizeof(SUB_Q_CURRENT_POSITION);
833         RtlEnterCriticalSection( &cache_section );
834         if (hdr->AudioStatus==AUDIO_STATUS_IN_PROGRESS) {
835           data->CurrentPosition.FormatCode = IOCTL_CDROM_CURRENT_POSITION;
836           data->CurrentPosition.Control = sc.cdsc_ctrl; 
837           data->CurrentPosition.ADR = sc.cdsc_adr; 
838           data->CurrentPosition.TrackNumber = sc.cdsc_trk; 
839           data->CurrentPosition.IndexNumber = sc.cdsc_ind; 
840
841           data->CurrentPosition.AbsoluteAddress[0] = 0; 
842           data->CurrentPosition.AbsoluteAddress[1] = sc.cdsc_absaddr.msf.minute; 
843           data->CurrentPosition.AbsoluteAddress[2] = sc.cdsc_absaddr.msf.second;
844           data->CurrentPosition.AbsoluteAddress[3] = sc.cdsc_absaddr.msf.frame;
845  
846           data->CurrentPosition.TrackRelativeAddress[0] = 0; 
847           data->CurrentPosition.TrackRelativeAddress[1] = sc.cdsc_reladdr.msf.minute; 
848           data->CurrentPosition.TrackRelativeAddress[2] = sc.cdsc_reladdr.msf.second;
849           data->CurrentPosition.TrackRelativeAddress[3] = sc.cdsc_reladdr.msf.frame;
850
851           cdrom_cache[dev].CurrentPosition = data->CurrentPosition;
852         }
853         else /* not playing */
854         {
855           cdrom_cache[dev].CurrentPosition.Header = *hdr; /* Preserve header info */
856           data->CurrentPosition = cdrom_cache[dev].CurrentPosition;
857         }
858         RtlLeaveCriticalSection( &cache_section );
859         break;
860     case IOCTL_CDROM_MEDIA_CATALOG:
861         size = sizeof(SUB_Q_MEDIA_CATALOG_NUMBER);
862         data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
863         {
864             struct cdrom_mcn mcn;
865             if ((io = ioctl(fd, CDROM_GET_MCN, &mcn)) == -1) goto end;
866
867             data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
868             data->MediaCatalog.Mcval = 0; /* FIXME */
869             memcpy(data->MediaCatalog.MediaCatalog, mcn.medium_catalog_number, 14);
870             data->MediaCatalog.MediaCatalog[14] = 0;
871         }
872         break;
873     case IOCTL_CDROM_TRACK_ISRC:
874         size = sizeof(SUB_Q_CURRENT_POSITION);
875         FIXME("TrackIsrc: NIY on linux\n");
876         data->TrackIsrc.FormatCode = IOCTL_CDROM_TRACK_ISRC;
877         data->TrackIsrc.Tcval = 0;
878         io = 0;
879         break;
880     }
881
882  end:
883     ret = CDROM_GetStatusCode(io);
884 #elif defined(__FreeBSD__) || defined(__NetBSD__)
885     unsigned            size;
886     SUB_Q_HEADER*       hdr = (SUB_Q_HEADER*)data;
887     int                 io;
888     struct ioc_read_subchannel  read_sc;
889     struct cd_sub_channel_info  sc;
890
891     read_sc.address_format = CD_MSF_FORMAT;
892     read_sc.track          = 0;
893     read_sc.data_len       = sizeof(sc);
894     read_sc.data           = &sc;
895     switch (fmt->Format)
896     {
897     case IOCTL_CDROM_CURRENT_POSITION:
898         read_sc.data_format    = CD_CURRENT_POSITION;
899         break;
900     case IOCTL_CDROM_MEDIA_CATALOG:
901         read_sc.data_format    = CD_MEDIA_CATALOG;
902         break;
903     case IOCTL_CDROM_TRACK_ISRC:
904         read_sc.data_format    = CD_TRACK_INFO;
905         sc.what.track_info.track_number = data->TrackIsrc.Track;
906         break;
907     }
908     io = ioctl(fd, CDIOCREADSUBCHANNEL, &read_sc);
909     if (io == -1)
910     {
911         TRACE("opened or no_media (%s)!\n", strerror(errno));
912         CDROM_ClearCacheEntry(dev);
913         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
914         goto end;
915     }
916
917     hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
918
919     switch (sc.header.audio_status) {
920     case CD_AS_AUDIO_INVALID:
921         CDROM_ClearCacheEntry(dev);
922         hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
923         break;
924     case CD_AS_NO_STATUS:
925         CDROM_ClearCacheEntry(dev);
926         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
927         break;
928     case CD_AS_PLAY_IN_PROGRESS:
929         hdr->AudioStatus = AUDIO_STATUS_IN_PROGRESS;
930         break;
931     case CD_AS_PLAY_PAUSED:
932         hdr->AudioStatus = AUDIO_STATUS_PAUSED;
933         break;
934     case CD_AS_PLAY_COMPLETED:
935         hdr->AudioStatus = AUDIO_STATUS_PLAY_COMPLETE;
936         break;
937     case CD_AS_PLAY_ERROR:
938         hdr->AudioStatus = AUDIO_STATUS_PLAY_ERROR;
939         break;
940     default:
941         TRACE("status=%02X !\n", sc.header.audio_status);
942     }
943     switch (fmt->Format)
944     {
945     case IOCTL_CDROM_CURRENT_POSITION:
946         size = sizeof(SUB_Q_CURRENT_POSITION);
947         RtlEnterCriticalSection( &cache_section );
948         if (hdr->AudioStatus==AUDIO_STATUS_IN_PROGRESS) {
949           data->CurrentPosition.FormatCode = IOCTL_CDROM_CURRENT_POSITION;
950           data->CurrentPosition.Control = sc.what.position.control;
951           data->CurrentPosition.ADR = sc.what.position.addr_type;
952           data->CurrentPosition.TrackNumber = sc.what.position.track_number;
953           data->CurrentPosition.IndexNumber = sc.what.position.index_number;
954
955           data->CurrentPosition.AbsoluteAddress[0] = 0;
956           data->CurrentPosition.AbsoluteAddress[1] = sc.what.position.absaddr.msf.minute;
957           data->CurrentPosition.AbsoluteAddress[2] = sc.what.position.absaddr.msf.second;
958           data->CurrentPosition.AbsoluteAddress[3] = sc.what.position.absaddr.msf.frame;
959           data->CurrentPosition.TrackRelativeAddress[0] = 0;
960           data->CurrentPosition.TrackRelativeAddress[1] = sc.what.position.reladdr.msf.minute;
961           data->CurrentPosition.TrackRelativeAddress[2] = sc.what.position.reladdr.msf.second;
962           data->CurrentPosition.TrackRelativeAddress[3] = sc.what.position.reladdr.msf.frame;
963           cdrom_cache[dev].CurrentPosition = data->CurrentPosition;
964         }
965         else { /* not playing */
966           cdrom_cache[dev].CurrentPosition.Header = *hdr; /* Preserve header info */
967           data->CurrentPosition = cdrom_cache[dev].CurrentPosition;
968         }
969         RtlLeaveCriticalSection( &cache_section );
970         break;
971     case IOCTL_CDROM_MEDIA_CATALOG:
972         size = sizeof(SUB_Q_MEDIA_CATALOG_NUMBER);
973         data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
974         data->MediaCatalog.Mcval = sc.what.media_catalog.mc_valid;
975         memcpy(data->MediaCatalog.MediaCatalog, sc.what.media_catalog.mc_number, 15);
976         break;
977     case IOCTL_CDROM_TRACK_ISRC:
978         size = sizeof(SUB_Q_CURRENT_POSITION);
979         data->TrackIsrc.FormatCode = IOCTL_CDROM_TRACK_ISRC;
980         data->TrackIsrc.Tcval = sc.what.track_info.ti_valid;
981         memcpy(data->TrackIsrc.TrackIsrc, sc.what.track_info.ti_number, 15);
982         break;
983     }
984
985  end:
986     ret = CDROM_GetStatusCode(io);
987 #endif
988     return ret;
989 }
990
991 /******************************************************************
992  *              CDROM_Verify
993  *  Implements: IOCTL_STORAGE_CHECK_VERIFY
994  *              IOCTL_CDROM_CHECK_VERIFY
995  *              IOCTL_DISK_CHECK_VERIFY
996  *
997  */
998 static NTSTATUS CDROM_Verify(int dev, int fd)
999 {
1000 #if defined(linux)
1001     int ret;
1002
1003     ret = ioctl(fd,  CDROM_DRIVE_STATUS, NULL);
1004     if(ret == -1) {
1005         TRACE("ioctl CDROM_DRIVE_STATUS failed(%s)!\n", strerror(errno));
1006         return CDROM_GetStatusCode(ret);
1007     }
1008
1009     if(ret == CDS_DISC_OK)
1010         return STATUS_SUCCESS;
1011     else
1012         return STATUS_NO_MEDIA_IN_DEVICE;
1013 #endif
1014     FIXME("not implemented for non-linux\n");
1015     return STATUS_NOT_SUPPORTED;
1016 }
1017
1018 /******************************************************************
1019  *              CDROM_PlayAudioMSF
1020  *
1021  *
1022  */
1023 static NTSTATUS CDROM_PlayAudioMSF(int fd, const CDROM_PLAY_AUDIO_MSF* audio_msf)
1024 {
1025     NTSTATUS       ret = STATUS_NOT_SUPPORTED;
1026 #ifdef linux
1027     struct      cdrom_msf       msf;
1028     int         io;
1029
1030     msf.cdmsf_min0   = audio_msf->StartingM;
1031     msf.cdmsf_sec0   = audio_msf->StartingS;
1032     msf.cdmsf_frame0 = audio_msf->StartingF;
1033     msf.cdmsf_min1   = audio_msf->EndingM;
1034     msf.cdmsf_sec1   = audio_msf->EndingS;
1035     msf.cdmsf_frame1 = audio_msf->EndingF;
1036
1037     io = ioctl(fd, CDROMSTART);
1038     if (io == -1)
1039     {
1040         WARN("motor doesn't start !\n");
1041         goto end;
1042     }
1043     io = ioctl(fd, CDROMPLAYMSF, &msf);
1044     if (io == -1)
1045     {
1046         WARN("device doesn't play !\n");
1047         goto end;
1048     }
1049     TRACE("msf = %d:%d:%d %d:%d:%d\n",
1050           msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0,
1051           msf.cdmsf_min1, msf.cdmsf_sec1, msf.cdmsf_frame1);
1052  end:
1053     ret = CDROM_GetStatusCode(io);
1054 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1055     struct      ioc_play_msf    msf;
1056     int         io;
1057
1058     msf.start_m      = audio_msf->StartingM;
1059     msf.start_s      = audio_msf->StartingS;
1060     msf.start_f      = audio_msf->StartingF;
1061     msf.end_m        = audio_msf->EndingM;
1062     msf.end_s        = audio_msf->EndingS;
1063     msf.end_f        = audio_msf->EndingF;
1064
1065     io = ioctl(fd, CDIOCSTART, NULL);
1066     if (io == -1)
1067     {
1068         WARN("motor doesn't start !\n");
1069         goto end;
1070     }
1071     io = ioctl(fd, CDIOCPLAYMSF, &msf);
1072     if (io == -1)
1073     {
1074         WARN("device doesn't play !\n");
1075         goto end;
1076     }
1077     TRACE("msf = %d:%d:%d %d:%d:%d\n",
1078           msf.start_m, msf.start_s, msf.start_f,
1079           msf.end_m,   msf.end_s,   msf.end_f);
1080 end:
1081     ret = CDROM_GetStatusCode(io);
1082 #endif
1083     return ret;
1084 }
1085
1086 /******************************************************************
1087  *              CDROM_SeekAudioMSF
1088  *
1089  *
1090  */
1091 static NTSTATUS CDROM_SeekAudioMSF(int dev, int fd, const CDROM_SEEK_AUDIO_MSF* audio_msf)
1092 {
1093     CDROM_TOC toc;
1094     int i, io, frame;
1095     SUB_Q_CURRENT_POSITION *cp;
1096 #if defined(linux)
1097     struct cdrom_msf0   msf;
1098     struct cdrom_subchnl sc;
1099 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1100     struct ioc_play_msf msf;
1101     struct ioc_read_subchannel  read_sc;
1102     struct cd_sub_channel_info  sc;
1103     int final_frame;
1104 #endif
1105
1106     /* Use the information on the TOC to compute the new current
1107      * position, which is shadowed on the cache. [Portable]. */
1108     frame = FRAME_OF_MSF(*audio_msf);
1109
1110     if ((io = CDROM_ReadTOC(dev, fd, &toc)) != 0) return io;
1111
1112     for(i=toc.FirstTrack;i<=toc.LastTrack+1;i++)
1113       if (FRAME_OF_TOC(toc,i)>frame) break;
1114     if (i <= toc.FirstTrack || i > toc.LastTrack+1)
1115       return STATUS_INVALID_PARAMETER;
1116     i--;
1117     RtlEnterCriticalSection( &cache_section );
1118     cp = &cdrom_cache[dev].CurrentPosition;
1119     cp->FormatCode = IOCTL_CDROM_CURRENT_POSITION; 
1120     cp->Control = toc.TrackData[i-toc.FirstTrack].Control; 
1121     cp->ADR = toc.TrackData[i-toc.FirstTrack].Adr; 
1122     cp->TrackNumber = toc.TrackData[i-toc.FirstTrack].TrackNumber;
1123     cp->IndexNumber = 0; /* FIXME: where do they keep these? */
1124     cp->AbsoluteAddress[0] = 0; 
1125     cp->AbsoluteAddress[1] = toc.TrackData[i-toc.FirstTrack].Address[1];
1126     cp->AbsoluteAddress[2] = toc.TrackData[i-toc.FirstTrack].Address[2];
1127     cp->AbsoluteAddress[3] = toc.TrackData[i-toc.FirstTrack].Address[3];
1128     frame -= FRAME_OF_TOC(toc,i);
1129     cp->TrackRelativeAddress[0] = 0;
1130     MSF_OF_FRAME(cp->TrackRelativeAddress[1], frame); 
1131     RtlLeaveCriticalSection( &cache_section );
1132
1133     /* If playing, then issue a seek command, otherwise do nothing */
1134 #ifdef linux
1135     sc.cdsc_format = CDROM_MSF;
1136
1137     io = ioctl(fd, CDROMSUBCHNL, &sc);
1138     if (io == -1)
1139     {
1140         TRACE("opened or no_media (%s)!\n", strerror(errno));
1141         CDROM_ClearCacheEntry(dev);
1142         return CDROM_GetStatusCode(io);
1143     }
1144     if (sc.cdsc_audiostatus==CDROM_AUDIO_PLAY)
1145     {
1146       msf.minute = audio_msf->M;
1147       msf.second = audio_msf->S;
1148       msf.frame  = audio_msf->F;
1149       return CDROM_GetStatusCode(ioctl(fd, CDROMSEEK, &msf));
1150     }
1151     return STATUS_SUCCESS;
1152 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1153     read_sc.address_format = CD_MSF_FORMAT;
1154     read_sc.track          = 0;
1155     read_sc.data_len       = sizeof(sc);
1156     read_sc.data           = &sc;
1157     read_sc.data_format    = CD_CURRENT_POSITION;
1158
1159     io = ioctl(fd, CDIOCREADSUBCHANNEL, &read_sc);
1160     if (io == -1)
1161     {
1162         TRACE("opened or no_media (%s)!\n", strerror(errno));
1163         CDROM_ClearCacheEntry(dev);
1164         return CDROM_GetStatusCode(io);
1165     }
1166     if (sc.header.audio_status==CD_AS_PLAY_IN_PROGRESS) 
1167     {
1168
1169       msf.start_m      = audio_msf->M;
1170       msf.start_s      = audio_msf->S;
1171       msf.start_f      = audio_msf->F;
1172       final_frame = FRAME_OF_TOC(toc,toc.LastTrack+1)-1;
1173       MSF_OF_FRAME(msf.end_m, final_frame);
1174
1175       return CDROM_GetStatusCode(ioctl(fd, CDIOCPLAYMSF, &msf));
1176     }
1177     return STATUS_SUCCESS;
1178 #else
1179     return STATUS_NOT_SUPPORTED;
1180 #endif
1181 }
1182
1183 /******************************************************************
1184  *              CDROM_PauseAudio
1185  *
1186  *
1187  */
1188 static NTSTATUS CDROM_PauseAudio(int fd)
1189 {
1190 #if defined(linux)
1191     return CDROM_GetStatusCode(ioctl(fd, CDROMPAUSE));
1192 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1193     return CDROM_GetStatusCode(ioctl(fd, CDIOCPAUSE, NULL));
1194 #else
1195     return STATUS_NOT_SUPPORTED;
1196 #endif
1197 }
1198
1199 /******************************************************************
1200  *              CDROM_ResumeAudio
1201  *
1202  *
1203  */
1204 static NTSTATUS CDROM_ResumeAudio(int fd)
1205 {
1206 #if defined(linux)
1207     return CDROM_GetStatusCode(ioctl(fd, CDROMRESUME));
1208 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1209     return CDROM_GetStatusCode(ioctl(fd, CDIOCRESUME, NULL));
1210 #else
1211     return STATUS_NOT_SUPPORTED;
1212 #endif
1213 }
1214
1215 /******************************************************************
1216  *              CDROM_StopAudio
1217  *
1218  *
1219  */
1220 static NTSTATUS CDROM_StopAudio(int fd)
1221 {
1222 #if defined(linux)
1223     return CDROM_GetStatusCode(ioctl(fd, CDROMSTOP));
1224 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1225     return CDROM_GetStatusCode(ioctl(fd, CDIOCSTOP, NULL));
1226 #else
1227     return STATUS_NOT_SUPPORTED;
1228 #endif
1229 }
1230
1231 /******************************************************************
1232  *              CDROM_GetVolume
1233  *
1234  *
1235  */
1236 static NTSTATUS CDROM_GetVolume(int fd, VOLUME_CONTROL* vc)
1237 {
1238 #if defined(linux)
1239     struct cdrom_volctrl volc;
1240     int io;
1241
1242     io = ioctl(fd, CDROMVOLREAD, &volc);
1243     if (io != -1)
1244     {
1245         vc->PortVolume[0] = volc.channel0;
1246         vc->PortVolume[1] = volc.channel1;
1247         vc->PortVolume[2] = volc.channel2;
1248         vc->PortVolume[3] = volc.channel3;
1249     }
1250     return CDROM_GetStatusCode(io);
1251 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1252     struct  ioc_vol     volc;
1253     int io;
1254
1255     io = ioctl(fd, CDIOCGETVOL, &volc);
1256     if (io != -1)
1257     {
1258         vc->PortVolume[0] = volc.vol[0];
1259         vc->PortVolume[1] = volc.vol[1];
1260         vc->PortVolume[2] = volc.vol[2];
1261         vc->PortVolume[3] = volc.vol[3];
1262     }
1263     return CDROM_GetStatusCode(io);
1264 #else
1265     return STATUS_NOT_SUPPORTED;
1266 #endif
1267 }
1268
1269 /******************************************************************
1270  *              CDROM_SetVolume
1271  *
1272  *
1273  */
1274 static NTSTATUS CDROM_SetVolume(int fd, const VOLUME_CONTROL* vc)
1275 {
1276 #if defined(linux)
1277     struct cdrom_volctrl volc;
1278
1279     volc.channel0 = vc->PortVolume[0];
1280     volc.channel1 = vc->PortVolume[1];
1281     volc.channel2 = vc->PortVolume[2];
1282     volc.channel3 = vc->PortVolume[3];
1283
1284     return CDROM_GetStatusCode(ioctl(fd, CDROMVOLCTRL, &volc));
1285 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1286     struct  ioc_vol     volc;
1287
1288     volc.vol[0] = vc->PortVolume[0];
1289     volc.vol[1] = vc->PortVolume[1];
1290     volc.vol[2] = vc->PortVolume[2];
1291     volc.vol[3] = vc->PortVolume[3];
1292
1293     return CDROM_GetStatusCode(ioctl(fd, CDIOCSETVOL, &volc));
1294 #else
1295     return STATUS_NOT_SUPPORTED;
1296 #endif
1297 }
1298
1299 /******************************************************************
1300  *              CDROM_RawRead
1301  *
1302  * Some features of this IOCTL are rather poorly documented and
1303  * not really intuitive either:
1304  *
1305  *   1. Although the DiskOffset parameter is meant to be a
1306  *      byte offset into the disk, it is in fact the sector
1307  *      number multiplied by 2048 regardless of the actual
1308  *      sector size.
1309  *
1310  *   2. The least significant 11 bits of DiskOffset are ignored.
1311  *
1312  *   3. The TrackMode parameter has no effect on the sector
1313  *      size. The entire raw sector (i.e. 2352 bytes of data)
1314  *      is always returned. IMO the TrackMode is only used
1315  *      to check the correct sector type.
1316  *
1317  */
1318 static NTSTATUS CDROM_RawRead(int fd, const RAW_READ_INFO* raw, void* buffer, DWORD len, DWORD* sz)
1319 {
1320     int         ret = STATUS_NOT_SUPPORTED;
1321     int         io = -1;
1322
1323     TRACE("RAW_READ_INFO: DiskOffset=%i,%i SectorCount=%i TrackMode=%i\n buffer=%p len=%i sz=%p\n",
1324           raw->DiskOffset.u.HighPart, raw->DiskOffset.u.LowPart, raw->SectorCount, raw->TrackMode, buffer, len, sz);
1325
1326     if (len < raw->SectorCount * 2352) return STATUS_BUFFER_TOO_SMALL;
1327
1328 #if defined(linux)
1329     if (raw->DiskOffset.u.HighPart & ~2047) {
1330         WARN("DiskOffset points to a sector >= 2**32\n");
1331         return ret;
1332     }
1333
1334     switch (raw->TrackMode)
1335     {
1336     case YellowMode2:
1337     case XAForm2:
1338     {
1339         DWORD lba = raw->DiskOffset.QuadPart >> 11;
1340         struct cdrom_msf*       msf;
1341         PBYTE                   *bp; /* current buffer pointer */
1342         int i;
1343
1344         if ((lba + raw->SectorCount) >
1345             ((1 << 8*sizeof(msf->cdmsf_min0)) * CD_SECS * CD_FRAMES
1346              - CD_MSF_OFFSET)) {
1347             WARN("DiskOffset not accessible with MSF\n");
1348             return ret;
1349         }
1350
1351         /* Linux reads only one sector at a time.
1352          * ioctl CDROMREADRAW takes struct cdrom_msf as an argument
1353          * on the contrary to what header comments state.
1354          */
1355         lba += CD_MSF_OFFSET;
1356         for (i = 0, bp = buffer; i < raw->SectorCount;
1357              i++, lba++, bp += 2352)
1358         {
1359             msf = (struct cdrom_msf*)bp;
1360             msf->cdmsf_min0   = lba / CD_FRAMES / CD_SECS;
1361             msf->cdmsf_sec0   = lba / CD_FRAMES % CD_SECS;
1362             msf->cdmsf_frame0 = lba % CD_FRAMES;
1363             io = ioctl(fd, CDROMREADRAW, msf);
1364             if (io != 0)
1365             {
1366                 *sz = 2352 * i;
1367                 return CDROM_GetStatusCode(io);
1368             }
1369         }
1370         break;
1371     }
1372
1373     case CDDA:
1374     {
1375         struct cdrom_read_audio cdra;
1376
1377         cdra.addr.lba = raw->DiskOffset.QuadPart >> 11;
1378         TRACE("reading at %u\n", cdra.addr.lba);
1379         cdra.addr_format = CDROM_LBA;
1380         cdra.nframes = raw->SectorCount;
1381         cdra.buf = buffer;
1382         io = ioctl(fd, CDROMREADAUDIO, &cdra);
1383         break;
1384     }
1385
1386     default:
1387         FIXME("NIY: %d\n", raw->TrackMode);
1388         return STATUS_INVALID_PARAMETER;
1389     }
1390 #else
1391     switch (raw->TrackMode)
1392     {
1393     case YellowMode2:
1394         FIXME("YellowMode2: NIY\n");
1395         return ret;
1396     case XAForm2:
1397         FIXME("XAForm2: NIY\n");
1398         return ret;
1399     case CDDA:
1400         FIXME("CDDA: NIY\n");
1401         return ret;
1402     default:
1403         FIXME("NIY: %d\n", raw->TrackMode);
1404         return STATUS_INVALID_PARAMETER;
1405     }
1406 #endif
1407
1408     *sz = 2352 * raw->SectorCount;
1409     ret = CDROM_GetStatusCode(io);
1410     return ret;
1411 }
1412
1413 /******************************************************************
1414  *        CDROM_ScsiPassThroughDirect
1415  *        Implements IOCTL_SCSI_PASS_THROUGH_DIRECT
1416  *
1417  */
1418 static NTSTATUS CDROM_ScsiPassThroughDirect(int fd, PSCSI_PASS_THROUGH_DIRECT pPacket)
1419 {
1420     int ret = STATUS_NOT_SUPPORTED;
1421 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1422     sg_io_hdr_t cmd;
1423     int io;
1424 #elif defined HAVE_SCSIREQ_T_CMD
1425     scsireq_t cmd;
1426     int io;
1427 #endif
1428
1429     if (pPacket->Length < sizeof(SCSI_PASS_THROUGH_DIRECT))
1430         return STATUS_BUFFER_TOO_SMALL;
1431
1432     if (pPacket->CdbLength > 16)
1433         return STATUS_INVALID_PARAMETER;
1434
1435 #ifdef SENSEBUFLEN
1436     if (pPacket->SenseInfoLength > SENSEBUFLEN)
1437         return STATUS_INVALID_PARAMETER;
1438 #elif defined HAVE_REQUEST_SENSE
1439     if (pPacket->SenseInfoLength > sizeof(struct request_sense))
1440         return STATUS_INVALID_PARAMETER;
1441 #endif
1442
1443     if (pPacket->DataTransferLength > 0 && !pPacket->DataBuffer)
1444         return STATUS_INVALID_PARAMETER;
1445
1446 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1447     RtlZeroMemory(&cmd, sizeof(cmd));
1448
1449     cmd.interface_id   = 'S';
1450     cmd.cmd_len        = pPacket->CdbLength;
1451     cmd.mx_sb_len      = pPacket->SenseInfoLength;
1452     cmd.dxfer_len      = pPacket->DataTransferLength;
1453     cmd.dxferp         = pPacket->DataBuffer;
1454     cmd.cmdp           = pPacket->Cdb;
1455     cmd.sbp            = (unsigned char*)pPacket + pPacket->SenseInfoOffset;
1456     cmd.timeout        = pPacket->TimeOutValue*1000;
1457
1458     switch (pPacket->DataIn)
1459     {
1460     case SCSI_IOCTL_DATA_IN:
1461         cmd.dxfer_direction = SG_DXFER_FROM_DEV;
1462         break;
1463     case SCSI_IOCTL_DATA_OUT:
1464         cmd.dxfer_direction = SG_DXFER_TO_DEV;
1465         break;
1466     case SCSI_IOCTL_DATA_UNSPECIFIED:
1467         cmd.dxfer_direction = SG_DXFER_NONE;
1468         break;
1469     default:
1470        return STATUS_INVALID_PARAMETER;
1471     }
1472
1473     io = ioctl(fd, SG_IO, &cmd);
1474
1475     pPacket->ScsiStatus         = cmd.status;
1476     pPacket->DataTransferLength = cmd.resid;
1477     pPacket->SenseInfoLength    = cmd.sb_len_wr;
1478
1479     ret = CDROM_GetStatusCode(io);
1480
1481 #elif defined HAVE_SCSIREQ_T_CMD
1482
1483     memset(&cmd, 0, sizeof(cmd));
1484     memcpy(&(cmd.cmd), &(pPacket->Cdb), pPacket->CdbLength);
1485
1486     cmd.cmdlen         = pPacket->CdbLength;
1487     cmd.databuf        = pPacket->DataBuffer;
1488     cmd.datalen        = pPacket->DataTransferLength;
1489     cmd.senselen       = pPacket->SenseInfoLength;
1490     cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */
1491
1492     switch (pPacket->DataIn)
1493     {
1494     case SCSI_IOCTL_DATA_OUT:
1495         cmd.flags |= SCCMD_WRITE;
1496         break;
1497     case SCSI_IOCTL_DATA_IN:
1498         cmd.flags |= SCCMD_READ;
1499         break;
1500     case SCSI_IOCTL_DATA_UNSPECIFIED:
1501         cmd.flags = 0;
1502         break;
1503     default:
1504        return STATUS_INVALID_PARAMETER;
1505     }
1506
1507     io = ioctl(fd, SCIOCCOMMAND, &cmd);
1508
1509     switch (cmd.retsts)
1510     {
1511     case SCCMD_OK:         break;
1512     case SCCMD_TIMEOUT:    return STATUS_TIMEOUT;
1513                            break;
1514     case SCCMD_BUSY:       return STATUS_DEVICE_BUSY;
1515                            break;
1516     case SCCMD_SENSE:      break;
1517     case SCCMD_UNKNOWN:    return STATUS_UNSUCCESSFUL;
1518                            break;
1519     }
1520
1521     if (pPacket->SenseInfoLength != 0)
1522     {
1523         memcpy((char*)pPacket + pPacket->SenseInfoOffset,
1524                cmd.sense, pPacket->SenseInfoLength);
1525     }
1526
1527     pPacket->ScsiStatus = cmd.status;
1528
1529     ret = CDROM_GetStatusCode(io);
1530 #endif
1531     return ret;
1532 }
1533
1534 /******************************************************************
1535  *              CDROM_ScsiPassThrough
1536  *              Implements IOCTL_SCSI_PASS_THROUGH
1537  *
1538  */
1539 static NTSTATUS CDROM_ScsiPassThrough(int fd, PSCSI_PASS_THROUGH pPacket)
1540 {
1541     int ret = STATUS_NOT_SUPPORTED;
1542 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1543     sg_io_hdr_t cmd;
1544     int io;
1545 #elif defined HAVE_SCSIREQ_T_CMD
1546     scsireq_t cmd;
1547     int io;
1548 #endif
1549
1550     if (pPacket->Length < sizeof(SCSI_PASS_THROUGH))
1551         return STATUS_BUFFER_TOO_SMALL;
1552
1553     if (pPacket->CdbLength > 16)
1554         return STATUS_INVALID_PARAMETER;
1555
1556 #ifdef SENSEBUFLEN
1557     if (pPacket->SenseInfoLength > SENSEBUFLEN)
1558         return STATUS_INVALID_PARAMETER;
1559 #elif defined HAVE_REQUEST_SENSE
1560     if (pPacket->SenseInfoLength > sizeof(struct request_sense))
1561         return STATUS_INVALID_PARAMETER;
1562 #endif
1563
1564     if (pPacket->DataTransferLength > 0 && pPacket->DataBufferOffset < sizeof(SCSI_PASS_THROUGH))
1565         return STATUS_INVALID_PARAMETER;
1566
1567 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1568     RtlZeroMemory(&cmd, sizeof(cmd));
1569
1570     cmd.interface_id   = 'S';
1571     cmd.dxfer_len      = pPacket->DataTransferLength;
1572     cmd.dxferp         = (char*)pPacket + pPacket->DataBufferOffset;
1573     cmd.cmd_len        = pPacket->CdbLength;
1574     cmd.cmdp           = pPacket->Cdb;
1575     cmd.mx_sb_len      = pPacket->SenseInfoLength;
1576     cmd.timeout        = pPacket->TimeOutValue*1000;
1577
1578     if(cmd.mx_sb_len > 0)
1579         cmd.sbp = (unsigned char*)pPacket + pPacket->SenseInfoOffset;
1580
1581     switch (pPacket->DataIn)
1582     {
1583     case SCSI_IOCTL_DATA_IN:
1584         cmd.dxfer_direction = SG_DXFER_FROM_DEV;
1585                              break;
1586     case SCSI_IOCTL_DATA_OUT:
1587         cmd.dxfer_direction = SG_DXFER_TO_DEV;
1588                              break;
1589     case SCSI_IOCTL_DATA_UNSPECIFIED:
1590         cmd.dxfer_direction = SG_DXFER_NONE;
1591                              break;
1592     default:
1593        return STATUS_INVALID_PARAMETER;
1594     }
1595
1596     io = ioctl(fd, SG_IO, &cmd);
1597
1598     pPacket->ScsiStatus         = cmd.status;
1599     pPacket->DataTransferLength = cmd.resid;
1600     pPacket->SenseInfoLength    = cmd.sb_len_wr;
1601
1602     ret = CDROM_GetStatusCode(io);
1603
1604 #elif defined HAVE_SCSIREQ_T_CMD
1605
1606     memset(&cmd, 0, sizeof(cmd));
1607     memcpy(&(cmd.cmd), &(pPacket->Cdb), pPacket->CdbLength);
1608
1609     if ( pPacket->DataBufferOffset > 0x1000 )
1610     {
1611         cmd.databuf     = (void*)pPacket->DataBufferOffset;
1612     }
1613     else
1614     {
1615         cmd.databuf     = (char*)pPacket + pPacket->DataBufferOffset;
1616     }
1617
1618     cmd.cmdlen         = pPacket->CdbLength;
1619     cmd.datalen        = pPacket->DataTransferLength;
1620     cmd.senselen       = pPacket->SenseInfoLength;
1621     cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */
1622
1623     switch (pPacket->DataIn)
1624     {
1625     case SCSI_IOCTL_DATA_OUT:
1626         cmd.flags |= SCCMD_WRITE;
1627         break;
1628     case SCSI_IOCTL_DATA_IN:
1629         cmd.flags |= SCCMD_READ;
1630         break;
1631     case SCSI_IOCTL_DATA_UNSPECIFIED:
1632         cmd.flags = 0;
1633         break;
1634     default:
1635        return STATUS_INVALID_PARAMETER;
1636     }
1637
1638     io = ioctl(fd, SCIOCCOMMAND, &cmd);
1639
1640     switch (cmd.retsts)
1641     {
1642     case SCCMD_OK:         break;
1643     case SCCMD_TIMEOUT:    return STATUS_TIMEOUT;
1644                            break;
1645     case SCCMD_BUSY:       return STATUS_DEVICE_BUSY;
1646                            break;
1647     case SCCMD_SENSE:      break;
1648     case SCCMD_UNKNOWN:    return STATUS_UNSUCCESSFUL;
1649                            break;
1650     }
1651
1652     if (pPacket->SenseInfoLength != 0)
1653     {
1654         memcpy((char*)pPacket + pPacket->SenseInfoOffset,
1655                cmd.sense, pPacket->SenseInfoLength);
1656     }
1657
1658     pPacket->ScsiStatus = cmd.status;
1659
1660     ret = CDROM_GetStatusCode(io);
1661 #endif
1662     return ret;
1663 }
1664
1665 /******************************************************************
1666  *              CDROM_ScsiGetCaps
1667  *
1668  *
1669  */
1670 static NTSTATUS CDROM_ScsiGetCaps(PIO_SCSI_CAPABILITIES caps)
1671 {
1672     NTSTATUS    ret = STATUS_NOT_IMPLEMENTED;
1673
1674     caps->Length = sizeof(*caps);
1675 #ifdef SG_SCATTER_SZ
1676     caps->MaximumTransferLength = SG_SCATTER_SZ; /* FIXME */
1677     caps->MaximumPhysicalPages = SG_SCATTER_SZ / getpagesize();
1678     caps->SupportedAsynchronousEvents = TRUE;
1679     caps->AlignmentMask = getpagesize();
1680     caps->TaggedQueuing = FALSE; /* we could check that it works and answer TRUE */
1681     caps->AdapterScansDown = FALSE; /* FIXME ? */
1682     caps->AdapterUsesPio = FALSE; /* FIXME ? */
1683     ret = STATUS_SUCCESS;
1684 #else
1685     FIXME("Unimplemented\n");
1686 #endif
1687     return ret;
1688 }
1689
1690 /******************************************************************
1691  *              CDROM_GetAddress
1692  *
1693  * implements IOCTL_SCSI_GET_ADDRESS
1694  */
1695 static NTSTATUS CDROM_GetAddress(int fd, SCSI_ADDRESS* address)
1696 {
1697     UCHAR portnum, busid, targetid, lun;
1698
1699     address->Length = sizeof(SCSI_ADDRESS);
1700     if ( ! CDROM_GetInterfaceInfo(fd, &portnum, &busid, &targetid, &lun))
1701         return STATUS_NOT_SUPPORTED;
1702
1703     address->PortNumber = portnum; /* primary=0 secondary=1 for ide */
1704     address->PathId = busid;       /* always 0 for ide */
1705     address->TargetId = targetid;  /* master=0 slave=1 for ide */
1706     address->Lun = lun;
1707     return STATUS_SUCCESS;
1708 }
1709
1710 /******************************************************************
1711  *              DVD_StartSession
1712  *
1713  *
1714  */
1715 static NTSTATUS DVD_StartSession(int fd, PDVD_SESSION_ID sid_in, PDVD_SESSION_ID sid_out)
1716 {
1717 #if defined(linux)
1718     NTSTATUS ret = STATUS_NOT_SUPPORTED;
1719     dvd_authinfo auth_info;
1720
1721     memset( &auth_info, 0, sizeof( auth_info ) );
1722     auth_info.type = DVD_LU_SEND_AGID;
1723     if (sid_in) auth_info.lsa.agid = *(int*)sid_in; /* ?*/
1724
1725     TRACE("fd 0x%08x\n",fd);
1726     ret =CDROM_GetStatusCode(ioctl(fd, DVD_AUTH, &auth_info));
1727     *sid_out = auth_info.lsa.agid;
1728     return ret;
1729 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1730     return STATUS_NOT_SUPPORTED;
1731 #else
1732     return STATUS_NOT_SUPPORTED;
1733 #endif
1734 }
1735
1736 /******************************************************************
1737  *              DVD_EndSession
1738  *
1739  *
1740  */
1741 static NTSTATUS DVD_EndSession(int fd, PDVD_SESSION_ID sid)
1742 {
1743 #if defined(linux)
1744     dvd_authinfo auth_info;
1745
1746     memset( &auth_info, 0, sizeof( auth_info ) );
1747     auth_info.type = DVD_INVALIDATE_AGID;
1748     auth_info.lsa.agid = *(int*)sid;
1749
1750     TRACE("\n");
1751     return CDROM_GetStatusCode(ioctl(fd, DVD_AUTH, &auth_info));
1752 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1753     return STATUS_NOT_SUPPORTED;
1754 #else
1755     return STATUS_NOT_SUPPORTED;
1756 #endif
1757 }
1758
1759 /******************************************************************
1760  *              DVD_SendKey
1761  *
1762  *
1763  */
1764 static NTSTATUS DVD_SendKey(int fd, PDVD_COPY_PROTECT_KEY key)
1765 {
1766 #if defined(linux)
1767     NTSTATUS ret = STATUS_NOT_SUPPORTED;
1768     dvd_authinfo auth_info;
1769
1770     memset( &auth_info, 0, sizeof( auth_info ) );
1771     switch (key->KeyType)
1772     {
1773     case DvdChallengeKey:
1774         auth_info.type = DVD_HOST_SEND_CHALLENGE;
1775         auth_info.hsc.agid = (int)key->SessionId;
1776         TRACE("DvdChallengeKey ioc 0x%x\n", DVD_AUTH );
1777         memcpy( auth_info.hsc.chal, key->KeyData, DVD_CHALLENGE_SIZE );
1778         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
1779         break;
1780     case DvdBusKey2:
1781         auth_info.type = DVD_HOST_SEND_KEY2;
1782         auth_info.hsk.agid = (int)key->SessionId;
1783
1784         memcpy( auth_info.hsk.key, key->KeyData, DVD_KEY_SIZE );
1785         
1786         TRACE("DvdBusKey2\n");
1787         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
1788         break;
1789
1790     default:
1791         FIXME("Unknown Keytype 0x%x\n",key->KeyType);
1792     }
1793     return ret;
1794 #else
1795     FIXME("unsupported on this platform\n");
1796     return STATUS_NOT_SUPPORTED;
1797 #endif    
1798 }
1799
1800 /******************************************************************
1801  *              DVD_ReadKey
1802  *
1803  *
1804  */
1805 static NTSTATUS DVD_ReadKey(int fd, PDVD_COPY_PROTECT_KEY key)
1806 {
1807 #if defined(linux)
1808     NTSTATUS ret = STATUS_NOT_SUPPORTED;
1809     dvd_struct dvd;
1810     dvd_authinfo auth_info;
1811
1812     memset( &dvd, 0, sizeof( dvd_struct ) );
1813     memset( &auth_info, 0, sizeof( auth_info ) );
1814     switch (key->KeyType)
1815     {
1816     case DvdDiskKey:
1817         
1818         dvd.type = DVD_STRUCT_DISCKEY;
1819         dvd.disckey.agid = (int)key->SessionId;
1820         memset( dvd.disckey.value, 0, DVD_DISCKEY_SIZE );
1821         
1822         TRACE("DvdDiskKey\n");
1823         ret = CDROM_GetStatusCode(ioctl( fd, DVD_READ_STRUCT, &dvd ));
1824         if (ret == STATUS_SUCCESS)
1825             memcpy(key->KeyData,dvd.disckey.value,DVD_DISCKEY_SIZE);
1826         break;
1827     case DvdTitleKey:
1828         auth_info.type = DVD_LU_SEND_TITLE_KEY;
1829         auth_info.lstk.agid = (int)key->SessionId;
1830         auth_info.lstk.lba = (int)(key->Parameters.TitleOffset.QuadPart>>11);
1831         TRACE("DvdTitleKey session %d Quadpart 0x%08lx offset 0x%08x\n",
1832               (int)key->SessionId, (long)key->Parameters.TitleOffset.QuadPart, 
1833               auth_info.lstk.lba);
1834         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
1835         if (ret == STATUS_SUCCESS)
1836             memcpy(key->KeyData, auth_info.lstk.title_key, DVD_KEY_SIZE );
1837         break;
1838     case DvdChallengeKey:
1839
1840         auth_info.type = DVD_LU_SEND_CHALLENGE;
1841         auth_info.lsc.agid = (int)key->SessionId;
1842
1843         TRACE("DvdChallengeKey\n");
1844         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
1845         if (ret == STATUS_SUCCESS)
1846             memcpy( key->KeyData, auth_info.lsc.chal, DVD_CHALLENGE_SIZE );
1847         break;
1848     case DvdAsf:
1849         auth_info.type = DVD_LU_SEND_ASF;
1850         TRACE("DvdAsf\n");
1851         auth_info.lsasf.asf=((PDVD_ASF)key->KeyData)->SuccessFlag;
1852         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
1853         ((PDVD_ASF)key->KeyData)->SuccessFlag = auth_info.lsasf.asf;
1854         break;
1855     case DvdBusKey1:
1856         auth_info.type = DVD_LU_SEND_KEY1;
1857         auth_info.lsk.agid = (int)key->SessionId;
1858
1859         TRACE("DvdBusKey1\n");
1860         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
1861
1862         if (ret == STATUS_SUCCESS)
1863             memcpy( key->KeyData, auth_info.lsk.key, DVD_KEY_SIZE );
1864         break;
1865     case DvdGetRpcKey:
1866         auth_info.type = DVD_LU_SEND_RPC_STATE;
1867
1868         TRACE("DvdGetRpcKey\n");
1869         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
1870
1871         if (ret == STATUS_SUCCESS)
1872         {
1873             ((PDVD_RPC_KEY)key->KeyData)->TypeCode = auth_info.lrpcs.type;
1874             ((PDVD_RPC_KEY)key->KeyData)->RegionMask = auth_info.lrpcs.region_mask;
1875             ((PDVD_RPC_KEY)key->KeyData)->RpcScheme = auth_info.lrpcs.rpc_scheme;
1876         }
1877         break;
1878     default:
1879         FIXME("Unknown keytype 0x%x\n",key->KeyType);
1880     }
1881     return ret;
1882 #elif defined(__FreeBSD__) || defined(__NetBSD__)
1883     TRACE("bsd\n");
1884     return STATUS_NOT_SUPPORTED;
1885 #else
1886     TRACE("outside\n");
1887     return STATUS_NOT_SUPPORTED;
1888 #endif
1889 }
1890
1891 /******************************************************************
1892  *              DVD_GetRegion
1893  *
1894  *
1895  */
1896 static NTSTATUS DVD_GetRegion(int dev, PDVD_REGION region)
1897 {
1898     FIXME("\n");
1899     return STATUS_SUCCESS;
1900
1901 }
1902
1903 /******************************************************************
1904  *              DVD_GetRegion
1905  *
1906  *
1907  */
1908 static NTSTATUS DVD_ReadStructure(int dev, PDVD_READ_STRUCTURE structure, PDVD_LAYER_DESCRIPTOR layer)
1909 {
1910 #ifdef DVD_READ_STRUCT
1911     dvd_struct s;
1912
1913     if (structure->BlockByteOffset.u.HighPart || structure->BlockByteOffset.u.LowPart)
1914         FIXME(": BlockByteOffset is not handled\n");
1915
1916     switch (structure->Format)
1917     {
1918     case DvdPhysicalDescriptor:
1919         s.type = DVD_STRUCT_PHYSICAL;
1920         s.physical.layer_num = structure->LayerNumber;
1921         break;
1922
1923     case DvdCopyrightDescriptor:
1924         s.type = DVD_STRUCT_COPYRIGHT;
1925         s.copyright.layer_num = structure->LayerNumber;
1926         break;
1927
1928     case DvdDiskKeyDescriptor:
1929         s.type = DVD_STRUCT_DISCKEY;
1930         s.disckey.agid = structure->SessionId;
1931         break;
1932
1933     case DvdBCADescriptor:
1934         s.type = DVD_STRUCT_BCA;
1935         break;
1936
1937     case DvdManufacturerDescriptor:
1938         s.type = DVD_STRUCT_MANUFACT;
1939         s.manufact.layer_num = structure->LayerNumber;
1940         break;
1941
1942     case DvdMaxDescriptor: /* This is not a real request, no matter what MSDN says! */
1943     default:
1944         return STATUS_INVALID_PARAMETER;
1945     }
1946
1947     if (ioctl(dev, DVD_READ_STRUCT, &s) < 0)
1948        return STATUS_INVALID_PARAMETER;
1949
1950     switch (structure->Format)
1951     {
1952     case DvdPhysicalDescriptor:
1953         {
1954             internal_dvd_layer_descriptor *p = (internal_dvd_layer_descriptor *) layer;
1955             struct dvd_layer *l = &s.physical.layer[s.physical.layer_num];
1956
1957             p->MagicHeader[0] = 2;
1958             p->MagicHeader[1] = 8;
1959             p->MagicHeader[2] = 0;
1960             p->MagicHeader[3] = 0;
1961             p->BookVersion = l->book_version;
1962             p->BookType = l->book_type;
1963             p->MinimumRate = l->min_rate;
1964             p->DiskSize = l->disc_size;
1965             p->LayerType = l->layer_type;
1966             p->TrackPath = l->track_path;
1967             p->NumberOfLayers = l->nlayers;
1968             p->Reserved1 = 0;
1969             p->TrackDensity = l->track_density;
1970             p->LinearDensity = l->linear_density;
1971             p->StartingDataSector = l->start_sector;
1972             p->EndDataSector = l->end_sector;
1973             p->EndLayerZeroSector = l->end_sector_l0;
1974             p->Reserved5 = 0;
1975             p->BCAFlag = l->bca;
1976             p->Reserved6 = 0;
1977         }
1978         break;
1979
1980     case DvdCopyrightDescriptor:
1981         {
1982             PDVD_COPYRIGHT_DESCRIPTOR p = (PDVD_COPYRIGHT_DESCRIPTOR) layer;
1983
1984             p->CopyrightProtectionType = s.copyright.cpst;
1985             p->RegionManagementInformation = s.copyright.rmi;
1986             p->Reserved = 0;
1987         }
1988         break;
1989
1990     case DvdDiskKeyDescriptor:
1991         {
1992             PDVD_DISK_KEY_DESCRIPTOR p = (PDVD_DISK_KEY_DESCRIPTOR) layer;
1993
1994             memcpy(p->DiskKeyData, s.disckey.value, 2048);
1995         }
1996         break;
1997
1998     case DvdBCADescriptor:
1999         {
2000             PDVD_BCA_DESCRIPTOR p = (PDVD_BCA_DESCRIPTOR) layer;
2001
2002             memcpy(p->BCAInformation, s.bca.value, s.bca.len);
2003         }
2004         break;
2005
2006     case DvdManufacturerDescriptor:
2007         {
2008             PDVD_MANUFACTURER_DESCRIPTOR p = (PDVD_MANUFACTURER_DESCRIPTOR) layer;
2009
2010             memcpy(p->ManufacturingInformation, s.manufact.value, 2048);
2011         }
2012         break;
2013
2014     case DvdMaxDescriptor: /* Suppress warning */
2015         break;
2016     }
2017 #else
2018     FIXME("\n");
2019 #endif
2020     return STATUS_SUCCESS;
2021
2022 }
2023
2024 /******************************************************************
2025  *        GetInquiryData
2026  *        Implements the IOCTL_GET_INQUIRY_DATA ioctl.
2027  *        Returns Inquiry data for all devices on the specified scsi bus
2028  *        Returns STATUS_BUFFER_TOO_SMALL if the output buffer is too small, 
2029  *        STATUS_INVALID_DEVICE_REQUEST if the given handle isn't to a SCSI device,
2030  *        or STATUS_NOT_SUPPORTED if the OS driver is too old
2031  */
2032 static NTSTATUS GetInquiryData(int fd, PSCSI_ADAPTER_BUS_INFO BufferOut, DWORD OutBufferSize)
2033 {
2034 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
2035     PSCSI_INQUIRY_DATA pInquiryData = NULL;
2036     UCHAR sense_buffer[32];
2037     int iochk, version;
2038     sg_io_hdr_t iocmd;
2039     UCHAR inquiry[INQ_CMD_LEN] = {INQUIRY, 0, 0, 0, INQ_REPLY_LEN, 0};
2040
2041     /* Check we have a SCSI device and a supported driver */
2042     if(ioctl(fd, SG_GET_VERSION_NUM, &version) != 0)
2043     {
2044         WARN("IOCTL_SCSI_GET_INQUIRY_DATA sg driver is not loaded\n");
2045         return STATUS_INVALID_DEVICE_REQUEST;
2046     }
2047     if(version < 30000 )
2048         return STATUS_NOT_SUPPORTED;
2049
2050     /* FIXME: Enumerate devices on the bus */
2051     BufferOut->NumberOfBuses = 1;
2052     BufferOut->BusData[0].NumberOfLogicalUnits = 1;
2053     BufferOut->BusData[0].InquiryDataOffset = sizeof(SCSI_ADAPTER_BUS_INFO);
2054
2055     pInquiryData = (PSCSI_INQUIRY_DATA)(BufferOut + 1);
2056
2057     RtlZeroMemory(&iocmd, sizeof(iocmd));
2058     iocmd.interface_id = 'S';
2059     iocmd.cmd_len = sizeof(inquiry);
2060     iocmd.mx_sb_len = sizeof(sense_buffer);
2061     iocmd.dxfer_direction = SG_DXFER_FROM_DEV;
2062     iocmd.dxfer_len = INQ_REPLY_LEN;
2063     iocmd.dxferp = pInquiryData->InquiryData;
2064     iocmd.cmdp = inquiry;
2065     iocmd.sbp = sense_buffer;
2066     iocmd.timeout = 1000;
2067
2068     iochk = ioctl(fd, SG_IO, &iocmd);
2069     if(iochk != 0)
2070         WARN("ioctl SG_IO returned %d, error (%s)\n", iochk, strerror(errno));
2071
2072     CDROM_GetInterfaceInfo(fd, &BufferOut->BusData[0].InitiatorBusId, &pInquiryData->PathId, &pInquiryData->TargetId, &pInquiryData->Lun);
2073     pInquiryData->DeviceClaimed = TRUE;
2074     pInquiryData->InquiryDataLength = INQ_REPLY_LEN;
2075     pInquiryData->NextInquiryDataOffset = 0;
2076     return STATUS_SUCCESS;
2077 #else
2078     FIXME("not implemented for nonlinux\n");
2079     return STATUS_NOT_SUPPORTED;
2080 #endif
2081 }
2082
2083 /******************************************************************
2084  *              CDROM_DeviceIoControl
2085  *
2086  *
2087  */
2088 NTSTATUS CDROM_DeviceIoControl(HANDLE hDevice, 
2089                                HANDLE hEvent, PIO_APC_ROUTINE UserApcRoutine,
2090                                PVOID UserApcContext, 
2091                                PIO_STATUS_BLOCK piosb, 
2092                                ULONG dwIoControlCode,
2093                                LPVOID lpInBuffer, DWORD nInBufferSize,
2094                                LPVOID lpOutBuffer, DWORD nOutBufferSize)
2095 {
2096     DWORD       sz = 0;
2097     NTSTATUS    status = STATUS_SUCCESS;
2098     int fd, needs_close, dev;
2099
2100     TRACE("%p %s %p %d %p %d %p\n",
2101           hDevice, iocodex(dwIoControlCode), lpInBuffer, nInBufferSize,
2102           lpOutBuffer, nOutBufferSize, piosb);
2103
2104     piosb->Information = 0;
2105
2106     if ((status = server_get_unix_fd( hDevice, 0, &fd, &needs_close, NULL, NULL ))) goto error;
2107     if ((status = CDROM_Open(fd, &dev)))
2108     {
2109         if (needs_close) close( fd );
2110         goto error;
2111     }
2112
2113     switch (dwIoControlCode)
2114     {
2115     case IOCTL_STORAGE_CHECK_VERIFY:
2116     case IOCTL_CDROM_CHECK_VERIFY:
2117     case IOCTL_DISK_CHECK_VERIFY:
2118         sz = 0;
2119         CDROM_ClearCacheEntry(dev);
2120         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2121             status = STATUS_INVALID_PARAMETER;
2122         else status = CDROM_Verify(dev, fd);
2123         break;
2124
2125 /* EPP     case IOCTL_STORAGE_CHECK_VERIFY2: */
2126
2127 /* EPP     case IOCTL_STORAGE_FIND_NEW_DEVICES: */
2128 /* EPP     case IOCTL_CDROM_FIND_NEW_DEVICES: */
2129
2130     case IOCTL_STORAGE_LOAD_MEDIA:
2131     case IOCTL_CDROM_LOAD_MEDIA:
2132         sz = 0;
2133         CDROM_ClearCacheEntry(dev);
2134         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2135             status = STATUS_INVALID_PARAMETER;
2136         else status = CDROM_SetTray(fd, FALSE);
2137         break;
2138      case IOCTL_STORAGE_EJECT_MEDIA:
2139         sz = 0;
2140         CDROM_ClearCacheEntry(dev);
2141         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2142             status = STATUS_INVALID_PARAMETER;
2143         else
2144         {
2145 #ifdef __APPLE__
2146             int parent_fd = open_parent_device( fd );
2147             if (parent_fd != -1)
2148             {
2149                 /* This is ugly as hell, but Mac OS is unable to eject from the device fd,
2150                  * it wants an fd for the whole device, and it also requires the device fd
2151                  * to be closed first, so we have to close the handle that the caller gave us */
2152                 NtClose( hDevice );
2153                 if (needs_close) close( fd );
2154                 fd = parent_fd;
2155                 needs_close = 1;
2156             }
2157 #endif
2158             status = CDROM_SetTray(fd, TRUE);
2159         }
2160         break;
2161
2162     case IOCTL_CDROM_MEDIA_REMOVAL:
2163     case IOCTL_DISK_MEDIA_REMOVAL:
2164     case IOCTL_STORAGE_MEDIA_REMOVAL:
2165     case IOCTL_STORAGE_EJECTION_CONTROL:
2166         /* FIXME the last ioctl:s is not the same as the two others...
2167          * lockcount/owner should be handled */
2168         sz = 0;
2169         CDROM_ClearCacheEntry(dev);
2170         if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2171         else if (nInBufferSize < sizeof(PREVENT_MEDIA_REMOVAL)) status = STATUS_BUFFER_TOO_SMALL;
2172         else status = CDROM_ControlEjection(fd, (const PREVENT_MEDIA_REMOVAL*)lpInBuffer);
2173         break;
2174
2175 /* EPP     case IOCTL_STORAGE_GET_MEDIA_TYPES: */
2176
2177     case IOCTL_STORAGE_GET_DEVICE_NUMBER:
2178         sz = sizeof(STORAGE_DEVICE_NUMBER);
2179         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2180         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2181         else status = CDROM_GetDeviceNumber(dev, (STORAGE_DEVICE_NUMBER*)lpOutBuffer);
2182         break;
2183
2184     case IOCTL_STORAGE_RESET_DEVICE:
2185         sz = 0;
2186         CDROM_ClearCacheEntry(dev);
2187         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2188             status = STATUS_INVALID_PARAMETER;
2189         else status = CDROM_ResetAudio(fd);
2190         break;
2191
2192     case IOCTL_CDROM_GET_CONTROL:
2193         sz = sizeof(CDROM_AUDIO_CONTROL);
2194         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2195         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2196         else status = CDROM_GetControl(dev, (CDROM_AUDIO_CONTROL*)lpOutBuffer);
2197         break;
2198
2199     case IOCTL_CDROM_GET_DRIVE_GEOMETRY:
2200         sz = sizeof(DISK_GEOMETRY);
2201         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2202         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2203         else status = CDROM_GetDriveGeometry(dev, fd, (DISK_GEOMETRY*)lpOutBuffer);
2204         break;
2205
2206     case IOCTL_CDROM_DISK_TYPE:
2207         sz = sizeof(CDROM_DISK_DATA);
2208         /* CDROM_ClearCacheEntry(dev); */
2209         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2210         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2211         else status = CDROM_GetDiskData(dev, fd, (CDROM_DISK_DATA*)lpOutBuffer);
2212         break;
2213
2214 /* EPP     case IOCTL_CDROM_GET_LAST_SESSION: */
2215
2216     case IOCTL_CDROM_READ_Q_CHANNEL:
2217         sz = sizeof(SUB_Q_CHANNEL_DATA);
2218         if (lpInBuffer == NULL || nInBufferSize < sizeof(CDROM_SUB_Q_DATA_FORMAT))
2219             status = STATUS_INVALID_PARAMETER;
2220         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2221         else status = CDROM_ReadQChannel(dev, fd, (const CDROM_SUB_Q_DATA_FORMAT*)lpInBuffer,
2222                                         (SUB_Q_CHANNEL_DATA*)lpOutBuffer);
2223         break;
2224
2225     case IOCTL_CDROM_READ_TOC:
2226         sz = sizeof(CDROM_TOC);
2227         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2228         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2229         else status = CDROM_ReadTOC(dev, fd, (CDROM_TOC*)lpOutBuffer);
2230         break;
2231
2232 /* EPP     case IOCTL_CDROM_READ_TOC_EX: */
2233
2234     case IOCTL_CDROM_PAUSE_AUDIO:
2235         sz = 0;
2236         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2237             status = STATUS_INVALID_PARAMETER;
2238         else status = CDROM_PauseAudio(fd);
2239         break;
2240     case IOCTL_CDROM_PLAY_AUDIO_MSF:
2241         sz = 0;
2242         if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2243         else if (nInBufferSize < sizeof(CDROM_PLAY_AUDIO_MSF)) status = STATUS_BUFFER_TOO_SMALL;
2244         else status = CDROM_PlayAudioMSF(fd, (const CDROM_PLAY_AUDIO_MSF*)lpInBuffer);
2245         break;
2246     case IOCTL_CDROM_RESUME_AUDIO:
2247         sz = 0;
2248         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2249             status = STATUS_INVALID_PARAMETER;
2250         else status = CDROM_ResumeAudio(fd);
2251         break;
2252     case IOCTL_CDROM_SEEK_AUDIO_MSF:
2253         sz = 0;
2254         if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2255         else if (nInBufferSize < sizeof(CDROM_SEEK_AUDIO_MSF)) status = STATUS_BUFFER_TOO_SMALL;
2256         else status = CDROM_SeekAudioMSF(dev, fd, (const CDROM_SEEK_AUDIO_MSF*)lpInBuffer);
2257         break;
2258     case IOCTL_CDROM_STOP_AUDIO:
2259         sz = 0;
2260         CDROM_ClearCacheEntry(dev); /* Maybe intention is to change media */
2261         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2262             status = STATUS_INVALID_PARAMETER;
2263         else status = CDROM_StopAudio(fd);
2264         break;
2265     case IOCTL_CDROM_GET_VOLUME:
2266         sz = sizeof(VOLUME_CONTROL);
2267         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2268         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2269         else status = CDROM_GetVolume(fd, (VOLUME_CONTROL*)lpOutBuffer);
2270         break;
2271     case IOCTL_CDROM_SET_VOLUME:
2272         sz = 0;
2273         CDROM_ClearCacheEntry(dev);
2274         if (lpInBuffer == NULL || nInBufferSize < sizeof(VOLUME_CONTROL) || lpOutBuffer != NULL)
2275             status = STATUS_INVALID_PARAMETER;
2276         else status = CDROM_SetVolume(fd, (const VOLUME_CONTROL*)lpInBuffer);
2277         break;
2278     case IOCTL_CDROM_RAW_READ:
2279         sz = 0;
2280         if (nInBufferSize < sizeof(RAW_READ_INFO)) status = STATUS_INVALID_PARAMETER;
2281         else if (lpOutBuffer == NULL) status = STATUS_BUFFER_TOO_SMALL;
2282         else status = CDROM_RawRead(fd, (const RAW_READ_INFO*)lpInBuffer,
2283                                    lpOutBuffer, nOutBufferSize, &sz);
2284         break;
2285     case IOCTL_SCSI_GET_ADDRESS:
2286         sz = sizeof(SCSI_ADDRESS);
2287         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2288         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2289         else status = CDROM_GetAddress(fd, (SCSI_ADDRESS*)lpOutBuffer);
2290         break;
2291     case IOCTL_SCSI_PASS_THROUGH_DIRECT:
2292         sz = sizeof(SCSI_PASS_THROUGH_DIRECT);
2293         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
2294         else if (nOutBufferSize < sizeof(SCSI_PASS_THROUGH_DIRECT)) status = STATUS_BUFFER_TOO_SMALL;
2295         else status = CDROM_ScsiPassThroughDirect(fd, (PSCSI_PASS_THROUGH_DIRECT)lpOutBuffer);
2296         break;
2297     case IOCTL_SCSI_PASS_THROUGH:
2298         sz = sizeof(SCSI_PASS_THROUGH);
2299         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
2300         else if (nOutBufferSize < sizeof(SCSI_PASS_THROUGH)) status = STATUS_BUFFER_TOO_SMALL;
2301         else status = CDROM_ScsiPassThrough(fd, (PSCSI_PASS_THROUGH)lpOutBuffer);
2302         break;
2303     case IOCTL_SCSI_GET_CAPABILITIES:
2304         sz = sizeof(IO_SCSI_CAPABILITIES);
2305         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
2306         else if (nOutBufferSize < sizeof(IO_SCSI_CAPABILITIES)) status = STATUS_BUFFER_TOO_SMALL;
2307         else status = CDROM_ScsiGetCaps((PIO_SCSI_CAPABILITIES)lpOutBuffer);
2308         break;
2309     case IOCTL_DVD_START_SESSION:
2310         sz = sizeof(DVD_SESSION_ID);
2311         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
2312         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2313         else
2314         {
2315             TRACE("before in 0x%08x out 0x%08x\n",(lpInBuffer)?*(PDVD_SESSION_ID)lpInBuffer:0,
2316                   *(PDVD_SESSION_ID)lpOutBuffer);
2317             status = DVD_StartSession(fd, (PDVD_SESSION_ID)lpInBuffer, (PDVD_SESSION_ID)lpOutBuffer);
2318             TRACE("before in 0x%08x out 0x%08x\n",(lpInBuffer)?*(PDVD_SESSION_ID)lpInBuffer:0,
2319                   *(PDVD_SESSION_ID)lpOutBuffer);
2320         }
2321         break;
2322     case IOCTL_DVD_END_SESSION:
2323         sz = sizeof(DVD_SESSION_ID);
2324         if ((lpInBuffer == NULL) ||  (nInBufferSize < sz))status = STATUS_INVALID_PARAMETER;
2325         else status = DVD_EndSession(fd, (PDVD_SESSION_ID)lpInBuffer);
2326         break;
2327     case IOCTL_DVD_SEND_KEY:
2328         sz = 0;
2329         if (!lpInBuffer ||
2330             (((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength != nInBufferSize))
2331             status = STATUS_INVALID_PARAMETER;
2332         else
2333         {
2334             TRACE("doing DVD_SendKey\n");
2335             status = DVD_SendKey(fd, (PDVD_COPY_PROTECT_KEY)lpInBuffer);
2336         }
2337         break;
2338     case IOCTL_DVD_READ_KEY:
2339         if (!lpInBuffer ||
2340             (((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength != nInBufferSize))
2341             status = STATUS_INVALID_PARAMETER;
2342         else if (lpInBuffer !=lpOutBuffer) status = STATUS_BUFFER_TOO_SMALL;
2343         else
2344         {
2345             TRACE("doing DVD_READ_KEY\n");
2346             sz = ((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength;
2347             status = DVD_ReadKey(fd, (PDVD_COPY_PROTECT_KEY)lpInBuffer);
2348         }
2349         break;
2350     case IOCTL_DVD_GET_REGION:
2351         sz = sizeof(DVD_REGION);
2352         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2353         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2354         TRACE("doing DVD_Get_REGION\n");
2355         status = DVD_GetRegion(fd, (PDVD_REGION)lpOutBuffer);
2356         break;
2357     case IOCTL_DVD_READ_STRUCTURE:
2358         sz = sizeof(DVD_LAYER_DESCRIPTOR);
2359         if (lpInBuffer == NULL || nInBufferSize != sizeof(DVD_READ_STRUCTURE)) status = STATUS_INVALID_PARAMETER;
2360         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2361         else
2362         {
2363             TRACE("doing DVD_READ_STRUCTURE\n");
2364             status = DVD_ReadStructure(fd, (PDVD_READ_STRUCTURE)lpInBuffer, (PDVD_LAYER_DESCRIPTOR)lpOutBuffer);
2365         }
2366         break;
2367
2368     case IOCTL_SCSI_GET_INQUIRY_DATA:
2369         sz = INQ_REPLY_LEN;
2370         status = GetInquiryData(fd, (PSCSI_ADAPTER_BUS_INFO)lpOutBuffer, nOutBufferSize);
2371         break;
2372
2373     default:
2374         FIXME("Unsupported IOCTL %x (type=%x access=%x func=%x meth=%x)\n", 
2375               dwIoControlCode, dwIoControlCode >> 16, (dwIoControlCode >> 14) & 3,
2376               (dwIoControlCode >> 2) & 0xFFF, dwIoControlCode & 3);
2377         sz = 0;
2378         status = STATUS_INVALID_PARAMETER;
2379         break;
2380     }
2381     if (needs_close) close( fd );
2382  error:
2383     piosb->u.Status = status;
2384     piosb->Information = sz;
2385     if (hEvent) NtSetEvent(hEvent, NULL);
2386     return status;
2387 }