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