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