kernel32: Add support for IOCTL_STORAGE_CHECK_VERIFY2.
[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 # undef FAILED           /* avoid conflict with winerror.h */
53 #endif
54 #ifdef HAVE_SCSI_SCSI_IOCTL_H
55 # include <scsi/scsi_ioctl.h>
56 #endif
57 #ifdef HAVE_LINUX_MAJOR_H
58 # include <linux/major.h>
59 #endif
60 #ifdef HAVE_LINUX_HDREG_H
61 # include <linux/hdreg.h>
62 #endif
63 #ifdef HAVE_LINUX_PARAM_H
64 # include <linux/param.h>
65 #endif
66 #ifdef HAVE_LINUX_CDROM_H
67 # include <linux/cdrom.h>
68 #endif
69 #ifdef HAVE_LINUX_UCDROM_H
70 # include <linux/ucdrom.h>
71 #endif
72 #ifdef HAVE_SYS_CDIO_H
73 # include <sys/cdio.h>
74 #endif
75 #ifdef HAVE_SYS_SCSIIO_H
76 # include <sys/scsiio.h>
77 #endif
78
79 #ifdef HAVE_IOKIT_IOKITLIB_H
80 # include <libkern/OSByteOrder.h>
81 # include <sys/disk.h>
82 # include <IOKit/IOKitLib.h>
83 # include <IOKit/storage/IOMedia.h>
84 # include <IOKit/storage/IOCDMediaBSDClient.h>
85 # include <IOKit/storage/IODVDMediaBSDClient.h>
86 # include <IOKit/scsi/SCSITask.h>
87 # include <IOKit/scsi/SCSICmds_REQUEST_SENSE_Defs.h>
88 # define SENSEBUFLEN kSenseDefaultSize
89
90 typedef struct
91 {
92     uint32_t attribute;
93     uint32_t timeout;
94     uint32_t response;
95     uint32_t status;
96     uint8_t direction;
97     uint8_t cdbSize;
98     uint8_t reserved0144[2];
99     uint8_t cdb[16];
100     void* buffer;
101     uint64_t bufferSize;
102     void* sense;
103     uint64_t senseLen;
104 } dk_scsi_command_t;
105
106 typedef struct
107 {
108     uint64_t bus;
109     uint64_t port;
110     uint64_t target;
111     uint64_t lun;
112 } dk_scsi_identify_t;
113
114 #define DKIOCSCSICOMMAND _IOWR('d', 253, dk_scsi_command_t)
115 #define DKIOCSCSIIDENTIFY _IOR('d', 254, dk_scsi_identify_t)
116
117 #endif
118
119 #define NONAMELESSUNION
120 #define NONAMELESSSTRUCT
121 #include "ntstatus.h"
122 #define WIN32_NO_STATUS
123 #include "windef.h"
124 #include "winternl.h"
125 #include "winioctl.h"
126 #include "ntddstor.h"
127 #include "ntddcdrm.h"
128 #include "ddk/ntddcdvd.h"
129 #include "ntddscsi.h"
130 #include "ntdll_misc.h"
131 #include "wine/server.h"
132 #include "wine/library.h"
133 #include "wine/debug.h"
134
135 WINE_DEFAULT_DEBUG_CHANNEL(cdrom);
136
137 /* Non-Linux systems do not have linux/cdrom.h and the like, and thus
138    lack the following constants. */
139
140 #ifndef CD_SECS
141 # define CD_SECS              60 /* seconds per minute */
142 #endif
143 #ifndef CD_FRAMES
144 # define CD_FRAMES            75 /* frames per second */
145 #endif
146
147 static const struct iocodexs
148 {
149   DWORD code;
150   const char *codex;
151 } iocodextable[] = {
152 #define X(x) { x, #x },
153 X(IOCTL_CDROM_CHECK_VERIFY)
154 X(IOCTL_CDROM_CURRENT_POSITION)
155 X(IOCTL_CDROM_DISK_TYPE)
156 X(IOCTL_CDROM_GET_CONTROL)
157 X(IOCTL_CDROM_GET_DRIVE_GEOMETRY)
158 X(IOCTL_CDROM_GET_VOLUME)
159 X(IOCTL_CDROM_LOAD_MEDIA)
160 X(IOCTL_CDROM_MEDIA_CATALOG)
161 X(IOCTL_CDROM_MEDIA_REMOVAL)
162 X(IOCTL_CDROM_PAUSE_AUDIO)
163 X(IOCTL_CDROM_PLAY_AUDIO_MSF)
164 X(IOCTL_CDROM_RAW_READ)
165 X(IOCTL_CDROM_READ_Q_CHANNEL)
166 X(IOCTL_CDROM_READ_TOC)
167 X(IOCTL_CDROM_RESUME_AUDIO)
168 X(IOCTL_CDROM_SEEK_AUDIO_MSF)
169 X(IOCTL_CDROM_SET_VOLUME)
170 X(IOCTL_CDROM_STOP_AUDIO)
171 X(IOCTL_CDROM_TRACK_ISRC)
172 X(IOCTL_DISK_MEDIA_REMOVAL)
173 X(IOCTL_DVD_END_SESSION)
174 X(IOCTL_DVD_GET_REGION)
175 X(IOCTL_DVD_READ_KEY)
176 X(IOCTL_DVD_READ_STRUCTURE)
177 X(IOCTL_DVD_SEND_KEY)
178 X(IOCTL_DVD_START_SESSION)
179 X(IOCTL_SCSI_GET_ADDRESS)
180 X(IOCTL_SCSI_GET_CAPABILITIES)
181 X(IOCTL_SCSI_GET_INQUIRY_DATA)
182 X(IOCTL_SCSI_PASS_THROUGH)
183 X(IOCTL_SCSI_PASS_THROUGH_DIRECT)
184 X(IOCTL_STORAGE_CHECK_VERIFY)
185 X(IOCTL_STORAGE_CHECK_VERIFY2)
186 X(IOCTL_STORAGE_EJECTION_CONTROL)
187 X(IOCTL_STORAGE_EJECT_MEDIA)
188 X(IOCTL_STORAGE_GET_DEVICE_NUMBER)
189 X(IOCTL_STORAGE_GET_MEDIA_TYPES)
190 X(IOCTL_STORAGE_GET_MEDIA_TYPES_EX)
191 X(IOCTL_STORAGE_LOAD_MEDIA)
192 X(IOCTL_STORAGE_MEDIA_REMOVAL)
193 X(IOCTL_STORAGE_RESET_DEVICE)
194 #undef X
195 };
196 static const char *iocodex(DWORD code)
197 {
198    unsigned int i;
199    static char buffer[25];
200    for(i=0; i<sizeof(iocodextable)/sizeof(struct iocodexs); i++)
201       if (code==iocodextable[i].code)
202          return iocodextable[i].codex;
203    sprintf(buffer, "IOCTL_CODE_%x", (int)code);
204    return buffer;
205 }
206
207 #define INQ_REPLY_LEN 36
208 #define INQ_CMD_LEN 6
209
210 #define FRAME_OF_ADDR(a) (((int)(a)[1] * CD_SECS + (a)[2]) * CD_FRAMES + (a)[3])
211 #define FRAME_OF_MSF(a) (((int)(a).M * CD_SECS + (a).S) * CD_FRAMES + (a).F)
212 #define FRAME_OF_TOC(toc, idx)  FRAME_OF_ADDR((toc).TrackData[idx - (toc).FirstTrack].Address)
213 #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;}
214
215 /* The documented format of DVD_LAYER_DESCRIPTOR is wrong. Even the format in the
216  * DDK's header is wrong. There are four bytes at the start  defined by
217  * MMC-5. The first two are the size of the structure in big-endian order as
218  * defined by MMC-5. The other two are reserved.
219  */
220 typedef struct
221 {
222     UCHAR DataLength[2];
223     UCHAR Reserved0[2];
224     UCHAR BookVersion : 4;
225     UCHAR BookType : 4;
226     UCHAR MinimumRate : 4;
227     UCHAR DiskSize : 4;
228     UCHAR LayerType : 4;
229     UCHAR TrackPath : 1;
230     UCHAR NumberOfLayers : 2;
231     UCHAR Reserved1 : 1;
232     UCHAR TrackDensity : 4;
233     UCHAR LinearDensity : 4;
234     ULONG StartingDataSector;
235     ULONG EndDataSector;
236     ULONG EndLayerZeroSector;
237     UCHAR Reserved5 : 7;
238     UCHAR BCAFlag : 1;
239     UCHAR Reserved6;
240 } internal_dvd_layer_descriptor;
241
242
243 static NTSTATUS CDROM_ReadTOC(int, int, CDROM_TOC*);
244 static NTSTATUS CDROM_GetStatusCode(int);
245
246
247 #ifdef linux
248
249 # ifndef IDE6_MAJOR
250 #  define IDE6_MAJOR 88
251 # endif
252 # ifndef IDE7_MAJOR
253 #  define IDE7_MAJOR 89
254 # endif
255
256 # ifdef CDROM_SEND_PACKET
257 /* structure for CDROM_PACKET_COMMAND ioctl */
258 /* not all Linux versions have all the fields, so we define the
259  * structure ourselves to make sure */
260 struct linux_cdrom_generic_command
261 {
262     unsigned char          cmd[CDROM_PACKET_SIZE];
263     unsigned char         *buffer;
264     unsigned int           buflen;
265     int                    stat;
266     struct request_sense  *sense;
267     unsigned char          data_direction;
268     int                    quiet;
269     int                    timeout;
270     void                  *reserved[1];
271 };
272 # endif  /* CDROM_SEND_PACKET */
273
274 #endif  /* linux */
275
276 /* FIXME: this is needed because we can't open simultaneously several times /dev/cdrom
277  * this should be removed when a proper device interface is implemented
278  * 
279  * (WS) We need this to keep track of current position and to safely
280  * detect media changes. Besides this should provide a great speed up
281  * for toc inquiries.
282  */
283 struct cdrom_cache {
284     dev_t       device;
285     ino_t       inode;
286     char        toc_good; /* if false, will reread TOC from disk */
287     CDROM_TOC   toc;
288     SUB_Q_CURRENT_POSITION CurrentPosition;
289 };
290 /* who has more than 5 cdroms on his/her machine ?? */
291 /* FIXME: this should grow depending on the number of cdroms we install/configure 
292  * at startup
293  */
294 #define MAX_CACHE_ENTRIES       5
295 static struct cdrom_cache cdrom_cache[MAX_CACHE_ENTRIES];
296
297 static RTL_CRITICAL_SECTION cache_section;
298 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
299 {
300     0, 0, &cache_section,
301     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
302       0, 0, { (DWORD_PTR)(__FILE__ ": cache_section") }
303 };
304 static RTL_CRITICAL_SECTION cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
305
306 /* Proposed media change function: not really needed at this time */
307 /* This is a 1 or 0 type of function */
308 #if 0
309 static int CDROM_MediaChanged(int dev)
310 {
311    int i;
312
313    struct cdrom_tochdr  hdr;
314    struct cdrom_tocentry entry;
315
316    if (dev < 0 || dev >= MAX_CACHE_ENTRIES)
317       return 0;
318    if ( ioctl(cdrom_cache[dev].fd, CDROMREADTOCHDR, &hdr) == -1 )
319       return 0;
320
321    if ( memcmp(&hdr, &cdrom_cache[dev].hdr, sizeof(struct cdrom_tochdr)) )
322       return 1;
323
324    for (i=hdr.cdth_trk0; i<=hdr.cdth_trk1+1; i++)
325    {
326       if (i == hdr.cdth_trk1 + 1)
327       {
328          entry.cdte_track = CDROM_LEADOUT;
329       } else {
330          entry.cdte_track = i;
331       }
332       entry.cdte_format = CDROM_MSF;
333       if ( ioctl(cdrom_cache[dev].fd, CDROMREADTOCENTRY, &entry) == -1)
334          return 0;
335       if ( memcmp(&entry, cdrom_cache[dev].entry+i-hdr.cdth_trk0,
336                               sizeof(struct cdrom_tocentry)) )
337          return 1;
338    }
339    return 0;
340 }
341 #endif
342
343
344 /******************************************************************
345  *              get_parent_device
346  *
347  * On Mac OS, get the device for the whole disk from a fd that points to a partition.
348  * This is ugly and inefficient, but we have no choice since the partition fd doesn't
349  * support the eject ioctl.
350  */
351 #ifdef __APPLE__
352 static NTSTATUS get_parent_device( int fd, char *name, size_t len )
353 {
354     NTSTATUS status = STATUS_NO_SUCH_FILE;
355     struct stat st;
356     int i;
357     io_service_t service;
358     CFMutableDictionaryRef dict;
359     CFTypeRef val;
360
361     if (fstat( fd, &st ) == -1) return FILE_GetNtStatus();
362     if (!S_ISCHR( st.st_mode )) return STATUS_OBJECT_TYPE_MISMATCH;
363
364     /* create a dictionary with the right major/minor numbers */
365
366     if (!(dict = IOServiceMatching( kIOMediaClass ))) return STATUS_NO_MEMORY;
367
368     i = major( st.st_rdev );
369     val = CFNumberCreate( NULL, kCFNumberIntType, &i );
370     CFDictionaryAddValue( dict, CFSTR( "BSD Major" ), val );
371     CFRelease( val );
372
373     i = minor( st.st_rdev );
374     val = CFNumberCreate( NULL, kCFNumberIntType, &i );
375     CFDictionaryAddValue( dict, CFSTR( "BSD Minor" ), val );
376     CFRelease( val );
377
378     CFDictionaryAddValue( dict, CFSTR("Removable"), kCFBooleanTrue );
379
380     service = IOServiceGetMatchingService( kIOMasterPortDefault, dict );
381
382     /* now look for the parent that has the "Whole" attribute set to TRUE */
383
384     while (service)
385     {
386         io_service_t parent = 0;
387         CFBooleanRef whole;
388         CFStringRef str;
389         int ok;
390
391         if (!IOObjectConformsTo( service, kIOMediaClass ))
392             goto next;
393         if (!(whole = IORegistryEntryCreateCFProperty( service, CFSTR("Whole"), NULL, 0 )))
394             goto next;
395         ok = (whole == kCFBooleanTrue);
396         CFRelease( whole );
397         if (!ok) goto next;
398
399         if ((str = IORegistryEntryCreateCFProperty( service, CFSTR("BSD Name"), NULL, 0 )))
400         {
401             strcpy( name, "/dev/r" );
402             CFStringGetCString( str, name + 6, len - 6, kCFStringEncodingUTF8 );
403             CFRelease( str );
404             status = STATUS_SUCCESS;
405         }
406         IOObjectRelease( service );
407         break;
408
409 next:
410         IORegistryEntryGetParentEntry( service, kIOServicePlane, &parent );
411         IOObjectRelease( service );
412         service = parent;
413     }
414     return status;
415 }
416 #endif
417
418
419 /******************************************************************
420  *              CDROM_SyncCache                          [internal]
421  *
422  * Read the TOC in and store it in the cdrom_cache structure.
423  * Further requests for the TOC will be copied from the cache
424  * unless certain events like disk ejection is detected, in which
425  * case the cache will be cleared, causing it to be resynced.
426  * The cache section must be held by caller.
427  */
428 static NTSTATUS CDROM_SyncCache(int dev, int fd)
429 {
430 #ifdef linux
431    int i, tsz;
432    struct cdrom_tochdr          hdr;
433    struct cdrom_tocentry        entry;
434
435    CDROM_TOC *toc = &cdrom_cache[dev].toc;
436    cdrom_cache[dev].toc_good = 0;
437
438    if (ioctl(fd, CDROMREADTOCHDR, &hdr) == -1)
439    {
440       WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
441       return FILE_GetNtStatus();
442    }
443
444    toc->FirstTrack = hdr.cdth_trk0;
445    toc->LastTrack  = hdr.cdth_trk1;
446    tsz = sizeof(toc->FirstTrack) + sizeof(toc->LastTrack)
447        + sizeof(TRACK_DATA) * (toc->LastTrack-toc->FirstTrack+2);
448    toc->Length[0] = tsz >> 8;
449    toc->Length[1] = tsz;
450
451    TRACE("caching toc from=%d to=%d\n", toc->FirstTrack, toc->LastTrack );
452
453    for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
454    {
455      if (i == toc->LastTrack + 1)
456        entry.cdte_track = CDROM_LEADOUT;
457      else 
458        entry.cdte_track = i;
459      entry.cdte_format = CDROM_MSF;
460      if (ioctl(fd, CDROMREADTOCENTRY, &entry) == -1)
461      {
462        WARN("error read entry (%s)\n", strerror(errno));
463        return FILE_GetNtStatus();
464      }
465      toc->TrackData[i - toc->FirstTrack].Control = entry.cdte_ctrl;
466      toc->TrackData[i - toc->FirstTrack].Adr = entry.cdte_adr;
467      /* marking last track with leadout value as index */
468      toc->TrackData[i - toc->FirstTrack].TrackNumber = entry.cdte_track;
469      toc->TrackData[i - toc->FirstTrack].Address[0] = 0;
470      toc->TrackData[i - toc->FirstTrack].Address[1] = entry.cdte_addr.msf.minute;
471      toc->TrackData[i - toc->FirstTrack].Address[2] = entry.cdte_addr.msf.second;
472      toc->TrackData[i - toc->FirstTrack].Address[3] = entry.cdte_addr.msf.frame;
473    }
474    cdrom_cache[dev].toc_good = 1;
475    return STATUS_SUCCESS;
476
477 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
478
479    int i, tsz;
480    struct ioc_toc_header hdr;
481    struct ioc_read_toc_entry entry;
482    struct cd_toc_entry toc_buffer;
483
484    CDROM_TOC *toc = &cdrom_cache[dev].toc;
485    cdrom_cache[dev].toc_good = 0;
486
487     if (ioctl(fd, CDIOREADTOCHEADER, &hdr) == -1)
488     {
489         WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
490         return FILE_GetNtStatus();
491     }
492     toc->FirstTrack = hdr.starting_track;
493     toc->LastTrack  = hdr.ending_track;
494     tsz = sizeof(toc->FirstTrack) + sizeof(toc->LastTrack)
495         + sizeof(TRACK_DATA) * (toc->LastTrack-toc->FirstTrack+2);
496     toc->Length[0] = tsz >> 8;
497     toc->Length[1] = tsz;
498
499     TRACE("caching toc from=%d to=%d\n", toc->FirstTrack, toc->LastTrack );
500
501     for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
502     {
503         if (i == toc->LastTrack + 1)
504         {
505 #define LEADOUT 0xaa
506             entry.starting_track = LEADOUT;
507         } else {
508             entry.starting_track = i;
509         }
510         memset(&toc_buffer, 0, sizeof(toc_buffer));
511         entry.address_format = CD_MSF_FORMAT;
512         entry.data_len = sizeof(toc_buffer);
513         entry.data = &toc_buffer;
514         if (ioctl(fd, CDIOREADTOCENTRYS, &entry) == -1)
515         {
516             WARN("error read entry (%s)\n", strerror(errno));
517             return FILE_GetNtStatus();
518         }
519         toc->TrackData[i - toc->FirstTrack].Control = toc_buffer.control;
520         toc->TrackData[i - toc->FirstTrack].Adr = toc_buffer.addr_type;
521         /* marking last track with leadout value as index */
522         toc->TrackData[i - toc->FirstTrack].TrackNumber = entry.starting_track;
523         toc->TrackData[i - toc->FirstTrack].Address[0] = 0;
524         toc->TrackData[i - toc->FirstTrack].Address[1] = toc_buffer.addr.msf.minute;
525         toc->TrackData[i - toc->FirstTrack].Address[2] = toc_buffer.addr.msf.second;
526         toc->TrackData[i - toc->FirstTrack].Address[3] = toc_buffer.addr.msf.frame;
527     }
528     cdrom_cache[dev].toc_good = 1;
529     return STATUS_SUCCESS;
530
531 #elif defined(__APPLE__)
532     int i;
533     dk_cd_read_toc_t hdr;
534     CDROM_TOC *toc = &cdrom_cache[dev].toc;
535     cdrom_cache[dev].toc_good = 0;
536
537     memset( &hdr, 0, sizeof(hdr) );
538     hdr.buffer = toc;
539     hdr.bufferLength = sizeof(*toc);
540     if (ioctl(fd, DKIOCCDREADTOC, &hdr) == -1)
541     {
542         WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
543         return FILE_GetNtStatus();
544     }
545     for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
546     {
547         /* convert address format */
548         TRACK_DATA *data = &toc->TrackData[i - toc->FirstTrack];
549         DWORD frame = (((DWORD)data->Address[0] << 24) | ((DWORD)data->Address[1] << 16) |
550                        ((DWORD)data->Address[2] << 8) | data->Address[3]);
551         MSF_OF_FRAME( data->Address[1], frame );
552         data->Address[0] = 0;
553     }
554
555     cdrom_cache[dev].toc_good = 1;
556     return STATUS_SUCCESS;
557 #else
558     FIXME("not supported on this O/S\n");
559     return STATUS_NOT_SUPPORTED;
560 #endif
561 }
562
563 static void CDROM_ClearCacheEntry(int dev)
564 {
565     RtlEnterCriticalSection( &cache_section );
566     cdrom_cache[dev].toc_good = 0;
567     RtlLeaveCriticalSection( &cache_section );
568 }
569
570
571
572 /******************************************************************
573  *              CDROM_GetInterfaceInfo
574  *
575  * Determines the ide interface (the number after the ide), and the
576  * number of the device on that interface for ide cdroms (*iface <= 1).
577  * Determines the scsi information for scsi cdroms (*iface >= 2).
578  * Returns false if the info cannot not be obtained.
579  */
580 static int CDROM_GetInterfaceInfo(int fd, UCHAR* iface, UCHAR* port, UCHAR* device, UCHAR* lun)
581 {
582 #if defined(linux)
583     struct stat st;
584     if ( fstat(fd, &st) == -1 || ! S_ISBLK(st.st_mode)) return 0;
585     *port = 0;
586     *iface = 0;
587     *device = 0;
588     *lun = 0;
589     switch (major(st.st_rdev)) {
590     case IDE0_MAJOR: *iface = 0; break;
591     case IDE1_MAJOR: *iface = 1; break;
592     case IDE2_MAJOR: *iface = 2; break;
593     case IDE3_MAJOR: *iface = 3; break;
594     case IDE4_MAJOR: *iface = 4; break;
595     case IDE5_MAJOR: *iface = 5; break;
596     case IDE6_MAJOR: *iface = 6; break;
597     case IDE7_MAJOR: *iface = 7; break;
598     default: *port = 1; break;
599     }
600
601     if (*port == 0)
602         *device = (minor(st.st_rdev) >> 6);
603     else
604     {
605 #ifdef SCSI_IOCTL_GET_IDLUN
606         UINT32 idlun[2];
607         if (ioctl(fd, SCSI_IOCTL_GET_IDLUN, idlun) != -1)
608         {
609             *port = (idlun[0] >> 24) & 0xff;
610             *iface = ((idlun[0] >> 16) & 0xff) + 2;
611             *device = idlun[0] & 0xff;
612             *lun = (idlun[0] >> 8) & 0xff;
613         }
614         else
615 #endif
616         {
617             WARN("CD-ROM device (%d, %d) not supported\n", major(st.st_rdev), minor(st.st_rdev));
618             return 0;
619         }
620     }
621     return 1;
622 #elif defined(__NetBSD__)
623     struct scsi_addr addr;
624     if (ioctl(fd, SCIOCIDENTIFY, &addr) != -1)
625     {
626         switch (addr.type)
627         {
628         case TYPE_SCSI:
629             *port = 1;
630             *iface = addr.addr.scsi.scbus;
631             *device = addr.addr.scsi.target;
632             *lun = addr.addr.scsi.lun;
633             return 1;
634         case TYPE_ATAPI:
635             *port = 0;
636             *iface = addr.addr.atapi.atbus;
637             *device = addr.addr.atapi.drive;
638             *lun = 0;
639             return 1;
640         }
641     }
642     return 0;
643 #elif defined(__APPLE__)
644     dk_scsi_identify_t addr;
645     if (ioctl(fd, DKIOCSCSIIDENTIFY, &addr) != -1)
646     {
647        *port = addr.bus;
648        *iface = addr.port;
649        *device = addr.target;
650        *lun = addr.lun;
651        return 1;
652     }
653     return 0;
654 #else
655     FIXME("not implemented on this O/S\n");
656     return 0;
657 #endif
658 }
659
660
661 /******************************************************************
662  *              CDROM_Open
663  *
664  */
665 static NTSTATUS CDROM_Open(int fd, int* dev)
666 {
667     struct stat st;
668     NTSTATUS ret = STATUS_SUCCESS;
669     int         empty = -1;
670
671     fstat(fd, &st);
672
673     RtlEnterCriticalSection( &cache_section );
674     for (*dev = 0; *dev < MAX_CACHE_ENTRIES; (*dev)++)
675     {
676         if (empty == -1 &&
677             cdrom_cache[*dev].device == 0 &&
678             cdrom_cache[*dev].inode == 0)
679             empty = *dev;
680         else if (cdrom_cache[*dev].device == st.st_dev &&
681                  cdrom_cache[*dev].inode == st.st_ino)
682             break;
683     }
684     if (*dev == MAX_CACHE_ENTRIES)
685     {
686         if (empty == -1) ret = STATUS_NOT_IMPLEMENTED;
687         else
688         {
689             *dev = empty;
690             cdrom_cache[*dev].device  = st.st_dev;
691             cdrom_cache[*dev].inode   = st.st_ino;
692         }
693     }
694     RtlLeaveCriticalSection( &cache_section );
695
696     TRACE("%d, %d\n", *dev, fd);
697     return ret;
698 }
699
700 /******************************************************************
701  *              CDROM_GetStatusCode
702  *
703  *
704  */
705 static NTSTATUS CDROM_GetStatusCode(int io)
706 {
707     if (io == 0) return STATUS_SUCCESS;
708     return FILE_GetNtStatus();
709 }
710
711 /******************************************************************
712  *              CDROM_GetControl
713  *
714  */
715 static NTSTATUS CDROM_GetControl(int dev, int fd, CDROM_AUDIO_CONTROL* cac)
716 {
717 #ifdef __APPLE__
718     uint16_t speed;
719     int io = ioctl( fd, DKIOCCDGETSPEED, &speed );
720     if (io != 0) return CDROM_GetStatusCode( io );
721     /* DKIOCCDGETSPEED returns the speed in kilobytes per second,
722      * so convert to logical blocks (assumed to be ~2 KB).
723      */
724     cac->LogicalBlocksPerSecond = speed/2;
725 #else
726     cac->LogicalBlocksPerSecond = 1; /* FIXME */
727 #endif
728     cac->LbaFormat = 0; /* FIXME */
729     return  STATUS_NOT_SUPPORTED;
730 }
731
732 /******************************************************************
733  *              CDROM_GetDeviceNumber
734  *
735  */
736 static NTSTATUS CDROM_GetDeviceNumber(int dev, STORAGE_DEVICE_NUMBER* devnum)
737 {
738     FIXME( "stub\n" );
739     devnum->DeviceType = FILE_DEVICE_DISK;
740     devnum->DeviceNumber = 1;
741     devnum->PartitionNumber = 1;
742     return STATUS_SUCCESS;
743 }
744
745 /******************************************************************
746  *              CDROM_GetDriveGeometry
747  *
748  */
749 static NTSTATUS CDROM_GetDriveGeometry(int dev, int fd, DISK_GEOMETRY* dg)
750 {
751   CDROM_TOC     toc;
752   NTSTATUS      ret = 0;
753   int           fsize = 0;
754
755   if ((ret = CDROM_ReadTOC(dev, fd, &toc)) != 0) return ret;
756
757   fsize = FRAME_OF_TOC(toc, toc.LastTrack+1)
758         - FRAME_OF_TOC(toc, 1); /* Total size in frames */
759   
760   dg->Cylinders.u.LowPart = fsize / (64 * 32); 
761   dg->Cylinders.u.HighPart = 0; 
762   dg->MediaType = RemovableMedia;  
763   dg->TracksPerCylinder = 64; 
764   dg->SectorsPerTrack = 32;  
765   dg->BytesPerSector= 2048; 
766   return ret;
767 }
768
769 /******************************************************************
770  *              CDROM_GetMediaType
771  *
772  */
773 static NTSTATUS CDROM_GetMediaType(int dev, GET_MEDIA_TYPES* medtype)
774 {
775     FIXME(": faking success\n");
776     medtype->DeviceType = FILE_DEVICE_CD_ROM;
777     medtype->MediaInfoCount = 0;
778     return STATUS_SUCCESS;
779 }
780
781 /**************************************************************************
782  *                              CDROM_Reset                     [internal]
783  */
784 static NTSTATUS CDROM_ResetAudio(int fd)
785 {
786 #if defined(linux)
787     return CDROM_GetStatusCode(ioctl(fd, CDROMRESET));
788 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
789     return CDROM_GetStatusCode(ioctl(fd, CDIOCRESET, NULL));
790 #else
791     FIXME("not supported on this O/S\n");
792     return STATUS_NOT_SUPPORTED;
793 #endif
794 }
795
796 /******************************************************************
797  *              CDROM_SetTray
798  *
799  *
800  */
801 static NTSTATUS CDROM_SetTray(int fd, BOOL doEject)
802 {
803 #if defined(linux)
804     return CDROM_GetStatusCode(ioctl(fd, doEject ? CDROMEJECT : CDROMCLOSETRAY));
805 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
806     return CDROM_GetStatusCode((ioctl(fd, CDIOCALLOW, NULL)) ||
807                                (ioctl(fd, doEject ? CDIOCEJECT : CDIOCCLOSE, NULL)) ||
808                                (ioctl(fd, CDIOCPREVENT, NULL)));
809 #elif defined(__APPLE__)
810     if (doEject) return CDROM_GetStatusCode( ioctl( fd, DKIOCEJECT, NULL ) );
811     else return STATUS_NOT_SUPPORTED;
812 #else
813     FIXME("not supported on this O/S\n");
814     return STATUS_NOT_SUPPORTED;
815 #endif
816 }
817
818 /******************************************************************
819  *              CDROM_ControlEjection
820  *
821  *
822  */
823 static NTSTATUS CDROM_ControlEjection(int fd, const PREVENT_MEDIA_REMOVAL* rmv)
824 {
825 #if defined(linux)
826     return CDROM_GetStatusCode(ioctl(fd, CDROM_LOCKDOOR, rmv->PreventMediaRemoval));
827 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
828     return CDROM_GetStatusCode(ioctl(fd, (rmv->PreventMediaRemoval) ? CDIOCPREVENT : CDIOCALLOW, NULL));
829 #else
830     FIXME("not supported on this O/S\n");
831     return STATUS_NOT_SUPPORTED;
832 #endif
833 }
834
835 /******************************************************************
836  *              CDROM_ReadTOC
837  *
838  *
839  */
840 static NTSTATUS CDROM_ReadTOC(int dev, int fd, CDROM_TOC* toc)
841 {
842     NTSTATUS       ret = STATUS_NOT_SUPPORTED;
843
844     if (dev < 0 || dev >= MAX_CACHE_ENTRIES)
845         return STATUS_INVALID_PARAMETER;
846
847     RtlEnterCriticalSection( &cache_section );
848     if (cdrom_cache[dev].toc_good || !(ret = CDROM_SyncCache(dev, fd)))
849     {
850         *toc = cdrom_cache[dev].toc;
851         ret = STATUS_SUCCESS;
852     }
853     RtlLeaveCriticalSection( &cache_section );
854     return ret;
855 }
856
857 /******************************************************************
858  *              CDROM_GetDiskData
859  *
860  *
861  */
862 static NTSTATUS CDROM_GetDiskData(int dev, int fd, CDROM_DISK_DATA* data)
863 {
864     CDROM_TOC   toc;
865     NTSTATUS    ret;
866     int         i;
867
868     if ((ret = CDROM_ReadTOC(dev, fd, &toc)) != 0) return ret;
869     data->DiskData = 0;
870     for (i = toc.FirstTrack; i <= toc.LastTrack; i++) {
871         if (toc.TrackData[i-toc.FirstTrack].Control & 0x04)
872             data->DiskData |= CDROM_DISK_DATA_TRACK;
873         else
874             data->DiskData |= CDROM_DISK_AUDIO_TRACK;
875     }
876     return STATUS_SUCCESS;
877 }
878
879 /******************************************************************
880  *              CDROM_ReadQChannel
881  *
882  *
883  */
884 static NTSTATUS CDROM_ReadQChannel(int dev, int fd, const CDROM_SUB_Q_DATA_FORMAT* fmt,
885                                    SUB_Q_CHANNEL_DATA* data)
886 {
887     NTSTATUS            ret = STATUS_NOT_SUPPORTED;
888 #ifdef linux
889     SUB_Q_HEADER*       hdr = (SUB_Q_HEADER*)data;
890     int                 io;
891     struct cdrom_subchnl        sc;
892     sc.cdsc_format = CDROM_MSF;
893
894     io = ioctl(fd, CDROMSUBCHNL, &sc);
895     if (io == -1)
896     {
897         TRACE("opened or no_media (%s)!\n", strerror(errno));
898         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
899         CDROM_ClearCacheEntry(dev);
900         goto end;
901     }
902
903     hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
904
905     switch (sc.cdsc_audiostatus) {
906     case CDROM_AUDIO_INVALID:
907         CDROM_ClearCacheEntry(dev);
908         hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
909         break;
910     case CDROM_AUDIO_NO_STATUS:
911         CDROM_ClearCacheEntry(dev);
912         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
913         break;
914     case CDROM_AUDIO_PLAY:
915         hdr->AudioStatus = AUDIO_STATUS_IN_PROGRESS;
916         break;
917     case CDROM_AUDIO_PAUSED:
918         hdr->AudioStatus = AUDIO_STATUS_PAUSED;
919         break;
920     case CDROM_AUDIO_COMPLETED:
921         hdr->AudioStatus = AUDIO_STATUS_PLAY_COMPLETE;
922         break;
923     case CDROM_AUDIO_ERROR:
924         hdr->AudioStatus = AUDIO_STATUS_PLAY_ERROR;
925         break;
926     default:
927         TRACE("status=%02X !\n", sc.cdsc_audiostatus);
928         break;
929     }
930     switch (fmt->Format)
931     {
932     case IOCTL_CDROM_CURRENT_POSITION:
933         RtlEnterCriticalSection( &cache_section );
934         if (hdr->AudioStatus==AUDIO_STATUS_IN_PROGRESS) {
935           data->CurrentPosition.FormatCode = IOCTL_CDROM_CURRENT_POSITION;
936           data->CurrentPosition.Control = sc.cdsc_ctrl; 
937           data->CurrentPosition.ADR = sc.cdsc_adr; 
938           data->CurrentPosition.TrackNumber = sc.cdsc_trk; 
939           data->CurrentPosition.IndexNumber = sc.cdsc_ind; 
940
941           data->CurrentPosition.AbsoluteAddress[0] = 0; 
942           data->CurrentPosition.AbsoluteAddress[1] = sc.cdsc_absaddr.msf.minute; 
943           data->CurrentPosition.AbsoluteAddress[2] = sc.cdsc_absaddr.msf.second;
944           data->CurrentPosition.AbsoluteAddress[3] = sc.cdsc_absaddr.msf.frame;
945  
946           data->CurrentPosition.TrackRelativeAddress[0] = 0; 
947           data->CurrentPosition.TrackRelativeAddress[1] = sc.cdsc_reladdr.msf.minute; 
948           data->CurrentPosition.TrackRelativeAddress[2] = sc.cdsc_reladdr.msf.second;
949           data->CurrentPosition.TrackRelativeAddress[3] = sc.cdsc_reladdr.msf.frame;
950
951           cdrom_cache[dev].CurrentPosition = data->CurrentPosition;
952         }
953         else /* not playing */
954         {
955           cdrom_cache[dev].CurrentPosition.Header = *hdr; /* Preserve header info */
956           data->CurrentPosition = cdrom_cache[dev].CurrentPosition;
957         }
958         RtlLeaveCriticalSection( &cache_section );
959         break;
960     case IOCTL_CDROM_MEDIA_CATALOG:
961         data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
962         {
963             struct cdrom_mcn mcn;
964             if ((io = ioctl(fd, CDROM_GET_MCN, &mcn)) == -1) goto end;
965
966             data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
967             data->MediaCatalog.Mcval = 0; /* FIXME */
968             memcpy(data->MediaCatalog.MediaCatalog, mcn.medium_catalog_number, 14);
969             data->MediaCatalog.MediaCatalog[14] = 0;
970         }
971         break;
972     case IOCTL_CDROM_TRACK_ISRC:
973         FIXME("TrackIsrc: NIY on linux\n");
974         data->TrackIsrc.FormatCode = IOCTL_CDROM_TRACK_ISRC;
975         data->TrackIsrc.Tcval = 0;
976         io = 0;
977         break;
978     }
979
980  end:
981     ret = CDROM_GetStatusCode(io);
982 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
983     SUB_Q_HEADER*       hdr = (SUB_Q_HEADER*)data;
984     int                 io;
985     struct ioc_read_subchannel  read_sc;
986     struct cd_sub_channel_info  sc;
987
988     read_sc.address_format = CD_MSF_FORMAT;
989     read_sc.track          = 0;
990     read_sc.data_len       = sizeof(sc);
991     read_sc.data           = &sc;
992     switch (fmt->Format)
993     {
994     case IOCTL_CDROM_CURRENT_POSITION:
995         read_sc.data_format    = CD_CURRENT_POSITION;
996         break;
997     case IOCTL_CDROM_MEDIA_CATALOG:
998         read_sc.data_format    = CD_MEDIA_CATALOG;
999         break;
1000     case IOCTL_CDROM_TRACK_ISRC:
1001         read_sc.data_format    = CD_TRACK_INFO;
1002         sc.what.track_info.track_number = data->TrackIsrc.Track;
1003         break;
1004     }
1005     io = ioctl(fd, CDIOCREADSUBCHANNEL, &read_sc);
1006     if (io == -1)
1007     {
1008         TRACE("opened or no_media (%s)!\n", strerror(errno));
1009         CDROM_ClearCacheEntry(dev);
1010         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
1011         goto end;
1012     }
1013
1014     hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
1015
1016     switch (sc.header.audio_status) {
1017     case CD_AS_AUDIO_INVALID:
1018         CDROM_ClearCacheEntry(dev);
1019         hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
1020         break;
1021     case CD_AS_NO_STATUS:
1022         CDROM_ClearCacheEntry(dev);
1023         hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
1024         break;
1025     case CD_AS_PLAY_IN_PROGRESS:
1026         hdr->AudioStatus = AUDIO_STATUS_IN_PROGRESS;
1027         break;
1028     case CD_AS_PLAY_PAUSED:
1029         hdr->AudioStatus = AUDIO_STATUS_PAUSED;
1030         break;
1031     case CD_AS_PLAY_COMPLETED:
1032         hdr->AudioStatus = AUDIO_STATUS_PLAY_COMPLETE;
1033         break;
1034     case CD_AS_PLAY_ERROR:
1035         hdr->AudioStatus = AUDIO_STATUS_PLAY_ERROR;
1036         break;
1037     default:
1038         TRACE("status=%02X !\n", sc.header.audio_status);
1039     }
1040     switch (fmt->Format)
1041     {
1042     case IOCTL_CDROM_CURRENT_POSITION:
1043         RtlEnterCriticalSection( &cache_section );
1044         if (hdr->AudioStatus==AUDIO_STATUS_IN_PROGRESS) {
1045           data->CurrentPosition.FormatCode = IOCTL_CDROM_CURRENT_POSITION;
1046           data->CurrentPosition.Control = sc.what.position.control;
1047           data->CurrentPosition.ADR = sc.what.position.addr_type;
1048           data->CurrentPosition.TrackNumber = sc.what.position.track_number;
1049           data->CurrentPosition.IndexNumber = sc.what.position.index_number;
1050
1051           data->CurrentPosition.AbsoluteAddress[0] = 0;
1052           data->CurrentPosition.AbsoluteAddress[1] = sc.what.position.absaddr.msf.minute;
1053           data->CurrentPosition.AbsoluteAddress[2] = sc.what.position.absaddr.msf.second;
1054           data->CurrentPosition.AbsoluteAddress[3] = sc.what.position.absaddr.msf.frame;
1055           data->CurrentPosition.TrackRelativeAddress[0] = 0;
1056           data->CurrentPosition.TrackRelativeAddress[1] = sc.what.position.reladdr.msf.minute;
1057           data->CurrentPosition.TrackRelativeAddress[2] = sc.what.position.reladdr.msf.second;
1058           data->CurrentPosition.TrackRelativeAddress[3] = sc.what.position.reladdr.msf.frame;
1059           cdrom_cache[dev].CurrentPosition = data->CurrentPosition;
1060         }
1061         else { /* not playing */
1062           cdrom_cache[dev].CurrentPosition.Header = *hdr; /* Preserve header info */
1063           data->CurrentPosition = cdrom_cache[dev].CurrentPosition;
1064         }
1065         RtlLeaveCriticalSection( &cache_section );
1066         break;
1067     case IOCTL_CDROM_MEDIA_CATALOG:
1068         data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
1069         data->MediaCatalog.Mcval = sc.what.media_catalog.mc_valid;
1070         memcpy(data->MediaCatalog.MediaCatalog, sc.what.media_catalog.mc_number, 15);
1071         break;
1072     case IOCTL_CDROM_TRACK_ISRC:
1073         data->TrackIsrc.FormatCode = IOCTL_CDROM_TRACK_ISRC;
1074         data->TrackIsrc.Tcval = sc.what.track_info.ti_valid;
1075         memcpy(data->TrackIsrc.TrackIsrc, sc.what.track_info.ti_number, 15);
1076         break;
1077     }
1078
1079  end:
1080     ret = CDROM_GetStatusCode(io);
1081 #elif defined(__APPLE__)
1082     SUB_Q_HEADER* hdr = (SUB_Q_HEADER*)data;
1083     int io = 0;
1084     union
1085     {
1086         dk_cd_read_mcn_t mcn;
1087         dk_cd_read_isrc_t isrc;
1088     } ioc;
1089     /* We need IOCDAudioControl for IOCTL_CDROM_CURRENT_POSITION */
1090     if (fmt->Format == IOCTL_CDROM_CURRENT_POSITION)
1091     {
1092         FIXME("NIY\n");
1093         return STATUS_NOT_SUPPORTED;
1094     }
1095     /* No IOCDAudioControl support; just set the audio status to none */
1096     hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
1097     switch(fmt->Format)
1098     {
1099     case IOCTL_CDROM_MEDIA_CATALOG:
1100         if ((io = ioctl(fd, DKIOCCDREADMCN, &ioc.mcn)) == -1) break;
1101         memcpy(data->MediaCatalog.MediaCatalog, ioc.mcn.mcn, kCDMCNMaxLength);
1102         data->MediaCatalog.Mcval = 1;
1103         break;
1104     case IOCTL_CDROM_TRACK_ISRC:
1105         ioc.isrc.track = fmt->Track;
1106         if ((io = ioctl(fd, DKIOCCDREADISRC, &ioc.isrc)) == -1) break;
1107         memcpy(data->TrackIsrc.TrackIsrc, ioc.isrc.isrc, kCDISRCMaxLength);
1108         data->TrackIsrc.Tcval = 1;
1109         data->TrackIsrc.Track = ioc.isrc.track;
1110     }
1111     ret = CDROM_GetStatusCode(io);
1112 #endif
1113     return ret;
1114 }
1115
1116 /******************************************************************
1117  *              CDROM_Verify
1118  *  Implements: IOCTL_STORAGE_CHECK_VERIFY
1119  *              IOCTL_CDROM_CHECK_VERIFY
1120  *              IOCTL_DISK_CHECK_VERIFY
1121  *
1122  */
1123 static NTSTATUS CDROM_Verify(int dev, int fd)
1124 {
1125 #if defined(linux)
1126     int ret;
1127
1128     ret = ioctl(fd,  CDROM_DRIVE_STATUS, NULL);
1129     if(ret == -1) {
1130         TRACE("ioctl CDROM_DRIVE_STATUS failed(%s)!\n", strerror(errno));
1131         return CDROM_GetStatusCode(ret);
1132     }
1133
1134     if(ret == CDS_DISC_OK)
1135         return STATUS_SUCCESS;
1136     else
1137         return STATUS_NO_MEDIA_IN_DEVICE;
1138 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1139     int ret;
1140     ret = ioctl(fd, CDIOCSTART, NULL);
1141     if(ret == 0)
1142         return STATUS_SUCCESS;
1143     else
1144         return STATUS_NO_MEDIA_IN_DEVICE;
1145 #elif defined(__APPLE__)
1146         /* At this point, we know that we have media, because in Mac OS X, the
1147          * device file is only created when media is present. */
1148         return STATUS_SUCCESS;
1149 #else
1150     FIXME("not supported on this O/S\n");
1151     return STATUS_NOT_SUPPORTED;
1152 #endif
1153 }
1154
1155 /******************************************************************
1156  *              CDROM_PlayAudioMSF
1157  *
1158  *
1159  */
1160 static NTSTATUS CDROM_PlayAudioMSF(int fd, const CDROM_PLAY_AUDIO_MSF* audio_msf)
1161 {
1162     NTSTATUS       ret = STATUS_NOT_SUPPORTED;
1163 #ifdef linux
1164     struct      cdrom_msf       msf;
1165     int         io;
1166
1167     msf.cdmsf_min0   = audio_msf->StartingM;
1168     msf.cdmsf_sec0   = audio_msf->StartingS;
1169     msf.cdmsf_frame0 = audio_msf->StartingF;
1170     msf.cdmsf_min1   = audio_msf->EndingM;
1171     msf.cdmsf_sec1   = audio_msf->EndingS;
1172     msf.cdmsf_frame1 = audio_msf->EndingF;
1173
1174     io = ioctl(fd, CDROMSTART);
1175     if (io == -1)
1176     {
1177         WARN("motor doesn't start !\n");
1178         goto end;
1179     }
1180     io = ioctl(fd, CDROMPLAYMSF, &msf);
1181     if (io == -1)
1182     {
1183         WARN("device doesn't play !\n");
1184         goto end;
1185     }
1186     TRACE("msf = %d:%d:%d %d:%d:%d\n",
1187           msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0,
1188           msf.cdmsf_min1, msf.cdmsf_sec1, msf.cdmsf_frame1);
1189  end:
1190     ret = CDROM_GetStatusCode(io);
1191 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1192     struct      ioc_play_msf    msf;
1193     int         io;
1194
1195     msf.start_m      = audio_msf->StartingM;
1196     msf.start_s      = audio_msf->StartingS;
1197     msf.start_f      = audio_msf->StartingF;
1198     msf.end_m        = audio_msf->EndingM;
1199     msf.end_s        = audio_msf->EndingS;
1200     msf.end_f        = audio_msf->EndingF;
1201
1202     io = ioctl(fd, CDIOCSTART, NULL);
1203     if (io == -1)
1204     {
1205         WARN("motor doesn't start !\n");
1206         goto end;
1207     }
1208     io = ioctl(fd, CDIOCPLAYMSF, &msf);
1209     if (io == -1)
1210     {
1211         WARN("device doesn't play !\n");
1212         goto end;
1213     }
1214     TRACE("msf = %d:%d:%d %d:%d:%d\n",
1215           msf.start_m, msf.start_s, msf.start_f,
1216           msf.end_m,   msf.end_s,   msf.end_f);
1217 end:
1218     ret = CDROM_GetStatusCode(io);
1219 #endif
1220     return ret;
1221 }
1222
1223 /******************************************************************
1224  *              CDROM_SeekAudioMSF
1225  *
1226  *
1227  */
1228 static NTSTATUS CDROM_SeekAudioMSF(int dev, int fd, const CDROM_SEEK_AUDIO_MSF* audio_msf)
1229 {
1230     CDROM_TOC toc;
1231     int i, io, frame;
1232     SUB_Q_CURRENT_POSITION *cp;
1233 #if defined(linux)
1234     struct cdrom_msf0   msf;
1235     struct cdrom_subchnl sc;
1236 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1237     struct ioc_play_msf msf;
1238     struct ioc_read_subchannel  read_sc;
1239     struct cd_sub_channel_info  sc;
1240     int final_frame;
1241 #endif
1242
1243     /* Use the information on the TOC to compute the new current
1244      * position, which is shadowed on the cache. [Portable]. */
1245     frame = FRAME_OF_MSF(*audio_msf);
1246
1247     if ((io = CDROM_ReadTOC(dev, fd, &toc)) != 0) return io;
1248
1249     for(i=toc.FirstTrack;i<=toc.LastTrack+1;i++)
1250       if (FRAME_OF_TOC(toc,i)>frame) break;
1251     if (i <= toc.FirstTrack || i > toc.LastTrack+1)
1252       return STATUS_INVALID_PARAMETER;
1253     i--;
1254     RtlEnterCriticalSection( &cache_section );
1255     cp = &cdrom_cache[dev].CurrentPosition;
1256     cp->FormatCode = IOCTL_CDROM_CURRENT_POSITION; 
1257     cp->Control = toc.TrackData[i-toc.FirstTrack].Control; 
1258     cp->ADR = toc.TrackData[i-toc.FirstTrack].Adr; 
1259     cp->TrackNumber = toc.TrackData[i-toc.FirstTrack].TrackNumber;
1260     cp->IndexNumber = 0; /* FIXME: where do they keep these? */
1261     cp->AbsoluteAddress[0] = 0; 
1262     cp->AbsoluteAddress[1] = toc.TrackData[i-toc.FirstTrack].Address[1];
1263     cp->AbsoluteAddress[2] = toc.TrackData[i-toc.FirstTrack].Address[2];
1264     cp->AbsoluteAddress[3] = toc.TrackData[i-toc.FirstTrack].Address[3];
1265     frame -= FRAME_OF_TOC(toc,i);
1266     cp->TrackRelativeAddress[0] = 0;
1267     MSF_OF_FRAME(cp->TrackRelativeAddress[1], frame); 
1268     RtlLeaveCriticalSection( &cache_section );
1269
1270     /* If playing, then issue a seek command, otherwise do nothing */
1271 #ifdef linux
1272     sc.cdsc_format = CDROM_MSF;
1273
1274     io = ioctl(fd, CDROMSUBCHNL, &sc);
1275     if (io == -1)
1276     {
1277         TRACE("opened or no_media (%s)!\n", strerror(errno));
1278         CDROM_ClearCacheEntry(dev);
1279         return CDROM_GetStatusCode(io);
1280     }
1281     if (sc.cdsc_audiostatus==CDROM_AUDIO_PLAY)
1282     {
1283       msf.minute = audio_msf->M;
1284       msf.second = audio_msf->S;
1285       msf.frame  = audio_msf->F;
1286       return CDROM_GetStatusCode(ioctl(fd, CDROMSEEK, &msf));
1287     }
1288     return STATUS_SUCCESS;
1289 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1290     read_sc.address_format = CD_MSF_FORMAT;
1291     read_sc.track          = 0;
1292     read_sc.data_len       = sizeof(sc);
1293     read_sc.data           = &sc;
1294     read_sc.data_format    = CD_CURRENT_POSITION;
1295
1296     io = ioctl(fd, CDIOCREADSUBCHANNEL, &read_sc);
1297     if (io == -1)
1298     {
1299         TRACE("opened or no_media (%s)!\n", strerror(errno));
1300         CDROM_ClearCacheEntry(dev);
1301         return CDROM_GetStatusCode(io);
1302     }
1303     if (sc.header.audio_status==CD_AS_PLAY_IN_PROGRESS) 
1304     {
1305
1306       msf.start_m      = audio_msf->M;
1307       msf.start_s      = audio_msf->S;
1308       msf.start_f      = audio_msf->F;
1309       final_frame = FRAME_OF_TOC(toc,toc.LastTrack+1)-1;
1310       MSF_OF_FRAME(msf.end_m, final_frame);
1311
1312       return CDROM_GetStatusCode(ioctl(fd, CDIOCPLAYMSF, &msf));
1313     }
1314     return STATUS_SUCCESS;
1315 #else
1316     FIXME("not supported on this O/S\n");
1317     return STATUS_NOT_SUPPORTED;
1318 #endif
1319 }
1320
1321 /******************************************************************
1322  *              CDROM_PauseAudio
1323  *
1324  *
1325  */
1326 static NTSTATUS CDROM_PauseAudio(int fd)
1327 {
1328 #if defined(linux)
1329     return CDROM_GetStatusCode(ioctl(fd, CDROMPAUSE));
1330 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1331     return CDROM_GetStatusCode(ioctl(fd, CDIOCPAUSE, NULL));
1332 #else
1333     FIXME(": not supported on this O/S\n");
1334     return STATUS_NOT_SUPPORTED;
1335 #endif
1336 }
1337
1338 /******************************************************************
1339  *              CDROM_ResumeAudio
1340  *
1341  *
1342  */
1343 static NTSTATUS CDROM_ResumeAudio(int fd)
1344 {
1345 #if defined(linux)
1346     return CDROM_GetStatusCode(ioctl(fd, CDROMRESUME));
1347 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1348     return CDROM_GetStatusCode(ioctl(fd, CDIOCRESUME, NULL));
1349 #else
1350     FIXME("not supported on this O/S\n");
1351     return STATUS_NOT_SUPPORTED;
1352 #endif
1353 }
1354
1355 /******************************************************************
1356  *              CDROM_StopAudio
1357  *
1358  *
1359  */
1360 static NTSTATUS CDROM_StopAudio(int fd)
1361 {
1362 #if defined(linux)
1363     return CDROM_GetStatusCode(ioctl(fd, CDROMSTOP));
1364 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1365     return CDROM_GetStatusCode(ioctl(fd, CDIOCSTOP, NULL));
1366 #else
1367     FIXME("not supported on this O/S\n");
1368     return STATUS_NOT_SUPPORTED;
1369 #endif
1370 }
1371
1372 /******************************************************************
1373  *              CDROM_GetVolume
1374  *
1375  *
1376  */
1377 static NTSTATUS CDROM_GetVolume(int fd, VOLUME_CONTROL* vc)
1378 {
1379 #if defined(linux)
1380     struct cdrom_volctrl volc;
1381     int io;
1382
1383     io = ioctl(fd, CDROMVOLREAD, &volc);
1384     if (io != -1)
1385     {
1386         vc->PortVolume[0] = volc.channel0;
1387         vc->PortVolume[1] = volc.channel1;
1388         vc->PortVolume[2] = volc.channel2;
1389         vc->PortVolume[3] = volc.channel3;
1390     }
1391     return CDROM_GetStatusCode(io);
1392 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1393     struct  ioc_vol     volc;
1394     int io;
1395
1396     io = ioctl(fd, CDIOCGETVOL, &volc);
1397     if (io != -1)
1398     {
1399         vc->PortVolume[0] = volc.vol[0];
1400         vc->PortVolume[1] = volc.vol[1];
1401         vc->PortVolume[2] = volc.vol[2];
1402         vc->PortVolume[3] = volc.vol[3];
1403     }
1404     return CDROM_GetStatusCode(io);
1405 #else
1406     FIXME("not supported on this O/S\n");
1407     return STATUS_NOT_SUPPORTED;
1408 #endif
1409 }
1410
1411 /******************************************************************
1412  *              CDROM_SetVolume
1413  *
1414  *
1415  */
1416 static NTSTATUS CDROM_SetVolume(int fd, const VOLUME_CONTROL* vc)
1417 {
1418 #if defined(linux)
1419     struct cdrom_volctrl volc;
1420
1421     volc.channel0 = vc->PortVolume[0];
1422     volc.channel1 = vc->PortVolume[1];
1423     volc.channel2 = vc->PortVolume[2];
1424     volc.channel3 = vc->PortVolume[3];
1425
1426     return CDROM_GetStatusCode(ioctl(fd, CDROMVOLCTRL, &volc));
1427 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1428     struct  ioc_vol     volc;
1429
1430     volc.vol[0] = vc->PortVolume[0];
1431     volc.vol[1] = vc->PortVolume[1];
1432     volc.vol[2] = vc->PortVolume[2];
1433     volc.vol[3] = vc->PortVolume[3];
1434
1435     return CDROM_GetStatusCode(ioctl(fd, CDIOCSETVOL, &volc));
1436 #else
1437     FIXME(": not supported on this O/S\n");
1438     return STATUS_NOT_SUPPORTED;
1439 #endif
1440 }
1441
1442 /******************************************************************
1443  *              CDROM_RawRead
1444  *
1445  * Some features of this IOCTL are rather poorly documented and
1446  * not really intuitive either:
1447  *
1448  *   1. Although the DiskOffset parameter is meant to be a
1449  *      byte offset into the disk, it is in fact the sector
1450  *      number multiplied by 2048 regardless of the actual
1451  *      sector size.
1452  *
1453  *   2. The least significant 11 bits of DiskOffset are ignored.
1454  *
1455  *   3. The TrackMode parameter has no effect on the sector
1456  *      size. The entire raw sector (i.e. 2352 bytes of data)
1457  *      is always returned. IMO the TrackMode is only used
1458  *      to check the correct sector type.
1459  *
1460  */
1461 static NTSTATUS CDROM_RawRead(int fd, const RAW_READ_INFO* raw, void* buffer, DWORD len, DWORD* sz)
1462 {
1463     int         ret = STATUS_NOT_SUPPORTED;
1464     int         io = -1;
1465 #ifdef __APPLE__
1466     dk_cd_read_t cdrd;
1467 #endif
1468
1469     TRACE("RAW_READ_INFO: DiskOffset=%i,%i SectorCount=%i TrackMode=%i\n buffer=%p len=%i sz=%p\n",
1470           raw->DiskOffset.u.HighPart, raw->DiskOffset.u.LowPart, raw->SectorCount, raw->TrackMode, buffer, len, sz);
1471
1472     if (len < raw->SectorCount * 2352) return STATUS_BUFFER_TOO_SMALL;
1473
1474 #if defined(linux)
1475     if (raw->DiskOffset.u.HighPart & ~2047) {
1476         WARN("DiskOffset points to a sector >= 2**32\n");
1477         return ret;
1478     }
1479
1480     switch (raw->TrackMode)
1481     {
1482     case YellowMode2:
1483     case XAForm2:
1484     {
1485         DWORD lba = raw->DiskOffset.QuadPart >> 11;
1486         struct cdrom_msf*       msf;
1487         PBYTE                   *bp; /* current buffer pointer */
1488         DWORD i;
1489
1490         if ((lba + raw->SectorCount) >
1491             ((1 << 8*sizeof(msf->cdmsf_min0)) * CD_SECS * CD_FRAMES
1492              - CD_MSF_OFFSET)) {
1493             WARN("DiskOffset not accessible with MSF\n");
1494             return ret;
1495         }
1496
1497         /* Linux reads only one sector at a time.
1498          * ioctl CDROMREADRAW takes struct cdrom_msf as an argument
1499          * on the contrary to what header comments state.
1500          */
1501         lba += CD_MSF_OFFSET;
1502         for (i = 0, bp = buffer; i < raw->SectorCount;
1503              i++, lba++, bp += 2352)
1504         {
1505             msf = (struct cdrom_msf*)bp;
1506             msf->cdmsf_min0   = lba / CD_FRAMES / CD_SECS;
1507             msf->cdmsf_sec0   = lba / CD_FRAMES % CD_SECS;
1508             msf->cdmsf_frame0 = lba % CD_FRAMES;
1509             io = ioctl(fd, CDROMREADRAW, msf);
1510             if (io != 0)
1511             {
1512                 *sz = 2352 * i;
1513                 return CDROM_GetStatusCode(io);
1514             }
1515         }
1516         break;
1517     }
1518
1519     case CDDA:
1520     {
1521         struct cdrom_read_audio cdra;
1522
1523         cdra.addr.lba = raw->DiskOffset.QuadPart >> 11;
1524         TRACE("reading at %u\n", cdra.addr.lba);
1525         cdra.addr_format = CDROM_LBA;
1526         cdra.nframes = raw->SectorCount;
1527         cdra.buf = buffer;
1528         io = ioctl(fd, CDROMREADAUDIO, &cdra);
1529         break;
1530     }
1531
1532     default:
1533         FIXME("NIY: %d\n", raw->TrackMode);
1534         return STATUS_INVALID_PARAMETER;
1535     }
1536 #elif defined(__APPLE__)
1537     /* Mac OS lets us read multiple parts of the sector at a time.
1538      * We can read all the sectors in at once, unlike Linux.
1539      */
1540     memset(&cdrd, 0, sizeof(cdrd));
1541     cdrd.offset = (raw->DiskOffset.QuadPart >> 11) * kCDSectorSizeWhole;
1542     cdrd.buffer = buffer;
1543     cdrd.bufferLength = raw->SectorCount * kCDSectorSizeWhole;
1544     switch (raw->TrackMode)
1545     {
1546     case YellowMode2:
1547         cdrd.sectorType = kCDSectorTypeMode2;
1548         cdrd.sectorArea = kCDSectorAreaSync | kCDSectorAreaHeader | kCDSectorAreaUser;
1549         break;
1550
1551     case XAForm2:
1552         cdrd.sectorType = kCDSectorTypeMode2Form2;
1553         cdrd.sectorArea = kCDSectorAreaSync | kCDSectorAreaHeader | kCDSectorAreaSubHeader | kCDSectorAreaUser;
1554         break;
1555
1556     case CDDA:
1557         cdrd.sectorType = kCDSectorTypeCDDA;
1558         cdrd.sectorArea = kCDSectorAreaUser;
1559         break;
1560
1561     default:
1562         FIXME("NIY: %d\n", raw->TrackMode);
1563         return STATUS_INVALID_PARAMETER;
1564     }
1565     io = ioctl(fd, DKIOCCDREAD, &cdrd);
1566     if (io != 0)
1567     {
1568         *sz = cdrd.bufferLength;
1569         return CDROM_GetStatusCode(io);
1570     }
1571 #else
1572     switch (raw->TrackMode)
1573     {
1574     case YellowMode2:
1575         FIXME("YellowMode2: NIY\n");
1576         return ret;
1577     case XAForm2:
1578         FIXME("XAForm2: NIY\n");
1579         return ret;
1580     case CDDA:
1581         FIXME("CDDA: NIY\n");
1582         return ret;
1583     default:
1584         FIXME("NIY: %d\n", raw->TrackMode);
1585         return STATUS_INVALID_PARAMETER;
1586     }
1587 #endif
1588
1589     *sz = 2352 * raw->SectorCount;
1590     ret = CDROM_GetStatusCode(io);
1591     return ret;
1592 }
1593
1594 /******************************************************************
1595  *        CDROM_ScsiPassThroughDirect
1596  *        Implements IOCTL_SCSI_PASS_THROUGH_DIRECT
1597  *
1598  */
1599 static NTSTATUS CDROM_ScsiPassThroughDirect(int fd, PSCSI_PASS_THROUGH_DIRECT pPacket)
1600 {
1601     int ret = STATUS_NOT_SUPPORTED;
1602 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1603     sg_io_hdr_t cmd;
1604     int io;
1605 #elif defined HAVE_SCSIREQ_T_CMD
1606     scsireq_t cmd;
1607     int io;
1608 #elif defined __APPLE__
1609     dk_scsi_command_t cmd;
1610     int io;
1611 #endif
1612
1613     if (pPacket->Length < sizeof(SCSI_PASS_THROUGH_DIRECT))
1614         return STATUS_BUFFER_TOO_SMALL;
1615
1616     if (pPacket->CdbLength > 16)
1617         return STATUS_INVALID_PARAMETER;
1618
1619 #ifdef SENSEBUFLEN
1620     if (pPacket->SenseInfoLength > SENSEBUFLEN)
1621         return STATUS_INVALID_PARAMETER;
1622 #elif defined HAVE_REQUEST_SENSE
1623     if (pPacket->SenseInfoLength > sizeof(struct request_sense))
1624         return STATUS_INVALID_PARAMETER;
1625 #endif
1626
1627     if (pPacket->DataTransferLength > 0 && !pPacket->DataBuffer)
1628         return STATUS_INVALID_PARAMETER;
1629
1630 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1631     RtlZeroMemory(&cmd, sizeof(cmd));
1632
1633     cmd.interface_id   = 'S';
1634     cmd.cmd_len        = pPacket->CdbLength;
1635     cmd.mx_sb_len      = pPacket->SenseInfoLength;
1636     cmd.dxfer_len      = pPacket->DataTransferLength;
1637     cmd.dxferp         = pPacket->DataBuffer;
1638     cmd.cmdp           = pPacket->Cdb;
1639     cmd.sbp            = (unsigned char*)pPacket + pPacket->SenseInfoOffset;
1640     cmd.timeout        = pPacket->TimeOutValue*1000;
1641
1642     switch (pPacket->DataIn)
1643     {
1644     case SCSI_IOCTL_DATA_IN:
1645         cmd.dxfer_direction = SG_DXFER_FROM_DEV;
1646         break;
1647     case SCSI_IOCTL_DATA_OUT:
1648         cmd.dxfer_direction = SG_DXFER_TO_DEV;
1649         break;
1650     case SCSI_IOCTL_DATA_UNSPECIFIED:
1651         cmd.dxfer_direction = SG_DXFER_NONE;
1652         break;
1653     default:
1654        return STATUS_INVALID_PARAMETER;
1655     }
1656
1657     io = ioctl(fd, SG_IO, &cmd);
1658
1659     pPacket->ScsiStatus         = cmd.status;
1660     pPacket->DataTransferLength = cmd.resid;
1661     pPacket->SenseInfoLength    = cmd.sb_len_wr;
1662
1663     ret = CDROM_GetStatusCode(io);
1664
1665 #elif defined HAVE_SCSIREQ_T_CMD
1666
1667     memset(&cmd, 0, sizeof(cmd));
1668     memcpy(&(cmd.cmd), &(pPacket->Cdb), pPacket->CdbLength);
1669
1670     cmd.cmdlen         = pPacket->CdbLength;
1671     cmd.databuf        = pPacket->DataBuffer;
1672     cmd.datalen        = pPacket->DataTransferLength;
1673     cmd.senselen       = pPacket->SenseInfoLength;
1674     cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */
1675
1676     switch (pPacket->DataIn)
1677     {
1678     case SCSI_IOCTL_DATA_OUT:
1679         cmd.flags |= SCCMD_WRITE;
1680         break;
1681     case SCSI_IOCTL_DATA_IN:
1682         cmd.flags |= SCCMD_READ;
1683         break;
1684     case SCSI_IOCTL_DATA_UNSPECIFIED:
1685         cmd.flags = 0;
1686         break;
1687     default:
1688        return STATUS_INVALID_PARAMETER;
1689     }
1690
1691     io = ioctl(fd, SCIOCCOMMAND, &cmd);
1692
1693     switch (cmd.retsts)
1694     {
1695     case SCCMD_OK:         break;
1696     case SCCMD_TIMEOUT:    return STATUS_TIMEOUT;
1697                            break;
1698     case SCCMD_BUSY:       return STATUS_DEVICE_BUSY;
1699                            break;
1700     case SCCMD_SENSE:      break;
1701     case SCCMD_UNKNOWN:    return STATUS_UNSUCCESSFUL;
1702                            break;
1703     }
1704
1705     if (pPacket->SenseInfoLength != 0)
1706     {
1707         memcpy((char*)pPacket + pPacket->SenseInfoOffset,
1708                cmd.sense, pPacket->SenseInfoLength);
1709     }
1710
1711     pPacket->ScsiStatus = cmd.status;
1712
1713     ret = CDROM_GetStatusCode(io);
1714
1715 #elif defined(__APPLE__)
1716
1717     memset(&cmd, 0, sizeof(cmd));
1718     memcpy(cmd.cdb, pPacket->Cdb, pPacket->CdbLength);
1719
1720     cmd.cdbSize        = pPacket->CdbLength;
1721     cmd.buffer         = pPacket->DataBuffer;
1722     cmd.bufferSize     = pPacket->DataTransferLength;
1723     cmd.sense          = (char*)pPacket + pPacket->SenseInfoOffset;
1724     cmd.senseLen       = pPacket->SenseInfoLength;
1725     cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */
1726
1727     switch (pPacket->DataIn)
1728     {
1729     case SCSI_IOCTL_DATA_OUT:
1730         cmd.direction = kSCSIDataTransfer_FromInitiatorToTarget;
1731         break;
1732     case SCSI_IOCTL_DATA_IN:
1733         cmd.direction = kSCSIDataTransfer_FromTargetToInitiator;
1734         break;
1735     case SCSI_IOCTL_DATA_UNSPECIFIED:
1736         cmd.direction = kSCSIDataTransfer_NoDataTransfer;
1737         break;
1738     default:
1739        return STATUS_INVALID_PARAMETER;
1740     }
1741
1742     io = ioctl(fd, DKIOCSCSICOMMAND, &cmd);
1743
1744     if (cmd.response == kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE)
1745     {
1746         /* Command failed */
1747         switch (cmd.status)
1748         {
1749         case kSCSITaskStatus_TaskTimeoutOccurred:     return STATUS_TIMEOUT;
1750                                                       break;
1751         case kSCSITaskStatus_ProtocolTimeoutOccurred: return STATUS_IO_TIMEOUT;
1752                                                       break;
1753         case kSCSITaskStatus_DeviceNotResponding:     return STATUS_DEVICE_BUSY;
1754                                                       break;
1755         case kSCSITaskStatus_DeviceNotPresent:
1756             return STATUS_NO_SUCH_DEVICE;
1757             break;
1758         case kSCSITaskStatus_DeliveryFailure:
1759             return STATUS_DEVICE_PROTOCOL_ERROR;
1760             break;
1761         case kSCSITaskStatus_No_Status:
1762         default:
1763             return STATUS_UNSUCCESSFUL;
1764             break;
1765         }
1766     }
1767
1768     if (cmd.status != kSCSITaskStatus_No_Status)
1769         pPacket->ScsiStatus = cmd.status;
1770
1771     ret = CDROM_GetStatusCode(io);
1772 #endif
1773     return ret;
1774 }
1775
1776 /******************************************************************
1777  *              CDROM_ScsiPassThrough
1778  *              Implements IOCTL_SCSI_PASS_THROUGH
1779  *
1780  */
1781 static NTSTATUS CDROM_ScsiPassThrough(int fd, PSCSI_PASS_THROUGH pPacket)
1782 {
1783     int ret = STATUS_NOT_SUPPORTED;
1784 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1785     sg_io_hdr_t cmd;
1786     int io;
1787 #elif defined HAVE_SCSIREQ_T_CMD
1788     scsireq_t cmd;
1789     int io;
1790 #elif defined __APPLE__
1791     dk_scsi_command_t cmd;
1792     int io;
1793 #endif
1794
1795     if (pPacket->Length < sizeof(SCSI_PASS_THROUGH))
1796         return STATUS_BUFFER_TOO_SMALL;
1797
1798     if (pPacket->CdbLength > 16)
1799         return STATUS_INVALID_PARAMETER;
1800
1801 #ifdef SENSEBUFLEN
1802     if (pPacket->SenseInfoLength > SENSEBUFLEN)
1803         return STATUS_INVALID_PARAMETER;
1804 #elif defined HAVE_REQUEST_SENSE
1805     if (pPacket->SenseInfoLength > sizeof(struct request_sense))
1806         return STATUS_INVALID_PARAMETER;
1807 #endif
1808
1809     if (pPacket->DataTransferLength > 0 && pPacket->DataBufferOffset < sizeof(SCSI_PASS_THROUGH))
1810         return STATUS_INVALID_PARAMETER;
1811
1812 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1813     RtlZeroMemory(&cmd, sizeof(cmd));
1814
1815     cmd.interface_id   = 'S';
1816     cmd.dxfer_len      = pPacket->DataTransferLength;
1817     cmd.dxferp         = (char*)pPacket + pPacket->DataBufferOffset;
1818     cmd.cmd_len        = pPacket->CdbLength;
1819     cmd.cmdp           = pPacket->Cdb;
1820     cmd.mx_sb_len      = pPacket->SenseInfoLength;
1821     cmd.timeout        = pPacket->TimeOutValue*1000;
1822
1823     if(cmd.mx_sb_len > 0)
1824         cmd.sbp = (unsigned char*)pPacket + pPacket->SenseInfoOffset;
1825
1826     switch (pPacket->DataIn)
1827     {
1828     case SCSI_IOCTL_DATA_IN:
1829         cmd.dxfer_direction = SG_DXFER_FROM_DEV;
1830                              break;
1831     case SCSI_IOCTL_DATA_OUT:
1832         cmd.dxfer_direction = SG_DXFER_TO_DEV;
1833                              break;
1834     case SCSI_IOCTL_DATA_UNSPECIFIED:
1835         cmd.dxfer_direction = SG_DXFER_NONE;
1836                              break;
1837     default:
1838        return STATUS_INVALID_PARAMETER;
1839     }
1840
1841     io = ioctl(fd, SG_IO, &cmd);
1842
1843     pPacket->ScsiStatus         = cmd.status;
1844     pPacket->DataTransferLength = cmd.resid;
1845     pPacket->SenseInfoLength    = cmd.sb_len_wr;
1846
1847     ret = CDROM_GetStatusCode(io);
1848
1849 #elif defined HAVE_SCSIREQ_T_CMD
1850
1851     memset(&cmd, 0, sizeof(cmd));
1852     memcpy(&(cmd.cmd), &(pPacket->Cdb), pPacket->CdbLength);
1853
1854     if ( pPacket->DataBufferOffset > 0x1000 )
1855     {
1856         cmd.databuf     = (void*)pPacket->DataBufferOffset;
1857     }
1858     else
1859     {
1860         cmd.databuf     = (char*)pPacket + pPacket->DataBufferOffset;
1861     }
1862
1863     cmd.cmdlen         = pPacket->CdbLength;
1864     cmd.datalen        = pPacket->DataTransferLength;
1865     cmd.senselen       = pPacket->SenseInfoLength;
1866     cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */
1867
1868     switch (pPacket->DataIn)
1869     {
1870     case SCSI_IOCTL_DATA_OUT:
1871         cmd.flags |= SCCMD_WRITE;
1872         break;
1873     case SCSI_IOCTL_DATA_IN:
1874         cmd.flags |= SCCMD_READ;
1875         break;
1876     case SCSI_IOCTL_DATA_UNSPECIFIED:
1877         cmd.flags = 0;
1878         break;
1879     default:
1880        return STATUS_INVALID_PARAMETER;
1881     }
1882
1883     io = ioctl(fd, SCIOCCOMMAND, &cmd);
1884
1885     switch (cmd.retsts)
1886     {
1887     case SCCMD_OK:         break;
1888     case SCCMD_TIMEOUT:    return STATUS_TIMEOUT;
1889                            break;
1890     case SCCMD_BUSY:       return STATUS_DEVICE_BUSY;
1891                            break;
1892     case SCCMD_SENSE:      break;
1893     case SCCMD_UNKNOWN:    return STATUS_UNSUCCESSFUL;
1894                            break;
1895     }
1896
1897     if (pPacket->SenseInfoLength != 0)
1898     {
1899         memcpy((char*)pPacket + pPacket->SenseInfoOffset,
1900                cmd.sense, pPacket->SenseInfoLength);
1901     }
1902
1903     pPacket->ScsiStatus = cmd.status;
1904
1905     ret = CDROM_GetStatusCode(io);
1906
1907 #elif defined(__APPLE__)
1908
1909     memset(&cmd, 0, sizeof(cmd));
1910     memcpy(cmd.cdb, pPacket->Cdb, pPacket->CdbLength);
1911
1912     cmd.cdbSize        = pPacket->CdbLength;
1913     cmd.buffer         = (char*)pPacket + pPacket->DataBufferOffset;
1914     cmd.bufferSize     = pPacket->DataTransferLength;
1915     cmd.sense          = (char*)pPacket + pPacket->SenseInfoOffset;
1916     cmd.senseLen       = pPacket->SenseInfoLength;
1917     cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */
1918
1919     switch (pPacket->DataIn)
1920     {
1921     case SCSI_IOCTL_DATA_OUT:
1922         cmd.direction = kSCSIDataTransfer_FromInitiatorToTarget;
1923         break;
1924     case SCSI_IOCTL_DATA_IN:
1925         cmd.direction = kSCSIDataTransfer_FromTargetToInitiator;
1926         break;
1927     case SCSI_IOCTL_DATA_UNSPECIFIED:
1928         cmd.direction = kSCSIDataTransfer_NoDataTransfer;
1929         break;
1930     default:
1931        return STATUS_INVALID_PARAMETER;
1932     }
1933
1934     io = ioctl(fd, DKIOCSCSICOMMAND, &cmd);
1935
1936     if (cmd.response == kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE)
1937     {
1938         /* Command failed */
1939         switch (cmd.status)
1940         {
1941         case kSCSITaskStatus_TaskTimeoutOccurred:
1942             return STATUS_TIMEOUT;
1943             break;
1944         case kSCSITaskStatus_ProtocolTimeoutOccurred:
1945             return STATUS_IO_TIMEOUT;
1946             break;
1947         case kSCSITaskStatus_DeviceNotResponding:
1948             return STATUS_DEVICE_BUSY;
1949             break;
1950         case kSCSITaskStatus_DeviceNotPresent:
1951             return STATUS_NO_SUCH_DEVICE;
1952             break;
1953         case kSCSITaskStatus_DeliveryFailure:
1954             return STATUS_DEVICE_PROTOCOL_ERROR;
1955             break;
1956         case kSCSITaskStatus_No_Status:
1957         default:
1958             return STATUS_UNSUCCESSFUL;
1959             break;
1960         }
1961     }
1962
1963     if (cmd.status != kSCSITaskStatus_No_Status)
1964         pPacket->ScsiStatus = cmd.status;
1965
1966     ret = CDROM_GetStatusCode(io);
1967 #endif
1968     return ret;
1969 }
1970
1971 /******************************************************************
1972  *              CDROM_ScsiGetCaps
1973  *
1974  *
1975  */
1976 static NTSTATUS CDROM_ScsiGetCaps(int fd, PIO_SCSI_CAPABILITIES caps)
1977 {
1978     NTSTATUS    ret = STATUS_NOT_IMPLEMENTED;
1979
1980 #ifdef SG_SCATTER_SZ
1981     caps->Length = sizeof(*caps);
1982     caps->MaximumTransferLength = SG_SCATTER_SZ; /* FIXME */
1983     caps->MaximumPhysicalPages = SG_SCATTER_SZ / getpagesize();
1984     caps->SupportedAsynchronousEvents = TRUE;
1985     caps->AlignmentMask = getpagesize();
1986     caps->TaggedQueuing = FALSE; /* we could check that it works and answer TRUE */
1987     caps->AdapterScansDown = FALSE; /* FIXME ? */
1988     caps->AdapterUsesPio = FALSE; /* FIXME ? */
1989     ret = STATUS_SUCCESS;
1990 #elif defined __APPLE__
1991     uint64_t bytesr, bytesw, align;
1992     int io = ioctl(fd, DKIOCGETMAXBYTECOUNTREAD, &bytesr);
1993     if (io != 0) return CDROM_GetStatusCode(io);
1994     io = ioctl(fd, DKIOCGETMAXBYTECOUNTWRITE, &bytesw);
1995     if (io != 0) return CDROM_GetStatusCode(io);
1996     io = ioctl(fd, DKIOCGETMINSEGMENTALIGNMENTBYTECOUNT, &align);
1997     if (io != 0) return CDROM_GetStatusCode(io);
1998     caps->Length = sizeof(*caps);
1999     caps->MaximumTransferLength = bytesr < bytesw ? bytesr : bytesw;
2000     caps->MaximumPhysicalPages = caps->MaximumTransferLength / getpagesize();
2001     caps->SupportedAsynchronousEvents = TRUE;
2002     caps->AlignmentMask = align-1;
2003     caps->TaggedQueuing = FALSE; /* we could check that it works and answer TRUE */
2004     caps->AdapterScansDown = FALSE; /* FIXME ? */
2005     caps->AdapterUsesPio = FALSE; /* FIXME ? */
2006     ret = STATUS_SUCCESS;
2007 #else
2008     FIXME("Unimplemented\n");
2009 #endif
2010     return ret;
2011 }
2012
2013 /******************************************************************
2014  *              CDROM_GetAddress
2015  *
2016  * implements IOCTL_SCSI_GET_ADDRESS
2017  */
2018 static NTSTATUS CDROM_GetAddress(int fd, SCSI_ADDRESS* address)
2019 {
2020     UCHAR portnum, busid, targetid, lun;
2021
2022     address->Length = sizeof(SCSI_ADDRESS);
2023     if ( ! CDROM_GetInterfaceInfo(fd, &portnum, &busid, &targetid, &lun))
2024         return STATUS_NOT_SUPPORTED;
2025
2026     address->PortNumber = portnum; /* primary=0 secondary=1 for ide */
2027     address->PathId = busid;       /* always 0 for ide */
2028     address->TargetId = targetid;  /* master=0 slave=1 for ide */
2029     address->Lun = lun;
2030     return STATUS_SUCCESS;
2031 }
2032
2033 /******************************************************************
2034  *              DVD_StartSession
2035  *
2036  *
2037  */
2038 static NTSTATUS DVD_StartSession(int fd, const DVD_SESSION_ID *sid_in, PDVD_SESSION_ID sid_out)
2039 {
2040 #if defined(linux)
2041     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2042     dvd_authinfo auth_info;
2043
2044     memset( &auth_info, 0, sizeof( auth_info ) );
2045     auth_info.type = DVD_LU_SEND_AGID;
2046     if (sid_in) auth_info.lsa.agid = *(const int*)sid_in; /* ?*/
2047
2048     TRACE("fd 0x%08x\n",fd);
2049     ret =CDROM_GetStatusCode(ioctl(fd, DVD_AUTH, &auth_info));
2050     *sid_out = auth_info.lsa.agid;
2051     return ret;
2052 #elif defined(__APPLE__)
2053     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2054     dk_dvd_report_key_t dvdrk;
2055     DVDAuthenticationGrantIDInfo agid_info;
2056
2057     dvdrk.format = kDVDKeyFormatAGID_CSS;
2058     dvdrk.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2059     if(sid_in) dvdrk.grantID = *(uint8_t*)sid_in; /* ? */
2060     dvdrk.bufferLength = sizeof(DVDAuthenticationGrantIDInfo);
2061     dvdrk.buffer = &agid_info;
2062
2063     ret = CDROM_GetStatusCode(ioctl(fd, DKIOCDVDREPORTKEY, &dvdrk));
2064     *sid_out = agid_info.grantID;
2065     return ret;
2066 #else
2067     FIXME("not supported on this O/S\n");
2068     return STATUS_NOT_SUPPORTED;
2069 #endif
2070 }
2071
2072 /******************************************************************
2073  *              DVD_EndSession
2074  *
2075  *
2076  */
2077 static NTSTATUS DVD_EndSession(int fd, const DVD_SESSION_ID *sid)
2078 {
2079 #if defined(linux)
2080     dvd_authinfo auth_info;
2081
2082     memset( &auth_info, 0, sizeof( auth_info ) );
2083     auth_info.type = DVD_INVALIDATE_AGID;
2084     auth_info.lsa.agid = *(const int*)sid;
2085
2086     TRACE("\n");
2087     return CDROM_GetStatusCode(ioctl(fd, DVD_AUTH, &auth_info));
2088 #elif defined(__APPLE__)
2089     dk_dvd_send_key_t dvdsk;
2090
2091     dvdsk.format = kDVDKeyFormatAGID_Invalidate;
2092     dvdsk.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2093     dvdsk.grantID = (uint8_t)*sid;
2094
2095     return CDROM_GetStatusCode(ioctl(fd, DKIOCDVDSENDKEY, &dvdsk));
2096 #else
2097     FIXME("not supported on this O/S\n");
2098     return STATUS_NOT_SUPPORTED;
2099 #endif
2100 }
2101
2102 /******************************************************************
2103  *              DVD_SendKey
2104  *
2105  *
2106  */
2107 static NTSTATUS DVD_SendKey(int fd, const DVD_COPY_PROTECT_KEY *key)
2108 {
2109 #if defined(linux)
2110     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2111     dvd_authinfo auth_info;
2112
2113     memset( &auth_info, 0, sizeof( auth_info ) );
2114     switch (key->KeyType)
2115     {
2116     case DvdChallengeKey:
2117         auth_info.type = DVD_HOST_SEND_CHALLENGE;
2118         auth_info.hsc.agid = (int)key->SessionId;
2119         TRACE("DvdChallengeKey ioc 0x%x\n", DVD_AUTH );
2120         memcpy( auth_info.hsc.chal, key->KeyData, DVD_CHALLENGE_SIZE );
2121         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2122         break;
2123     case DvdBusKey2:
2124         auth_info.type = DVD_HOST_SEND_KEY2;
2125         auth_info.hsk.agid = (int)key->SessionId;
2126
2127         memcpy( auth_info.hsk.key, key->KeyData, DVD_KEY_SIZE );
2128         
2129         TRACE("DvdBusKey2\n");
2130         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2131         break;
2132
2133     default:
2134         FIXME("Unknown Keytype 0x%x\n",key->KeyType);
2135     }
2136     return ret;
2137 #elif defined(__APPLE__)
2138     dk_dvd_send_key_t dvdsk;
2139     union
2140     {
2141         DVDChallengeKeyInfo chal;
2142         DVDKey2Info key2;
2143     } key_desc;
2144
2145     switch(key->KeyType)
2146     {
2147     case DvdChallengeKey:
2148         dvdsk.format = kDVDKeyFormatChallengeKey;
2149         dvdsk.bufferLength = sizeof(key_desc.chal);
2150         dvdsk.buffer = &key_desc.chal;
2151         OSWriteBigInt16(key_desc.chal.dataLength, 0, key->KeyLength);
2152         memcpy(key_desc.chal.challengeKeyValue, key->KeyData, key->KeyLength);
2153         break;
2154     case DvdBusKey2:
2155         dvdsk.format = kDVDKeyFormatKey2;
2156         dvdsk.bufferLength = sizeof(key_desc.key2);
2157         dvdsk.buffer = &key_desc.key2;
2158         OSWriteBigInt16(key_desc.key2.dataLength, 0, key->KeyLength);
2159         memcpy(key_desc.key2.key2Value, key->KeyData, key->KeyLength);
2160         break;
2161     case DvdInvalidateAGID:
2162         dvdsk.format = kDVDKeyFormatAGID_Invalidate;
2163         break;
2164     case DvdBusKey1:
2165     case DvdTitleKey:
2166     case DvdAsf:
2167     case DvdGetRpcKey:
2168     case DvdDiskKey:
2169         ERR("attempted to write read-only key type 0x%x\n", key->KeyType);
2170         return STATUS_NOT_SUPPORTED;
2171     case DvdSetRpcKey:
2172         FIXME("DvdSetRpcKey NIY\n");
2173         return STATUS_NOT_SUPPORTED;
2174     default:
2175         FIXME("got unknown key type 0x%x\n", key->KeyType);
2176         return STATUS_NOT_SUPPORTED;
2177     }
2178     dvdsk.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2179     dvdsk.grantID = (uint8_t)key->SessionId;
2180
2181     return CDROM_GetStatusCode(ioctl(fd, DKIOCDVDSENDKEY, &dvdsk));
2182 #else
2183     FIXME("not supported on this O/S\n");
2184     return STATUS_NOT_SUPPORTED;
2185 #endif    
2186 }
2187
2188 /******************************************************************
2189  *              DVD_ReadKey
2190  *
2191  *
2192  */
2193 static NTSTATUS DVD_ReadKey(int fd, PDVD_COPY_PROTECT_KEY key)
2194 {
2195 #if defined(linux)
2196     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2197     dvd_struct dvd;
2198     dvd_authinfo auth_info;
2199
2200     memset( &dvd, 0, sizeof( dvd_struct ) );
2201     memset( &auth_info, 0, sizeof( auth_info ) );
2202     switch (key->KeyType)
2203     {
2204     case DvdDiskKey:
2205         
2206         dvd.type = DVD_STRUCT_DISCKEY;
2207         dvd.disckey.agid = (int)key->SessionId;
2208         memset( dvd.disckey.value, 0, DVD_DISCKEY_SIZE );
2209         
2210         TRACE("DvdDiskKey\n");
2211         ret = CDROM_GetStatusCode(ioctl( fd, DVD_READ_STRUCT, &dvd ));
2212         if (ret == STATUS_SUCCESS)
2213             memcpy(key->KeyData,dvd.disckey.value,DVD_DISCKEY_SIZE);
2214         break;
2215     case DvdTitleKey:
2216         auth_info.type = DVD_LU_SEND_TITLE_KEY;
2217         auth_info.lstk.agid = (int)key->SessionId;
2218         auth_info.lstk.lba = (int)(key->Parameters.TitleOffset.QuadPart>>11);
2219         TRACE("DvdTitleKey session %d Quadpart 0x%08lx offset 0x%08x\n",
2220               (int)key->SessionId, (long)key->Parameters.TitleOffset.QuadPart, 
2221               auth_info.lstk.lba);
2222         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2223         if (ret == STATUS_SUCCESS)
2224             memcpy(key->KeyData, auth_info.lstk.title_key, DVD_KEY_SIZE );
2225         break;
2226     case DvdChallengeKey:
2227
2228         auth_info.type = DVD_LU_SEND_CHALLENGE;
2229         auth_info.lsc.agid = (int)key->SessionId;
2230
2231         TRACE("DvdChallengeKey\n");
2232         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2233         if (ret == STATUS_SUCCESS)
2234             memcpy( key->KeyData, auth_info.lsc.chal, DVD_CHALLENGE_SIZE );
2235         break;
2236     case DvdAsf:
2237         auth_info.type = DVD_LU_SEND_ASF;
2238         TRACE("DvdAsf\n");
2239         auth_info.lsasf.asf=((PDVD_ASF)key->KeyData)->SuccessFlag;
2240         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2241         ((PDVD_ASF)key->KeyData)->SuccessFlag = auth_info.lsasf.asf;
2242         break;
2243     case DvdBusKey1:
2244         auth_info.type = DVD_LU_SEND_KEY1;
2245         auth_info.lsk.agid = (int)key->SessionId;
2246
2247         TRACE("DvdBusKey1\n");
2248         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2249
2250         if (ret == STATUS_SUCCESS)
2251             memcpy( key->KeyData, auth_info.lsk.key, DVD_KEY_SIZE );
2252         break;
2253     case DvdGetRpcKey:
2254         auth_info.type = DVD_LU_SEND_RPC_STATE;
2255
2256         TRACE("DvdGetRpcKey\n");
2257         ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2258
2259         if (ret == STATUS_SUCCESS)
2260         {
2261             ((PDVD_RPC_KEY)key->KeyData)->TypeCode = auth_info.lrpcs.type;
2262             ((PDVD_RPC_KEY)key->KeyData)->RegionMask = auth_info.lrpcs.region_mask;
2263             ((PDVD_RPC_KEY)key->KeyData)->RpcScheme = auth_info.lrpcs.rpc_scheme;
2264             ((PDVD_RPC_KEY)key->KeyData)->UserResetsAvailable = auth_info.lrpcs.ucca;
2265             ((PDVD_RPC_KEY)key->KeyData)->ManufacturerResetsAvailable = auth_info.lrpcs.vra;
2266         }
2267         break;
2268     default:
2269         FIXME("Unknown keytype 0x%x\n",key->KeyType);
2270     }
2271     return ret;
2272 #elif defined(__APPLE__)
2273     union
2274     {
2275         dk_dvd_report_key_t key;
2276         dk_dvd_read_structure_t disk_key;
2277     } ioc;
2278     union
2279     {
2280         DVDDiscKeyInfo disk_key;
2281         DVDChallengeKeyInfo chal;
2282         DVDKey1Info key1;
2283         DVDTitleKeyInfo title;
2284         DVDAuthenticationSuccessFlagInfo asf;
2285         DVDRegionPlaybackControlInfo rpc;
2286     } desc;
2287     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2288
2289     switch(key->KeyType)
2290     {
2291     case DvdChallengeKey:
2292         ioc.key.format = kDVDKeyFormatChallengeKey;
2293         ioc.key.grantID = (uint8_t)key->SessionId;
2294         ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2295         ioc.key.bufferLength = sizeof(desc.chal);
2296         ioc.key.buffer = &desc.chal;
2297         OSWriteBigInt16(desc.chal.dataLength, 0, key->KeyLength);
2298         break;
2299     case DvdBusKey1:
2300         ioc.key.format = kDVDKeyFormatKey1;
2301         ioc.key.grantID = (uint8_t)key->SessionId;
2302         ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2303         ioc.key.bufferLength = sizeof(desc.key1);
2304         ioc.key.buffer = &desc.key1;
2305         OSWriteBigInt16(desc.key1.dataLength, 0, key->KeyLength);
2306         break;
2307     case DvdTitleKey:
2308         ioc.key.format = kDVDKeyFormatTitleKey;
2309         ioc.key.grantID = (uint8_t)key->SessionId;
2310         ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2311         ioc.key.bufferLength = sizeof(desc.title);
2312         ioc.key.buffer = &desc.title;
2313         ioc.key.address = (uint32_t)(key->Parameters.TitleOffset.QuadPart>>11);
2314         OSWriteBigInt16(desc.title.dataLength, 0, key->KeyLength);
2315         break;
2316     case DvdAsf:
2317         ioc.key.format = kDVDKeyFormatASF;
2318         ioc.key.grantID = (uint8_t)key->SessionId;
2319         ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2320         ioc.key.bufferLength = sizeof(desc.asf);
2321         ioc.key.buffer = &desc.asf;
2322         OSWriteBigInt16(desc.asf.dataLength, 0, key->KeyLength);
2323         break;
2324     case DvdGetRpcKey:
2325         ioc.key.format = kDVDKeyFormatRegionState;
2326         ioc.key.grantID = (uint8_t)key->SessionId;
2327         ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2328         ioc.key.bufferLength = sizeof(desc.rpc);
2329         ioc.key.buffer = &desc.rpc;
2330         OSWriteBigInt16(desc.rpc.dataLength, 0, key->KeyLength);
2331         break;
2332     case DvdDiskKey:
2333         ioc.disk_key.format = kDVDStructureFormatDiscKeyInfo;
2334         ioc.disk_key.grantID = (uint8_t)key->SessionId;
2335         ioc.disk_key.bufferLength = sizeof(desc.disk_key);
2336         ioc.disk_key.buffer = &desc.disk_key;
2337         break;
2338     case DvdInvalidateAGID:
2339         ioc.key.format = kDVDKeyFormatAGID_Invalidate;
2340         ioc.key.grantID = (uint8_t)key->SessionId;
2341         ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2342         break;
2343     case DvdBusKey2:
2344     case DvdSetRpcKey:
2345         ERR("attempted to read write-only key type 0x%x\n", key->KeyType);
2346         return STATUS_NOT_SUPPORTED;
2347     default:
2348         FIXME("got unknown key type 0x%x\n", key->KeyType);
2349         return STATUS_NOT_SUPPORTED;
2350     }
2351
2352     ret = CDROM_GetStatusCode(ioctl(fd, (key->KeyType == DvdDiskKey ? DKIOCDVDREADSTRUCTURE : DKIOCDVDREPORTKEY), &ioc));
2353
2354     if (ret == STATUS_SUCCESS)
2355     {
2356         switch(key->KeyType)
2357         {
2358         case DvdChallengeKey:
2359             key->KeyLength = OSReadBigInt16(desc.chal.dataLength, 0);
2360             memcpy(key->KeyData, desc.chal.challengeKeyValue, key->KeyLength);
2361             break;
2362         case DvdBusKey1:
2363             key->KeyLength = OSReadBigInt16(desc.key1.dataLength, 0);
2364             memcpy(key->KeyData, desc.key1.key1Value, key->KeyLength);
2365             break;
2366         case DvdTitleKey:
2367             key->KeyLength = OSReadBigInt16(desc.title.dataLength, 0);
2368             memcpy(key->KeyData, desc.title.titleKeyValue, key->KeyLength);
2369             key->KeyFlags = 0;
2370             if (desc.title.CPM)
2371             {
2372                 /*key->KeyFlags |= DVD_COPYRIGHTED;*/
2373                 if (desc.title.CP_SEC) key->KeyFlags |= DVD_SECTOR_PROTECTED;
2374                 /*else key->KeyFlags |= DVD_SECTOR_NOT_PROTECTED;*/
2375 #if 0
2376                 switch (desc.title.CGMS)
2377                 {
2378                 case 0:
2379                     key->KeyFlags |= DVD_CGMS_COPY_PERMITTED;
2380                     break;
2381                 case 2:
2382                     key->KeyFlags |= DVD_CGMS_COPY_ONCE;
2383                     break;
2384                 case 3:
2385                     key->KeyFlags |= DVD_CGMS_NO_COPY;
2386                     break;
2387                 }
2388 #endif
2389             } /*else key->KeyFlags |= DVD_NOT_COPYRIGHTED;*/
2390             break;
2391         case DvdAsf:
2392             key->KeyLength = OSReadBigInt16(desc.title.dataLength, 0);
2393             ((PDVD_ASF)key->KeyData)->SuccessFlag = desc.asf.successFlag;
2394             break;
2395         case DvdGetRpcKey:
2396             key->KeyLength = OSReadBigInt16(desc.rpc.dataLength, 0);
2397             ((PDVD_RPC_KEY)key->KeyData)->UserResetsAvailable =
2398                 desc.rpc.numberUserResets;
2399             ((PDVD_RPC_KEY)key->KeyData)->ManufacturerResetsAvailable =
2400                 desc.rpc.numberVendorResets;
2401             ((PDVD_RPC_KEY)key->KeyData)->TypeCode =
2402                 desc.rpc.typeCode;
2403             ((PDVD_RPC_KEY)key->KeyData)->RegionMask =
2404                 desc.rpc.driveRegion;
2405             ((PDVD_RPC_KEY)key->KeyData)->RpcScheme =
2406                 desc.rpc.rpcScheme;
2407         case DvdDiskKey:
2408             key->KeyLength = OSReadBigInt16(desc.disk_key.dataLength, 0);
2409             memcpy(key->KeyData, desc.disk_key.discKeyStructures, key->KeyLength);
2410             break;
2411         case DvdBusKey2:
2412         case DvdSetRpcKey:
2413         case DvdInvalidateAGID:
2414         default:
2415             /* Silence warning */
2416             ;
2417         }
2418     }
2419     return ret;
2420 #else
2421     FIXME("not supported on this O/S\n");
2422     return STATUS_NOT_SUPPORTED;
2423 #endif
2424 }
2425
2426 /******************************************************************
2427  *              DVD_GetRegion
2428  *
2429  * This IOCTL combines information from both IOCTL_DVD_READ_KEY
2430  * with key type DvdGetRpcKey and IOCTL_DVD_READ_STRUCTURE with
2431  * structure type DvdCopyrightInformation into one structure.
2432  */
2433 static NTSTATUS DVD_GetRegion(int fd, PDVD_REGION region)
2434 {
2435 #if defined(linux)
2436     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2437     dvd_struct dvd;
2438     dvd_authinfo auth_info;
2439
2440     dvd.type = DVD_STRUCT_COPYRIGHT;
2441     dvd.copyright.layer_num = 0;
2442     auth_info.type = DVD_LU_SEND_RPC_STATE;
2443
2444     ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2445
2446     if (ret == STATUS_SUCCESS)
2447     {
2448         ret = CDROM_GetStatusCode(ioctl( fd, DVD_READ_STRUCT, &dvd ));
2449
2450         if (ret == STATUS_SUCCESS)
2451         {
2452             region->CopySystem = dvd.copyright.cpst;
2453             region->RegionData = dvd.copyright.rmi;
2454             region->SystemRegion = auth_info.lrpcs.region_mask;
2455             region->ResetCount = auth_info.lrpcs.ucca;
2456         }
2457     }
2458     return ret;
2459 #elif defined(__APPLE__)
2460     dk_dvd_report_key_t key;
2461     dk_dvd_read_structure_t dvd;
2462     DVDRegionPlaybackControlInfo rpc;
2463     DVDCopyrightInfo copy;
2464     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2465
2466     key.format = kDVDKeyFormatRegionState;
2467     key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
2468     key.bufferLength = sizeof(rpc);
2469     key.buffer = &rpc;
2470     dvd.format = kDVDStructureFormatCopyrightInfo;
2471     dvd.bufferLength = sizeof(copy);
2472     dvd.buffer = &copy;
2473
2474     ret = CDROM_GetStatusCode(ioctl( fd, DKIOCDVDREPORTKEY, &key ));
2475
2476     if (ret == STATUS_SUCCESS)
2477     {
2478         ret = CDROM_GetStatusCode(ioctl( fd, DKIOCDVDREADSTRUCTURE, &dvd ));
2479
2480         if (ret == STATUS_SUCCESS)
2481         {
2482             region->CopySystem = copy.copyrightProtectionSystemType;
2483             region->RegionData = copy.regionMask;
2484             region->SystemRegion = rpc.driveRegion;
2485             region->ResetCount = rpc.numberUserResets;
2486         }
2487     }
2488     return ret;
2489 #else
2490     FIXME("not supported on this O/S\n");
2491     return STATUS_NOT_SUPPORTED;
2492 #endif
2493 }
2494
2495 /******************************************************************
2496  *              DVD_ReadStructure
2497  *
2498  *
2499  */
2500 static NTSTATUS DVD_ReadStructure(int dev, const DVD_READ_STRUCTURE *structure, PDVD_LAYER_DESCRIPTOR layer)
2501 {
2502 #ifdef DVD_READ_STRUCT
2503     /* dvd_struct is not defined consistently across platforms */
2504     union
2505     {
2506         struct dvd_physical     physical;
2507         struct dvd_copyright    copyright;
2508         struct dvd_disckey      disckey;
2509         struct dvd_bca          bca;
2510         struct dvd_manufact     manufact;
2511     } s;
2512
2513     if (structure->BlockByteOffset.u.HighPart || structure->BlockByteOffset.u.LowPart)
2514         FIXME(": BlockByteOffset is not handled\n");
2515
2516     switch (structure->Format)
2517     {
2518     case DvdPhysicalDescriptor:
2519         s.physical.type = DVD_STRUCT_PHYSICAL;
2520         s.physical.layer_num = structure->LayerNumber;
2521         break;
2522
2523     case DvdCopyrightDescriptor:
2524         s.copyright.type = DVD_STRUCT_COPYRIGHT;
2525         s.copyright.layer_num = structure->LayerNumber;
2526         break;
2527
2528     case DvdDiskKeyDescriptor:
2529         s.disckey.type = DVD_STRUCT_DISCKEY;
2530         s.disckey.agid = structure->SessionId;
2531         break;
2532
2533     case DvdBCADescriptor:
2534         s.bca.type = DVD_STRUCT_BCA;
2535         break;
2536
2537     case DvdManufacturerDescriptor:
2538         s.manufact.type = DVD_STRUCT_MANUFACT;
2539         s.manufact.layer_num = structure->LayerNumber;
2540         break;
2541
2542     case DvdMaxDescriptor: /* This is not a real request, no matter what MSDN says! */
2543     default:
2544         return STATUS_INVALID_PARAMETER;
2545     }
2546
2547     if (ioctl(dev, DVD_READ_STRUCT, &s) < 0)
2548        return STATUS_INVALID_PARAMETER;
2549
2550     switch (structure->Format)
2551     {
2552     case DvdPhysicalDescriptor:
2553         {
2554             internal_dvd_layer_descriptor *p = (internal_dvd_layer_descriptor *) layer;
2555             struct dvd_layer *l = &s.physical.layer[s.physical.layer_num];
2556
2557             p->DataLength[0] = 2;
2558             p->DataLength[1] = 8;
2559             p->Reserved0[0] = 0;
2560             p->Reserved0[1] = 0;
2561             p->BookVersion = l->book_version;
2562             p->BookType = l->book_type;
2563             p->MinimumRate = l->min_rate;
2564             p->DiskSize = l->disc_size;
2565             p->LayerType = l->layer_type;
2566             p->TrackPath = l->track_path;
2567             p->NumberOfLayers = l->nlayers;
2568             p->Reserved1 = 0;
2569             p->TrackDensity = l->track_density;
2570             p->LinearDensity = l->linear_density;
2571             p->StartingDataSector = l->start_sector;
2572             p->EndDataSector = l->end_sector;
2573             p->EndLayerZeroSector = l->end_sector_l0;
2574             p->Reserved5 = 0;
2575             p->BCAFlag = l->bca;
2576             p->Reserved6 = 0;
2577         }
2578         break;
2579
2580     case DvdCopyrightDescriptor:
2581         {
2582             PDVD_COPYRIGHT_DESCRIPTOR p = (PDVD_COPYRIGHT_DESCRIPTOR) layer;
2583
2584             p->CopyrightProtectionType = s.copyright.cpst;
2585             p->RegionManagementInformation = s.copyright.rmi;
2586             p->Reserved = 0;
2587         }
2588         break;
2589
2590     case DvdDiskKeyDescriptor:
2591         {
2592             PDVD_DISK_KEY_DESCRIPTOR p = (PDVD_DISK_KEY_DESCRIPTOR) layer;
2593
2594             memcpy(p->DiskKeyData, s.disckey.value, 2048);
2595         }
2596         break;
2597
2598     case DvdBCADescriptor:
2599         {
2600             PDVD_BCA_DESCRIPTOR p = (PDVD_BCA_DESCRIPTOR) layer;
2601
2602             memcpy(p->BCAInformation, s.bca.value, s.bca.len);
2603         }
2604         break;
2605
2606     case DvdManufacturerDescriptor:
2607         {
2608             PDVD_MANUFACTURER_DESCRIPTOR p = (PDVD_MANUFACTURER_DESCRIPTOR) layer;
2609
2610             memcpy(p->ManufacturingInformation, s.manufact.value, 2048);
2611         }
2612         break;
2613
2614     case DvdMaxDescriptor: /* Suppress warning */
2615         break;
2616     }
2617 #elif defined(__APPLE__)
2618     NTSTATUS ret = STATUS_NOT_SUPPORTED;
2619     dk_dvd_read_structure_t dvdrs;
2620     union
2621     {
2622         DVDPhysicalFormatInfo phys;
2623         DVDCopyrightInfo copy;
2624         DVDDiscKeyInfo disk_key;
2625         DVDManufacturingInfo manf;
2626     } desc;
2627     union
2628     {
2629         PDVD_LAYER_DESCRIPTOR layer;
2630         internal_dvd_layer_descriptor *xlayer;
2631         PDVD_COPYRIGHT_DESCRIPTOR copy;
2632         PDVD_DISK_KEY_DESCRIPTOR disk_key;
2633         PDVD_MANUFACTURER_DESCRIPTOR manf;
2634     } nt_desc;
2635
2636     nt_desc.layer = layer;
2637     dvdrs.address = (uint32_t)(structure->BlockByteOffset.QuadPart>>11);
2638     dvdrs.grantID = (uint8_t)structure->SessionId;
2639     dvdrs.layer = structure->LayerNumber;
2640     switch(structure->Format)
2641     {
2642     case DvdPhysicalDescriptor:
2643         dvdrs.format = kDVDStructureFormatPhysicalFormatInfo;
2644         dvdrs.bufferLength = sizeof(desc.phys);
2645         dvdrs.buffer = &desc.phys;
2646         break;
2647
2648     case DvdCopyrightDescriptor:
2649         dvdrs.format = kDVDStructureFormatCopyrightInfo;
2650         dvdrs.bufferLength = sizeof(desc.copy);
2651         dvdrs.buffer = &desc.copy;
2652         break;
2653
2654     case DvdDiskKeyDescriptor:
2655         dvdrs.format = kDVDStructureFormatDiscKeyInfo;
2656         dvdrs.bufferLength = sizeof(desc.disk_key);
2657         dvdrs.buffer = &desc.disk_key;
2658         break;
2659
2660     case DvdBCADescriptor:
2661         FIXME("DvdBCADescriptor NIY\n");
2662         return STATUS_NOT_SUPPORTED;
2663
2664     case DvdManufacturerDescriptor:
2665         dvdrs.format = kDVDStructureFormatManufacturingInfo;
2666         dvdrs.bufferLength = sizeof(desc.manf);
2667         dvdrs.buffer = &desc.manf;
2668         break;
2669
2670     case DvdMaxDescriptor:
2671     default:
2672         FIXME("got unknown structure type 0x%x\n", structure->Format);
2673         return STATUS_NOT_SUPPORTED;
2674     }
2675     ret = CDROM_GetStatusCode(ioctl(dev, DKIOCDVDREADSTRUCTURE, &dvdrs));
2676     if(ret == STATUS_SUCCESS)
2677     {
2678         switch(structure->Format)
2679         {
2680         case DvdPhysicalDescriptor:
2681             nt_desc.xlayer->DataLength[0] = 2;
2682             nt_desc.xlayer->DataLength[1] = 8;
2683             nt_desc.xlayer->Reserved0[0] = 0;
2684             nt_desc.xlayer->Reserved0[1] = 0;
2685             nt_desc.xlayer->BookVersion = desc.phys.partVersion;
2686             nt_desc.xlayer->BookType = desc.phys.bookType;
2687             nt_desc.xlayer->MinimumRate = desc.phys.minimumRate;
2688             nt_desc.xlayer->DiskSize = desc.phys.discSize;
2689             nt_desc.xlayer->LayerType = desc.phys.layerType;
2690             nt_desc.xlayer->TrackPath = desc.phys.trackPath;
2691             nt_desc.xlayer->NumberOfLayers = desc.phys.numberOfLayers;
2692             nt_desc.xlayer->Reserved1 = 0;
2693             nt_desc.xlayer->TrackDensity = desc.phys.trackDensity;
2694             nt_desc.xlayer->LinearDensity = desc.phys.linearDensity;
2695             nt_desc.xlayer->BCAFlag = desc.phys.bcaFlag;
2696             nt_desc.xlayer->StartingDataSector = OSReadBigInt32(&desc.phys.zero1, 0);
2697             nt_desc.xlayer->EndDataSector = OSReadBigInt32(&desc.phys.zero2, 0);
2698             nt_desc.xlayer->EndLayerZeroSector = OSReadBigInt32(&desc.phys.zero3, 0);
2699             nt_desc.xlayer->Reserved5 = 0;
2700             nt_desc.xlayer->Reserved6 = 0;
2701             break;
2702
2703         case DvdCopyrightDescriptor:
2704             nt_desc.copy->CopyrightProtectionType =
2705                 desc.copy.copyrightProtectionSystemType;
2706             nt_desc.copy->RegionManagementInformation =
2707                 desc.copy.regionMask;
2708             nt_desc.copy->Reserved = 0;
2709             break;
2710
2711         case DvdDiskKeyDescriptor:
2712             memcpy(
2713                 nt_desc.disk_key->DiskKeyData,
2714                 desc.disk_key.discKeyStructures,
2715                 2048);
2716             break;
2717
2718         case DvdManufacturerDescriptor:
2719             memcpy(
2720                 nt_desc.manf->ManufacturingInformation,
2721                 desc.manf.discManufacturingInfo,
2722                 2048);
2723             break;
2724
2725         case DvdBCADescriptor:
2726         case DvdMaxDescriptor:
2727         default:
2728             /* Silence warning */
2729             break;
2730         }
2731     }
2732     return ret;
2733 #else
2734     FIXME("\n");
2735 #endif
2736     return STATUS_SUCCESS;
2737
2738 }
2739
2740 /******************************************************************
2741  *        GetInquiryData
2742  *        Implements the IOCTL_GET_INQUIRY_DATA ioctl.
2743  *        Returns Inquiry data for all devices on the specified scsi bus
2744  *        Returns STATUS_BUFFER_TOO_SMALL if the output buffer is too small, 
2745  *        STATUS_INVALID_DEVICE_REQUEST if the given handle isn't to a SCSI device,
2746  *        or STATUS_NOT_SUPPORTED if the OS driver is too old
2747  */
2748 static NTSTATUS GetInquiryData(int fd, PSCSI_ADAPTER_BUS_INFO BufferOut, DWORD OutBufferSize)
2749 {
2750 #ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
2751     PSCSI_INQUIRY_DATA pInquiryData = NULL;
2752     UCHAR sense_buffer[32];
2753     int iochk, version;
2754     sg_io_hdr_t iocmd;
2755     UCHAR inquiry[INQ_CMD_LEN] = {INQUIRY, 0, 0, 0, INQ_REPLY_LEN, 0};
2756
2757     /* Check we have a SCSI device and a supported driver */
2758     if(ioctl(fd, SG_GET_VERSION_NUM, &version) != 0)
2759     {
2760         WARN("IOCTL_SCSI_GET_INQUIRY_DATA sg driver is not loaded\n");
2761         return STATUS_INVALID_DEVICE_REQUEST;
2762     }
2763     if(version < 30000 )
2764         return STATUS_NOT_SUPPORTED;
2765
2766     /* FIXME: Enumerate devices on the bus */
2767     BufferOut->NumberOfBuses = 1;
2768     BufferOut->BusData[0].NumberOfLogicalUnits = 1;
2769     BufferOut->BusData[0].InquiryDataOffset = sizeof(SCSI_ADAPTER_BUS_INFO);
2770
2771     pInquiryData = (PSCSI_INQUIRY_DATA)(BufferOut + 1);
2772
2773     RtlZeroMemory(&iocmd, sizeof(iocmd));
2774     iocmd.interface_id = 'S';
2775     iocmd.cmd_len = sizeof(inquiry);
2776     iocmd.mx_sb_len = sizeof(sense_buffer);
2777     iocmd.dxfer_direction = SG_DXFER_FROM_DEV;
2778     iocmd.dxfer_len = INQ_REPLY_LEN;
2779     iocmd.dxferp = pInquiryData->InquiryData;
2780     iocmd.cmdp = inquiry;
2781     iocmd.sbp = sense_buffer;
2782     iocmd.timeout = 1000;
2783
2784     iochk = ioctl(fd, SG_IO, &iocmd);
2785     if(iochk != 0)
2786         WARN("ioctl SG_IO returned %d, error (%s)\n", iochk, strerror(errno));
2787
2788     CDROM_GetInterfaceInfo(fd, &BufferOut->BusData[0].InitiatorBusId, &pInquiryData->PathId, &pInquiryData->TargetId, &pInquiryData->Lun);
2789     pInquiryData->DeviceClaimed = TRUE;
2790     pInquiryData->InquiryDataLength = INQ_REPLY_LEN;
2791     pInquiryData->NextInquiryDataOffset = 0;
2792     return STATUS_SUCCESS;
2793 #else
2794     FIXME("not supported on this O/S\n");
2795     return STATUS_NOT_SUPPORTED;
2796 #endif
2797 }
2798
2799 /******************************************************************
2800  *              CDROM_DeviceIoControl
2801  *
2802  *
2803  */
2804 NTSTATUS CDROM_DeviceIoControl(HANDLE hDevice, 
2805                                HANDLE hEvent, PIO_APC_ROUTINE UserApcRoutine,
2806                                PVOID UserApcContext, 
2807                                PIO_STATUS_BLOCK piosb, 
2808                                ULONG dwIoControlCode,
2809                                LPVOID lpInBuffer, DWORD nInBufferSize,
2810                                LPVOID lpOutBuffer, DWORD nOutBufferSize)
2811 {
2812     DWORD       sz = 0;
2813     NTSTATUS    status = STATUS_SUCCESS;
2814     int fd, needs_close, dev;
2815
2816     TRACE("%p %s %p %d %p %d %p\n",
2817           hDevice, iocodex(dwIoControlCode), lpInBuffer, nInBufferSize,
2818           lpOutBuffer, nOutBufferSize, piosb);
2819
2820     piosb->Information = 0;
2821
2822     if ((status = server_get_unix_fd( hDevice, 0, &fd, &needs_close, NULL, NULL )))
2823     {
2824         if (status == STATUS_BAD_DEVICE_TYPE) return status;  /* no associated fd */
2825         goto error;
2826     }
2827
2828     if ((status = CDROM_Open(fd, &dev)))
2829     {
2830         if (needs_close) close( fd );
2831         goto error;
2832     }
2833
2834 #ifdef __APPLE__
2835     {
2836         char name[100];
2837
2838         /* This is ugly as hell, but Mac OS is unable to do anything from the
2839          * partition fd, it wants an fd for the whole device, and it sometimes
2840          * also requires the device fd to be closed first, so we have to close
2841          * the handle that the caller gave us.
2842          * Also for some reason it wants the fd to be closed before we even
2843          * open the parent if we're trying to eject the disk.
2844          */
2845         if ((status = get_parent_device( fd, name, sizeof(name) ))) goto error;
2846         if (dwIoControlCode == IOCTL_STORAGE_EJECT_MEDIA)
2847             NtClose( hDevice );
2848         if (needs_close) close( fd );
2849         TRACE("opening parent %s\n", name );
2850         if ((fd = open( name, O_RDONLY )) == -1)
2851         {
2852             status = FILE_GetNtStatus();
2853             goto error;
2854         }
2855         needs_close = 1;
2856     }
2857 #endif
2858
2859     switch (dwIoControlCode)
2860     {
2861     case IOCTL_CDROM_CHECK_VERIFY:
2862     case IOCTL_DISK_CHECK_VERIFY:
2863     case IOCTL_STORAGE_CHECK_VERIFY:
2864     case IOCTL_STORAGE_CHECK_VERIFY2:
2865         sz = 0;
2866         CDROM_ClearCacheEntry(dev);
2867         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2868             status = STATUS_INVALID_PARAMETER;
2869         else status = CDROM_Verify(dev, fd);
2870         break;
2871
2872 /* EPP     case IOCTL_STORAGE_CHECK_VERIFY2: */
2873
2874 /* EPP     case IOCTL_STORAGE_FIND_NEW_DEVICES: */
2875 /* EPP     case IOCTL_CDROM_FIND_NEW_DEVICES: */
2876
2877     case IOCTL_STORAGE_LOAD_MEDIA:
2878     case IOCTL_CDROM_LOAD_MEDIA:
2879         sz = 0;
2880         CDROM_ClearCacheEntry(dev);
2881         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2882             status = STATUS_INVALID_PARAMETER;
2883         else status = CDROM_SetTray(fd, FALSE);
2884         break;
2885      case IOCTL_STORAGE_EJECT_MEDIA:
2886         sz = 0;
2887         CDROM_ClearCacheEntry(dev);
2888         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2889             status = STATUS_INVALID_PARAMETER;
2890         else
2891             status = CDROM_SetTray(fd, TRUE);
2892         break;
2893
2894     case IOCTL_CDROM_MEDIA_REMOVAL:
2895     case IOCTL_DISK_MEDIA_REMOVAL:
2896     case IOCTL_STORAGE_MEDIA_REMOVAL:
2897     case IOCTL_STORAGE_EJECTION_CONTROL:
2898         /* FIXME the last ioctl:s is not the same as the two others...
2899          * lockcount/owner should be handled */
2900         sz = 0;
2901         CDROM_ClearCacheEntry(dev);
2902         if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2903         else if (nInBufferSize < sizeof(PREVENT_MEDIA_REMOVAL)) status = STATUS_BUFFER_TOO_SMALL;
2904         else status = CDROM_ControlEjection(fd, lpInBuffer);
2905         break;
2906
2907     case IOCTL_STORAGE_GET_MEDIA_TYPES:
2908     case IOCTL_STORAGE_GET_MEDIA_TYPES_EX:
2909         sz = sizeof(GET_MEDIA_TYPES);
2910         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2911         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2912         else status = CDROM_GetMediaType(dev, lpOutBuffer);
2913         break;
2914
2915     case IOCTL_STORAGE_GET_DEVICE_NUMBER:
2916         sz = sizeof(STORAGE_DEVICE_NUMBER);
2917         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2918         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2919         else status = CDROM_GetDeviceNumber(dev, lpOutBuffer);
2920         break;
2921
2922     case IOCTL_STORAGE_RESET_DEVICE:
2923         sz = 0;
2924         CDROM_ClearCacheEntry(dev);
2925         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2926             status = STATUS_INVALID_PARAMETER;
2927         else status = CDROM_ResetAudio(fd);
2928         break;
2929
2930     case IOCTL_CDROM_GET_CONTROL:
2931         sz = sizeof(CDROM_AUDIO_CONTROL);
2932         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2933         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2934         else status = CDROM_GetControl(dev, fd, lpOutBuffer);
2935         break;
2936
2937     case IOCTL_CDROM_GET_DRIVE_GEOMETRY:
2938         sz = sizeof(DISK_GEOMETRY);
2939         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2940         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2941         else status = CDROM_GetDriveGeometry(dev, fd, lpOutBuffer);
2942         break;
2943
2944     case IOCTL_CDROM_DISK_TYPE:
2945         sz = sizeof(CDROM_DISK_DATA);
2946         /* CDROM_ClearCacheEntry(dev); */
2947         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2948         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2949         else status = CDROM_GetDiskData(dev, fd, lpOutBuffer);
2950         break;
2951
2952 /* EPP     case IOCTL_CDROM_GET_LAST_SESSION: */
2953
2954     case IOCTL_CDROM_READ_Q_CHANNEL:
2955         sz = sizeof(SUB_Q_CHANNEL_DATA);
2956         if (lpInBuffer == NULL || nInBufferSize < sizeof(CDROM_SUB_Q_DATA_FORMAT))
2957             status = STATUS_INVALID_PARAMETER;
2958         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2959         else status = CDROM_ReadQChannel(dev, fd, lpInBuffer, lpOutBuffer);
2960         break;
2961
2962     case IOCTL_CDROM_READ_TOC:
2963         sz = sizeof(CDROM_TOC);
2964         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2965         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2966         else status = CDROM_ReadTOC(dev, fd, lpOutBuffer);
2967         break;
2968
2969 /* EPP     case IOCTL_CDROM_READ_TOC_EX: */
2970
2971     case IOCTL_CDROM_PAUSE_AUDIO:
2972         sz = 0;
2973         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2974             status = STATUS_INVALID_PARAMETER;
2975         else status = CDROM_PauseAudio(fd);
2976         break;
2977     case IOCTL_CDROM_PLAY_AUDIO_MSF:
2978         sz = 0;
2979         if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2980         else if (nInBufferSize < sizeof(CDROM_PLAY_AUDIO_MSF)) status = STATUS_BUFFER_TOO_SMALL;
2981         else status = CDROM_PlayAudioMSF(fd, lpInBuffer);
2982         break;
2983     case IOCTL_CDROM_RESUME_AUDIO:
2984         sz = 0;
2985         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2986             status = STATUS_INVALID_PARAMETER;
2987         else status = CDROM_ResumeAudio(fd);
2988         break;
2989     case IOCTL_CDROM_SEEK_AUDIO_MSF:
2990         sz = 0;
2991         if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
2992         else if (nInBufferSize < sizeof(CDROM_SEEK_AUDIO_MSF)) status = STATUS_BUFFER_TOO_SMALL;
2993         else status = CDROM_SeekAudioMSF(dev, fd, lpInBuffer);
2994         break;
2995     case IOCTL_CDROM_STOP_AUDIO:
2996         sz = 0;
2997         CDROM_ClearCacheEntry(dev); /* Maybe intention is to change media */
2998         if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2999             status = STATUS_INVALID_PARAMETER;
3000         else status = CDROM_StopAudio(fd);
3001         break;
3002     case IOCTL_CDROM_GET_VOLUME:
3003         sz = sizeof(VOLUME_CONTROL);
3004         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
3005         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3006         else status = CDROM_GetVolume(fd, lpOutBuffer);
3007         break;
3008     case IOCTL_CDROM_SET_VOLUME:
3009         sz = 0;
3010         CDROM_ClearCacheEntry(dev);
3011         if (lpInBuffer == NULL || nInBufferSize < sizeof(VOLUME_CONTROL) || lpOutBuffer != NULL)
3012             status = STATUS_INVALID_PARAMETER;
3013         else status = CDROM_SetVolume(fd, lpInBuffer);
3014         break;
3015     case IOCTL_CDROM_RAW_READ:
3016         sz = 0;
3017         if (nInBufferSize < sizeof(RAW_READ_INFO)) status = STATUS_INVALID_PARAMETER;
3018         else if (lpOutBuffer == NULL) status = STATUS_BUFFER_TOO_SMALL;
3019         else status = CDROM_RawRead(fd, lpInBuffer, lpOutBuffer,
3020                                     nOutBufferSize, &sz);
3021         break;
3022     case IOCTL_SCSI_GET_ADDRESS:
3023         sz = sizeof(SCSI_ADDRESS);
3024         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
3025         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3026         else status = CDROM_GetAddress(fd, lpOutBuffer);
3027         break;
3028     case IOCTL_SCSI_PASS_THROUGH_DIRECT:
3029         sz = sizeof(SCSI_PASS_THROUGH_DIRECT);
3030         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
3031         else if (nOutBufferSize < sizeof(SCSI_PASS_THROUGH_DIRECT)) status = STATUS_BUFFER_TOO_SMALL;
3032         else status = CDROM_ScsiPassThroughDirect(fd, lpOutBuffer);
3033         break;
3034     case IOCTL_SCSI_PASS_THROUGH:
3035         sz = sizeof(SCSI_PASS_THROUGH);
3036         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
3037         else if (nOutBufferSize < sizeof(SCSI_PASS_THROUGH)) status = STATUS_BUFFER_TOO_SMALL;
3038         else status = CDROM_ScsiPassThrough(fd, lpOutBuffer);
3039         break;
3040     case IOCTL_SCSI_GET_CAPABILITIES:
3041         sz = sizeof(IO_SCSI_CAPABILITIES);
3042         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
3043         else if (nOutBufferSize < sizeof(IO_SCSI_CAPABILITIES)) status = STATUS_BUFFER_TOO_SMALL;
3044         else status = CDROM_ScsiGetCaps(fd, lpOutBuffer);
3045         break;
3046     case IOCTL_DVD_START_SESSION:
3047         sz = sizeof(DVD_SESSION_ID);
3048         if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
3049         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3050         else
3051         {
3052             TRACE("before in 0x%08x out 0x%08x\n",(lpInBuffer)?*(PDVD_SESSION_ID)lpInBuffer:0,
3053                   *(PDVD_SESSION_ID)lpOutBuffer);
3054             status = DVD_StartSession(fd, lpInBuffer, lpOutBuffer);
3055             TRACE("before in 0x%08x out 0x%08x\n",(lpInBuffer)?*(PDVD_SESSION_ID)lpInBuffer:0,
3056                   *(PDVD_SESSION_ID)lpOutBuffer);
3057         }
3058         break;
3059     case IOCTL_DVD_END_SESSION:
3060         sz = sizeof(DVD_SESSION_ID);
3061         if ((lpInBuffer == NULL) ||  (nInBufferSize < sz))status = STATUS_INVALID_PARAMETER;
3062         else status = DVD_EndSession(fd, lpInBuffer);
3063         break;
3064     case IOCTL_DVD_SEND_KEY:
3065         sz = 0;
3066         if (!lpInBuffer ||
3067             (((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength != nInBufferSize))
3068             status = STATUS_INVALID_PARAMETER;
3069         else
3070         {
3071             TRACE("doing DVD_SendKey\n");
3072             status = DVD_SendKey(fd, lpInBuffer);
3073         }
3074         break;
3075     case IOCTL_DVD_READ_KEY:
3076         if (!lpInBuffer ||
3077             (((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength != nInBufferSize))
3078             status = STATUS_INVALID_PARAMETER;
3079         else if (lpInBuffer !=lpOutBuffer) status = STATUS_BUFFER_TOO_SMALL;
3080         else
3081         {
3082             TRACE("doing DVD_READ_KEY\n");
3083             sz = ((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength;
3084             status = DVD_ReadKey(fd, lpInBuffer);
3085         }
3086         break;
3087     case IOCTL_DVD_GET_REGION:
3088         sz = sizeof(DVD_REGION);
3089         if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
3090         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3091         TRACE("doing DVD_Get_REGION\n");
3092         status = DVD_GetRegion(fd, lpOutBuffer);
3093         break;
3094     case IOCTL_DVD_READ_STRUCTURE:
3095         sz = sizeof(DVD_LAYER_DESCRIPTOR);
3096         if (lpInBuffer == NULL || nInBufferSize != sizeof(DVD_READ_STRUCTURE)) status = STATUS_INVALID_PARAMETER;
3097         else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3098         else
3099         {
3100             TRACE("doing DVD_READ_STRUCTURE\n");
3101             status = DVD_ReadStructure(fd, lpInBuffer, lpOutBuffer);
3102         }
3103         break;
3104
3105     case IOCTL_SCSI_GET_INQUIRY_DATA:
3106         sz = INQ_REPLY_LEN;
3107         status = GetInquiryData(fd, lpOutBuffer, nOutBufferSize);
3108         break;
3109
3110     default:
3111         if (needs_close) close( fd );
3112         return STATUS_NOT_SUPPORTED;
3113     }
3114     if (needs_close) close( fd );
3115  error:
3116     piosb->u.Status = status;
3117     piosb->Information = sz;
3118     if (hEvent) NtSetEvent(hEvent, NULL);
3119     return status;
3120 }