cdrom.c 97.4 KB
Newer Older
1 2 3 4
/* -*- tab-width: 8; c-basic-offset: 4 -*- */
/* Main file for CD-ROM support
 *
 * Copyright 1994 Martin Ayotte
5
 * Copyright 1999, 2001, 2003 Eric Pouech
6
 * Copyright 2000 Andreas Mohr
7
 * Copyright 2005 Ivan Leo Puoti
8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 28

#include <errno.h>
#include <string.h>
29
#include <stdarg.h>
30
#include <stdio.h>
31 32 33
#ifdef HAVE_IO_H
# include <io.h>
#endif
34 35 36
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
37
#include <fcntl.h>
38 39 40
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
41 42
#include <sys/types.h>

Alexandre Julliard's avatar
Alexandre Julliard committed
43 44 45
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
46 47 48
#ifdef HAVE_SCSI_SG_H
# include <scsi/sg.h>
#endif
49 50 51
#ifdef HAVE_SCSI_SCSI_H
# include <scsi/scsi.h>
# undef REASSIGN_BLOCKS  /* avoid conflict with winioctl.h */
52
# undef FAILED           /* avoid conflict with winerror.h */
53
#endif
54 55 56
#ifdef HAVE_SCSI_SCSI_IOCTL_H
# include <scsi/scsi_ioctl.h>
#endif
57 58 59 60 61 62
#ifdef HAVE_LINUX_MAJOR_H
# include <linux/major.h>
#endif
#ifdef HAVE_LINUX_HDREG_H
# include <linux/hdreg.h>
#endif
63 64 65
#ifdef HAVE_LINUX_PARAM_H
# include <linux/param.h>
#endif
66 67 68 69 70 71 72 73 74
#ifdef HAVE_LINUX_CDROM_H
# include <linux/cdrom.h>
#endif
#ifdef HAVE_LINUX_UCDROM_H
# include <linux/ucdrom.h>
#endif
#ifdef HAVE_SYS_CDIO_H
# include <sys/cdio.h>
#endif
75 76 77
#ifdef HAVE_SYS_SCSIIO_H
# include <sys/scsiio.h>
#endif
78

79
#ifdef HAVE_IOKIT_IOKITLIB_H
80
# include <libkern/OSByteOrder.h>
81 82 83 84
# include <sys/disk.h>
# include <IOKit/IOKitLib.h>
# include <IOKit/storage/IOMedia.h>
# include <IOKit/storage/IOCDMediaBSDClient.h>
85
# include <IOKit/storage/IODVDMediaBSDClient.h>
86
# include <IOKit/scsi/SCSITask.h>
87 88
# include <IOKit/scsi/SCSICmds_REQUEST_SENSE_Defs.h>
# define SENSEBUFLEN kSenseDefaultSize
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

typedef struct
{
    uint32_t attribute;
    uint32_t timeout;
    uint32_t response;
    uint32_t status;
    uint8_t direction;
    uint8_t cdbSize;
    uint8_t reserved0144[2];
    uint8_t cdb[16];
    void* buffer;
    uint64_t bufferSize;
    void* sense;
    uint64_t senseLen;
} dk_scsi_command_t;

106 107 108 109 110 111 112 113
typedef struct
{
    uint64_t bus;
    uint64_t port;
    uint64_t target;
    uint64_t lun;
} dk_scsi_identify_t;

114
#define DKIOCSCSICOMMAND _IOWR('d', 253, dk_scsi_command_t)
115
#define DKIOCSCSIIDENTIFY _IOR('d', 254, dk_scsi_identify_t)
116

117 118
#endif

119 120
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
121
#include "ntstatus.h"
122
#define WIN32_NO_STATUS
123
#include "windef.h"
124
#include "winternl.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
125 126 127
#include "winioctl.h"
#include "ntddstor.h"
#include "ntddcdrm.h"
128
#include "ddk/ntddcdvd.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
129
#include "ntddscsi.h"
130 131 132
#include "ntdll_misc.h"
#include "wine/server.h"
#include "wine/library.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
133 134
#include "wine/debug.h"

135 136
WINE_DEFAULT_DEBUG_CHANNEL(cdrom);

137 138 139 140
/* Non-Linux systems do not have linux/cdrom.h and the like, and thus
   lack the following constants. */

#ifndef CD_SECS
141
# define CD_SECS              60 /* seconds per minute */
142 143
#endif
#ifndef CD_FRAMES
144
# define CD_FRAMES            75 /* frames per second */
145
#endif
146

147 148 149 150 151 152
#ifdef WORDS_BIGENDIAN
#define GET_BE_DWORD(x) (x)
#else
#define GET_BE_DWORD(x) RtlUlongByteSwap(x)
#endif

153 154 155 156 157
static const struct iocodexs
{
  DWORD code;
  const char *codex;
} iocodextable[] = {
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
#define X(x) { x, #x },
X(IOCTL_CDROM_CHECK_VERIFY)
X(IOCTL_CDROM_CURRENT_POSITION)
X(IOCTL_CDROM_DISK_TYPE)
X(IOCTL_CDROM_GET_CONTROL)
X(IOCTL_CDROM_GET_DRIVE_GEOMETRY)
X(IOCTL_CDROM_GET_VOLUME)
X(IOCTL_CDROM_LOAD_MEDIA)
X(IOCTL_CDROM_MEDIA_CATALOG)
X(IOCTL_CDROM_MEDIA_REMOVAL)
X(IOCTL_CDROM_PAUSE_AUDIO)
X(IOCTL_CDROM_PLAY_AUDIO_MSF)
X(IOCTL_CDROM_RAW_READ)
X(IOCTL_CDROM_READ_Q_CHANNEL)
X(IOCTL_CDROM_READ_TOC)
X(IOCTL_CDROM_RESUME_AUDIO)
X(IOCTL_CDROM_SEEK_AUDIO_MSF)
X(IOCTL_CDROM_SET_VOLUME)
X(IOCTL_CDROM_STOP_AUDIO)
X(IOCTL_CDROM_TRACK_ISRC)
X(IOCTL_DISK_MEDIA_REMOVAL)
X(IOCTL_DVD_END_SESSION)
X(IOCTL_DVD_GET_REGION)
X(IOCTL_DVD_READ_KEY)
X(IOCTL_DVD_READ_STRUCTURE)
X(IOCTL_DVD_SEND_KEY)
X(IOCTL_DVD_START_SESSION)
X(IOCTL_SCSI_GET_ADDRESS)
X(IOCTL_SCSI_GET_CAPABILITIES)
187
X(IOCTL_SCSI_GET_INQUIRY_DATA)
188 189 190
X(IOCTL_SCSI_PASS_THROUGH)
X(IOCTL_SCSI_PASS_THROUGH_DIRECT)
X(IOCTL_STORAGE_CHECK_VERIFY)
191
X(IOCTL_STORAGE_CHECK_VERIFY2)
192 193 194
X(IOCTL_STORAGE_EJECTION_CONTROL)
X(IOCTL_STORAGE_EJECT_MEDIA)
X(IOCTL_STORAGE_GET_DEVICE_NUMBER)
195 196
X(IOCTL_STORAGE_GET_MEDIA_TYPES)
X(IOCTL_STORAGE_GET_MEDIA_TYPES_EX)
197 198 199 200
X(IOCTL_STORAGE_LOAD_MEDIA)
X(IOCTL_STORAGE_MEDIA_REMOVAL)
X(IOCTL_STORAGE_RESET_DEVICE)
#undef X
201 202 203
};
static const char *iocodex(DWORD code)
{
204
   unsigned int i;
205 206 207 208 209 210 211 212
   static char buffer[25];
   for(i=0; i<sizeof(iocodextable)/sizeof(struct iocodexs); i++)
      if (code==iocodextable[i].code)
	 return iocodextable[i].codex;
   sprintf(buffer, "IOCTL_CODE_%x", (int)code);
   return buffer;
}

213 214
#define INQ_REPLY_LEN 36
#define INQ_CMD_LEN 6
215

216 217 218 219 220
#define FRAME_OF_ADDR(a) (((int)(a)[1] * CD_SECS + (a)[2]) * CD_FRAMES + (a)[3])
#define FRAME_OF_MSF(a) (((int)(a).M * CD_SECS + (a).S) * CD_FRAMES + (a).F)
#define FRAME_OF_TOC(toc, idx)  FRAME_OF_ADDR((toc).TrackData[idx - (toc).FirstTrack].Address)
#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;}

221
/* The documented format of DVD_LAYER_DESCRIPTOR is wrong. Even the format in the
222 223 224
 * DDK's header is wrong. There are four bytes at the start  defined by
 * MMC-5. The first two are the size of the structure in big-endian order as
 * defined by MMC-5. The other two are reserved.
225 226 227
 */
typedef struct
{
228 229
    UCHAR DataLength[2];
    UCHAR Reserved0[2];
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    UCHAR BookVersion : 4;
    UCHAR BookType : 4;
    UCHAR MinimumRate : 4;
    UCHAR DiskSize : 4;
    UCHAR LayerType : 4;
    UCHAR TrackPath : 1;
    UCHAR NumberOfLayers : 2;
    UCHAR Reserved1 : 1;
    UCHAR TrackDensity : 4;
    UCHAR LinearDensity : 4;
    ULONG StartingDataSector;
    ULONG EndDataSector;
    ULONG EndLayerZeroSector;
    UCHAR Reserved5 : 7;
    UCHAR BCAFlag : 1;
    UCHAR Reserved6;
} internal_dvd_layer_descriptor;


249
static NTSTATUS CDROM_ReadTOC(int, int, CDROM_TOC*);
250
static NTSTATUS CDROM_GetStatusCode(int);
251 252


Alexandre Julliard's avatar
Alexandre Julliard committed
253 254 255 256 257 258 259 260 261
#ifdef linux

# ifndef IDE6_MAJOR
#  define IDE6_MAJOR 88
# endif
# ifndef IDE7_MAJOR
#  define IDE7_MAJOR 89
# endif

Alexandre Julliard's avatar
Alexandre Julliard committed
262
# ifdef CDROM_SEND_PACKET
Alexandre Julliard's avatar
Alexandre Julliard committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
/* structure for CDROM_PACKET_COMMAND ioctl */
/* not all Linux versions have all the fields, so we define the
 * structure ourselves to make sure */
struct linux_cdrom_generic_command
{
    unsigned char          cmd[CDROM_PACKET_SIZE];
    unsigned char         *buffer;
    unsigned int           buflen;
    int                    stat;
    struct request_sense  *sense;
    unsigned char          data_direction;
    int                    quiet;
    int                    timeout;
    void                  *reserved[1];
};
Alexandre Julliard's avatar
Alexandre Julliard committed
278
# endif  /* CDROM_SEND_PACKET */
Alexandre Julliard's avatar
Alexandre Julliard committed
279 280 281

#endif  /* linux */

282
/* FIXME: this is needed because we can't open simultaneously several times /dev/cdrom
283
 * this should be removed when a proper device interface is implemented
284 285 286 287
 * 
 * (WS) We need this to keep track of current position and to safely
 * detect media changes. Besides this should provide a great speed up
 * for toc inquiries.
288 289
 */
struct cdrom_cache {
290 291 292 293
    dev_t       device;
    ino_t       inode;
    char        toc_good; /* if false, will reread TOC from disk */
    CDROM_TOC   toc;
294
    SUB_Q_CURRENT_POSITION CurrentPosition;
295
};
296 297 298 299 300 301
/* who has more than 5 cdroms on his/her machine ?? */
/* FIXME: this should grow depending on the number of cdroms we install/configure 
 * at startup
 */
#define MAX_CACHE_ENTRIES       5
static struct cdrom_cache cdrom_cache[MAX_CACHE_ENTRIES];
302

303 304
static RTL_CRITICAL_SECTION cache_section;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
305 306 307
{
    0, 0, &cache_section,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
308
      0, 0, { (DWORD_PTR)(__FILE__ ": cache_section") }
309
};
310
static RTL_CRITICAL_SECTION cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
311

312 313 314 315 316 317 318 319 320 321
/* Proposed media change function: not really needed at this time */
/* This is a 1 or 0 type of function */
#if 0
static int CDROM_MediaChanged(int dev)
{
   int i;

   struct cdrom_tochdr	hdr;
   struct cdrom_tocentry entry;

322
   if (dev < 0 || dev >= MAX_CACHE_ENTRIES)
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
      return 0;
   if ( ioctl(cdrom_cache[dev].fd, CDROMREADTOCHDR, &hdr) == -1 )
      return 0;

   if ( memcmp(&hdr, &cdrom_cache[dev].hdr, sizeof(struct cdrom_tochdr)) )
      return 1;

   for (i=hdr.cdth_trk0; i<=hdr.cdth_trk1+1; i++)
   {
      if (i == hdr.cdth_trk1 + 1)
      {
	 entry.cdte_track = CDROM_LEADOUT;
      } else {
         entry.cdte_track = i;
      }
      entry.cdte_format = CDROM_MSF;
      if ( ioctl(cdrom_cache[dev].fd, CDROMREADTOCENTRY, &entry) == -1)
	 return 0;
      if ( memcmp(&entry, cdrom_cache[dev].entry+i-hdr.cdth_trk0,
			      sizeof(struct cdrom_tocentry)) )
	 return 1;
   }
   return 0;
}
#endif

349 350

/******************************************************************
351
 *		get_parent_device
352
 *
353
 * On Mac OS, get the device for the whole disk from a fd that points to a partition.
354 355 356 357
 * This is ugly and inefficient, but we have no choice since the partition fd doesn't
 * support the eject ioctl.
 */
#ifdef __APPLE__
358
static NTSTATUS get_parent_device( int fd, char *name, size_t len )
359
{
360
    NTSTATUS status = STATUS_NO_SUCH_FILE;
361
    struct stat st;
362
    int i;
363 364 365 366
    io_service_t service;
    CFMutableDictionaryRef dict;
    CFTypeRef val;

367 368
    if (fstat( fd, &st ) == -1) return FILE_GetNtStatus();
    if (!S_ISCHR( st.st_mode )) return STATUS_OBJECT_TYPE_MISMATCH;
369 370 371

    /* create a dictionary with the right major/minor numbers */

372
    if (!(dict = IOServiceMatching( kIOMediaClass ))) return STATUS_NO_MEMORY;
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

    i = major( st.st_rdev );
    val = CFNumberCreate( NULL, kCFNumberIntType, &i );
    CFDictionaryAddValue( dict, CFSTR( "BSD Major" ), val );
    CFRelease( val );

    i = minor( st.st_rdev );
    val = CFNumberCreate( NULL, kCFNumberIntType, &i );
    CFDictionaryAddValue( dict, CFSTR( "BSD Minor" ), val );
    CFRelease( val );

    CFDictionaryAddValue( dict, CFSTR("Removable"), kCFBooleanTrue );

    service = IOServiceGetMatchingService( kIOMasterPortDefault, dict );

    /* now look for the parent that has the "Whole" attribute set to TRUE */

    while (service)
    {
        io_service_t parent = 0;
        CFBooleanRef whole;
        CFStringRef str;
        int ok;

        if (!IOObjectConformsTo( service, kIOMediaClass ))
            goto next;
        if (!(whole = IORegistryEntryCreateCFProperty( service, CFSTR("Whole"), NULL, 0 )))
            goto next;
        ok = (whole == kCFBooleanTrue);
        CFRelease( whole );
        if (!ok) goto next;

        if ((str = IORegistryEntryCreateCFProperty( service, CFSTR("BSD Name"), NULL, 0 )))
        {
            strcpy( name, "/dev/r" );
408
            CFStringGetCString( str, name + 6, len - 6, kCFStringEncodingUTF8 );
409
            CFRelease( str );
410
            status = STATUS_SUCCESS;
411 412 413 414 415 416 417 418 419
        }
        IOObjectRelease( service );
        break;

next:
        IORegistryEntryGetParentEntry( service, kIOServicePlane, &parent );
        IOObjectRelease( service );
        service = parent;
    }
420
    return status;
421 422 423 424
}
#endif


425 426 427 428 429 430 431
/******************************************************************
 *		CDROM_SyncCache                          [internal]
 *
 * Read the TOC in and store it in the cdrom_cache structure.
 * Further requests for the TOC will be copied from the cache
 * unless certain events like disk ejection is detected, in which
 * case the cache will be cleared, causing it to be resynced.
432
 * The cache section must be held by caller.
433
 */
434
static NTSTATUS CDROM_SyncCache(int dev, int fd)
435 436
{
#ifdef linux
437
   int i, tsz;
438 439
   struct cdrom_tochdr		hdr;
   struct cdrom_tocentry	entry;
440

441 442 443
   CDROM_TOC *toc = &cdrom_cache[dev].toc;
   cdrom_cache[dev].toc_good = 0;

444
   if (ioctl(fd, CDROMREADTOCHDR, &hdr) == -1)
445 446
   {
      WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
447
      return FILE_GetNtStatus();
448 449 450 451 452 453 454 455 456
   }

   toc->FirstTrack = hdr.cdth_trk0;
   toc->LastTrack  = hdr.cdth_trk1;
   tsz = sizeof(toc->FirstTrack) + sizeof(toc->LastTrack)
       + sizeof(TRACK_DATA) * (toc->LastTrack-toc->FirstTrack+2);
   toc->Length[0] = tsz >> 8;
   toc->Length[1] = tsz;

457 458
   TRACE("caching toc from=%d to=%d\n", toc->FirstTrack, toc->LastTrack );

459 460 461 462 463 464 465
   for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
   {
     if (i == toc->LastTrack + 1)
       entry.cdte_track = CDROM_LEADOUT;
     else 
       entry.cdte_track = i;
     entry.cdte_format = CDROM_MSF;
466 467
     if (ioctl(fd, CDROMREADTOCENTRY, &entry) == -1)
     {
468
       WARN("error read entry (%s)\n", strerror(errno));
469
       return FILE_GetNtStatus();
470 471 472 473 474 475 476 477 478
     }
     toc->TrackData[i - toc->FirstTrack].Control = entry.cdte_ctrl;
     toc->TrackData[i - toc->FirstTrack].Adr = entry.cdte_adr;
     /* marking last track with leadout value as index */
     toc->TrackData[i - toc->FirstTrack].TrackNumber = entry.cdte_track;
     toc->TrackData[i - toc->FirstTrack].Address[0] = 0;
     toc->TrackData[i - toc->FirstTrack].Address[1] = entry.cdte_addr.msf.minute;
     toc->TrackData[i - toc->FirstTrack].Address[2] = entry.cdte_addr.msf.second;
     toc->TrackData[i - toc->FirstTrack].Address[3] = entry.cdte_addr.msf.frame;
479 480 481 482
   }
   cdrom_cache[dev].toc_good = 1;
   return STATUS_SUCCESS;

483
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
484

485 486 487 488 489 490 491 492 493
   int i, tsz;
   struct ioc_toc_header hdr;
   struct ioc_read_toc_entry entry;
   struct cd_toc_entry toc_buffer;

   CDROM_TOC *toc = &cdrom_cache[dev].toc;
   cdrom_cache[dev].toc_good = 0;

    if (ioctl(fd, CDIOREADTOCHEADER, &hdr) == -1)
494 495
    {
        WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
496
        return FILE_GetNtStatus();
497 498 499 500 501 502 503
    }
    toc->FirstTrack = hdr.starting_track;
    toc->LastTrack  = hdr.ending_track;
    tsz = sizeof(toc->FirstTrack) + sizeof(toc->LastTrack)
        + sizeof(TRACK_DATA) * (toc->LastTrack-toc->FirstTrack+2);
    toc->Length[0] = tsz >> 8;
    toc->Length[1] = tsz;
504 505

    TRACE("caching toc from=%d to=%d\n", toc->FirstTrack, toc->LastTrack );
506 507 508 509 510 511 512 513 514 515

    for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
    {
	if (i == toc->LastTrack + 1)
        {
#define LEADOUT 0xaa
	    entry.starting_track = LEADOUT;
        } else {
            entry.starting_track = i;
        }
516
        memset(&toc_buffer, 0, sizeof(toc_buffer));
517 518 519
	entry.address_format = CD_MSF_FORMAT;
	entry.data_len = sizeof(toc_buffer);
	entry.data = &toc_buffer;
520 521
        if (ioctl(fd, CDIOREADTOCENTRYS, &entry) == -1)
        {
522
	    WARN("error read entry (%s)\n", strerror(errno));
523
            return FILE_GetNtStatus();
524 525 526 527 528 529 530 531 532 533 534
	}
        toc->TrackData[i - toc->FirstTrack].Control = toc_buffer.control;
        toc->TrackData[i - toc->FirstTrack].Adr = toc_buffer.addr_type;
        /* marking last track with leadout value as index */
        toc->TrackData[i - toc->FirstTrack].TrackNumber = entry.starting_track;
        toc->TrackData[i - toc->FirstTrack].Address[0] = 0;
        toc->TrackData[i - toc->FirstTrack].Address[1] = toc_buffer.addr.msf.minute;
        toc->TrackData[i - toc->FirstTrack].Address[2] = toc_buffer.addr.msf.second;
        toc->TrackData[i - toc->FirstTrack].Address[3] = toc_buffer.addr.msf.frame;
    }
    cdrom_cache[dev].toc_good = 1;
535
    return STATUS_SUCCESS;
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

#elif defined(__APPLE__)
    int i;
    dk_cd_read_toc_t hdr;
    CDROM_TOC *toc = &cdrom_cache[dev].toc;
    cdrom_cache[dev].toc_good = 0;

    memset( &hdr, 0, sizeof(hdr) );
    hdr.buffer = toc;
    hdr.bufferLength = sizeof(*toc);
    if (ioctl(fd, DKIOCCDREADTOC, &hdr) == -1)
    {
        WARN("(%d) -- Error occurred (%s)!\n", dev, strerror(errno));
        return FILE_GetNtStatus();
    }
    for (i = toc->FirstTrack; i <= toc->LastTrack + 1; i++)
    {
        /* convert address format */
        TRACK_DATA *data = &toc->TrackData[i - toc->FirstTrack];
        DWORD frame = (((DWORD)data->Address[0] << 24) | ((DWORD)data->Address[1] << 16) |
                       ((DWORD)data->Address[2] << 8) | data->Address[3]);
        MSF_OF_FRAME( data->Address[1], frame );
        data->Address[0] = 0;
    }

    cdrom_cache[dev].toc_good = 1;
    return STATUS_SUCCESS;
563
#else
564
    FIXME("not supported on this O/S\n");
565
    return STATUS_NOT_SUPPORTED;
566 567 568 569 570
#endif
}

static void CDROM_ClearCacheEntry(int dev)
{
571
    RtlEnterCriticalSection( &cache_section );
572
    cdrom_cache[dev].toc_good = 0;
573
    RtlLeaveCriticalSection( &cache_section );
574 575 576 577
}



578
/******************************************************************
579
 *		CDROM_GetInterfaceInfo
580
 *
581
 * Determines the ide interface (the number after the ide), and the
582 583
 * number of the device on that interface for ide cdroms (*iface <= 1).
 * Determines the scsi information for scsi cdroms (*iface >= 2).
584
 * Returns false if the info cannot not be obtained.
585
 */
586
static int CDROM_GetInterfaceInfo(int fd, UCHAR* iface, UCHAR* port, UCHAR* device, UCHAR* lun)
587 588
{
#if defined(linux)
589
    struct stat st;
590
    if ( fstat(fd, &st) == -1 || ! S_ISBLK(st.st_mode)) return 0;
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    *port = 0;
    *iface = 0;
    *device = 0;
    *lun = 0;
    switch (major(st.st_rdev)) {
    case IDE0_MAJOR: *iface = 0; break;
    case IDE1_MAJOR: *iface = 1; break;
    case IDE2_MAJOR: *iface = 2; break;
    case IDE3_MAJOR: *iface = 3; break;
    case IDE4_MAJOR: *iface = 4; break;
    case IDE5_MAJOR: *iface = 5; break;
    case IDE6_MAJOR: *iface = 6; break;
    case IDE7_MAJOR: *iface = 7; break;
    default: *port = 1; break;
    }
606

607 608 609 610
    if (*port == 0)
        *device = (minor(st.st_rdev) >> 6);
    else
    {
611
#ifdef SCSI_IOCTL_GET_IDLUN
612
        UINT32 idlun[2];
613
        if (ioctl(fd, SCSI_IOCTL_GET_IDLUN, idlun) != -1)
614
        {
615 616
            *port = (idlun[0] >> 24) & 0xff;
            *iface = ((idlun[0] >> 16) & 0xff) + 2;
617 618 619 620
            *device = idlun[0] & 0xff;
            *lun = (idlun[0] >> 8) & 0xff;
        }
        else
621
#endif
622
        {
623
            WARN("CD-ROM device (%d, %d) not supported\n", major(st.st_rdev), minor(st.st_rdev));
624
            return 0;
625 626
        }
    }
627
    return 1;
628
#elif defined(__NetBSD__)
629 630
    struct scsi_addr addr;
    if (ioctl(fd, SCIOCIDENTIFY, &addr) != -1)
631
    {
632
        switch (addr.type)
633
        {
634 635
        case TYPE_SCSI:
            *port = 1;
636 637 638
            *iface = addr.addr.scsi.scbus;
            *device = addr.addr.scsi.target;
            *lun = addr.addr.scsi.lun;
639 640 641
            return 1;
        case TYPE_ATAPI:
            *port = 0;
642 643 644
            *iface = addr.addr.atapi.atbus;
            *device = addr.addr.atapi.drive;
            *lun = 0;
645
            return 1;
646
        }
647
    }
648
    return 0;
649 650 651 652 653 654 655 656 657 658 659
#elif defined(__APPLE__)
    dk_scsi_identify_t addr;
    if (ioctl(fd, DKIOCSCSIIDENTIFY, &addr) != -1)
    {
       *port = addr.bus;
       *iface = addr.port;
       *device = addr.target;
       *lun = addr.lun;
       return 1;
    }
    return 0;
660
#else
661
    FIXME("not implemented on this O/S\n");
662 663 664 665 666
    return 0;
#endif
}


667 668 669 670
/******************************************************************
 *		CDROM_Open
 *
 */
671
static NTSTATUS CDROM_Open(int fd, int* dev)
672
{
673
    struct stat st;
674
    NTSTATUS ret = STATUS_SUCCESS;
675
    int         empty = -1;
676

677
    fstat(fd, &st);
678

679
    RtlEnterCriticalSection( &cache_section );
680
    for (*dev = 0; *dev < MAX_CACHE_ENTRIES; (*dev)++)
681
    {
682 683 684 685 686 687 688
        if (empty == -1 &&
            cdrom_cache[*dev].device == 0 &&
            cdrom_cache[*dev].inode == 0)
            empty = *dev;
        else if (cdrom_cache[*dev].device == st.st_dev &&
                 cdrom_cache[*dev].inode == st.st_ino)
            break;
689
    }
690
    if (*dev == MAX_CACHE_ENTRIES)
691
    {
692 693 694 695 696 697 698
        if (empty == -1) ret = STATUS_NOT_IMPLEMENTED;
        else
        {
            *dev = empty;
            cdrom_cache[*dev].device  = st.st_dev;
            cdrom_cache[*dev].inode   = st.st_ino;
        }
699
    }
700 701 702 703
    RtlLeaveCriticalSection( &cache_section );

    TRACE("%d, %d\n", *dev, fd);
    return ret;
704 705 706 707 708 709 710
}

/******************************************************************
 *		CDROM_GetStatusCode
 *
 *
 */
711
static NTSTATUS CDROM_GetStatusCode(int io)
712
{
713
    if (io == 0) return STATUS_SUCCESS;
714
    return FILE_GetNtStatus();
715 716
}

717 718 719 720
/******************************************************************
 *		CDROM_GetControl
 *
 */
721
static NTSTATUS CDROM_GetControl(int dev, int fd, CDROM_AUDIO_CONTROL* cac)
722
{
723 724 725 726 727 728 729 730 731
#ifdef __APPLE__
    uint16_t speed;
    int io = ioctl( fd, DKIOCCDGETSPEED, &speed );
    if (io != 0) return CDROM_GetStatusCode( io );
    /* DKIOCCDGETSPEED returns the speed in kilobytes per second,
     * so convert to logical blocks (assumed to be ~2 KB).
     */
    cac->LogicalBlocksPerSecond = speed/2;
#else
732
    cac->LogicalBlocksPerSecond = 1; /* FIXME */
733 734
#endif
    cac->LbaFormat = 0; /* FIXME */
735 736 737
    return  STATUS_NOT_SUPPORTED;
}

738 739 740 741 742
/******************************************************************
 *		CDROM_GetDeviceNumber
 *
 */
static NTSTATUS CDROM_GetDeviceNumber(int dev, STORAGE_DEVICE_NUMBER* devnum)
743
{
744 745 746 747 748
    FIXME( "stub\n" );
    devnum->DeviceType = FILE_DEVICE_DISK;
    devnum->DeviceNumber = 1;
    devnum->PartitionNumber = 1;
    return STATUS_SUCCESS;
749 750
}

751 752 753 754
/******************************************************************
 *		CDROM_GetDriveGeometry
 *
 */
755
static NTSTATUS CDROM_GetDriveGeometry(int dev, int fd, DISK_GEOMETRY* dg)
756
{
757 758 759
  CDROM_TOC     toc;
  NTSTATUS      ret = 0;
  int           fsize = 0;
760

761
  if ((ret = CDROM_ReadTOC(dev, fd, &toc)) != 0) return ret;
762 763 764 765

  fsize = FRAME_OF_TOC(toc, toc.LastTrack+1)
        - FRAME_OF_TOC(toc, 1); /* Total size in frames */
  
766 767
  dg->Cylinders.u.LowPart = fsize / (64 * 32); 
  dg->Cylinders.u.HighPart = 0; 
768 769 770 771 772
  dg->MediaType = RemovableMedia;  
  dg->TracksPerCylinder = 64; 
  dg->SectorsPerTrack = 32;  
  dg->BytesPerSector= 2048; 
  return ret;
773 774
}

775 776 777 778 779 780 781 782 783 784 785 786
/******************************************************************
 *		CDROM_GetMediaType
 *
 */
static NTSTATUS CDROM_GetMediaType(int dev, GET_MEDIA_TYPES* medtype)
{
    FIXME(": faking success\n");
    medtype->DeviceType = FILE_DEVICE_CD_ROM;
    medtype->MediaInfoCount = 0;
    return STATUS_SUCCESS;
}

787 788 789
/**************************************************************************
 *                              CDROM_Reset                     [internal]
 */
790
static NTSTATUS CDROM_ResetAudio(int fd)
791 792
{
#if defined(linux)
793
    return CDROM_GetStatusCode(ioctl(fd, CDROMRESET));
794
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
795
    return CDROM_GetStatusCode(ioctl(fd, CDIOCRESET, NULL));
796
#else
797
    FIXME("not supported on this O/S\n");
798 799
    return STATUS_NOT_SUPPORTED;
#endif
800
}
801 802 803 804 805 806

/******************************************************************
 *		CDROM_SetTray
 *
 *
 */
807
static NTSTATUS CDROM_SetTray(int fd, BOOL doEject)
808 809
{
#if defined(linux)
810
    return CDROM_GetStatusCode(ioctl(fd, doEject ? CDROMEJECT : CDROMCLOSETRAY));
811
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
812 813 814
    return CDROM_GetStatusCode((ioctl(fd, CDIOCALLOW, NULL)) ||
                               (ioctl(fd, doEject ? CDIOCEJECT : CDIOCCLOSE, NULL)) ||
                               (ioctl(fd, CDIOCPREVENT, NULL)));
815 816 817
#elif defined(__APPLE__)
    if (doEject) return CDROM_GetStatusCode( ioctl( fd, DKIOCEJECT, NULL ) );
    else return STATUS_NOT_SUPPORTED;
818
#else
819
    FIXME("not supported on this O/S\n");
820 821 822 823 824 825 826 827 828
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_ControlEjection
 *
 *
 */
829
static NTSTATUS CDROM_ControlEjection(int fd, const PREVENT_MEDIA_REMOVAL* rmv)
830 831
{
#if defined(linux)
832
    return CDROM_GetStatusCode(ioctl(fd, CDROM_LOCKDOOR, rmv->PreventMediaRemoval));
833
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
834
    return CDROM_GetStatusCode(ioctl(fd, (rmv->PreventMediaRemoval) ? CDIOCPREVENT : CDIOCALLOW, NULL));
835
#else
836
    FIXME("not supported on this O/S\n");
837 838 839 840 841 842 843 844 845
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_ReadTOC
 *
 *
 */
846
static NTSTATUS CDROM_ReadTOC(int dev, int fd, CDROM_TOC* toc)
847
{
848
    NTSTATUS       ret = STATUS_NOT_SUPPORTED;
849

850 851 852
    if (dev < 0 || dev >= MAX_CACHE_ENTRIES)
        return STATUS_INVALID_PARAMETER;

853 854 855 856 857 858 859 860
    RtlEnterCriticalSection( &cache_section );
    if (cdrom_cache[dev].toc_good || !(ret = CDROM_SyncCache(dev, fd)))
    {
        *toc = cdrom_cache[dev].toc;
        ret = STATUS_SUCCESS;
    }
    RtlLeaveCriticalSection( &cache_section );
    return ret;
861 862 863 864 865 866 867
}

/******************************************************************
 *		CDROM_GetDiskData
 *
 *
 */
868
static NTSTATUS CDROM_GetDiskData(int dev, int fd, CDROM_DISK_DATA* data)
869 870
{
    CDROM_TOC   toc;
871
    NTSTATUS    ret;
872 873
    int         i;

874
    if ((ret = CDROM_ReadTOC(dev, fd, &toc)) != 0) return ret;
875 876
    data->DiskData = 0;
    for (i = toc.FirstTrack; i <= toc.LastTrack; i++) {
877
        if (toc.TrackData[i-toc.FirstTrack].Control & 0x04)
878 879 880 881
            data->DiskData |= CDROM_DISK_DATA_TRACK;
        else
            data->DiskData |= CDROM_DISK_AUDIO_TRACK;
    }
882
    return STATUS_SUCCESS;
883 884 885 886 887 888 889
}

/******************************************************************
 *		CDROM_ReadQChannel
 *
 *
 */
890
static NTSTATUS CDROM_ReadQChannel(int dev, int fd, const CDROM_SUB_Q_DATA_FORMAT* fmt,
891
                                   SUB_Q_CHANNEL_DATA* data)
892
{
893
    NTSTATUS            ret = STATUS_NOT_SUPPORTED;
894
#ifdef linux
895 896 897 898 899
    SUB_Q_HEADER*       hdr = (SUB_Q_HEADER*)data;
    int                 io;
    struct cdrom_subchnl	sc;
    sc.cdsc_format = CDROM_MSF;

900
    io = ioctl(fd, CDROMSUBCHNL, &sc);
901 902 903 904
    if (io == -1)
    {
	TRACE("opened or no_media (%s)!\n", strerror(errno));
	hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
905
	CDROM_ClearCacheEntry(dev);
906 907 908 909 910 911 912
	goto end;
    }

    hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;

    switch (sc.cdsc_audiostatus) {
    case CDROM_AUDIO_INVALID:
913
	CDROM_ClearCacheEntry(dev);
914 915
	hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
	break;
916
    case CDROM_AUDIO_NO_STATUS:
917
	CDROM_ClearCacheEntry(dev);
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
	hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
	break;
    case CDROM_AUDIO_PLAY:
        hdr->AudioStatus = AUDIO_STATUS_IN_PROGRESS;
        break;
    case CDROM_AUDIO_PAUSED:
        hdr->AudioStatus = AUDIO_STATUS_PAUSED;
        break;
    case CDROM_AUDIO_COMPLETED:
        hdr->AudioStatus = AUDIO_STATUS_PLAY_COMPLETE;
        break;
    case CDROM_AUDIO_ERROR:
        hdr->AudioStatus = AUDIO_STATUS_PLAY_ERROR;
        break;
    default:
	TRACE("status=%02X !\n", sc.cdsc_audiostatus);
        break;
    }
    switch (fmt->Format)
    {
    case IOCTL_CDROM_CURRENT_POSITION:
939
        RtlEnterCriticalSection( &cache_section );
940
	if (hdr->AudioStatus==AUDIO_STATUS_IN_PROGRESS) {
941
          data->CurrentPosition.FormatCode = IOCTL_CDROM_CURRENT_POSITION;
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
          data->CurrentPosition.Control = sc.cdsc_ctrl; 
          data->CurrentPosition.ADR = sc.cdsc_adr; 
          data->CurrentPosition.TrackNumber = sc.cdsc_trk; 
          data->CurrentPosition.IndexNumber = sc.cdsc_ind; 

          data->CurrentPosition.AbsoluteAddress[0] = 0; 
          data->CurrentPosition.AbsoluteAddress[1] = sc.cdsc_absaddr.msf.minute; 
          data->CurrentPosition.AbsoluteAddress[2] = sc.cdsc_absaddr.msf.second;
          data->CurrentPosition.AbsoluteAddress[3] = sc.cdsc_absaddr.msf.frame;
 
          data->CurrentPosition.TrackRelativeAddress[0] = 0; 
          data->CurrentPosition.TrackRelativeAddress[1] = sc.cdsc_reladdr.msf.minute; 
          data->CurrentPosition.TrackRelativeAddress[2] = sc.cdsc_reladdr.msf.second;
          data->CurrentPosition.TrackRelativeAddress[3] = sc.cdsc_reladdr.msf.frame;

	  cdrom_cache[dev].CurrentPosition = data->CurrentPosition;
	}
	else /* not playing */
	{
	  cdrom_cache[dev].CurrentPosition.Header = *hdr; /* Preserve header info */
	  data->CurrentPosition = cdrom_cache[dev].CurrentPosition;
	}
964
        RtlLeaveCriticalSection( &cache_section );
965 966 967 968 969
        break;
    case IOCTL_CDROM_MEDIA_CATALOG:
        data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
        {
            struct cdrom_mcn mcn;
970
            if ((io = ioctl(fd, CDROM_GET_MCN, &mcn)) == -1) goto end;
971 972 973 974 975 976 977 978

            data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
            data->MediaCatalog.Mcval = 0; /* FIXME */
            memcpy(data->MediaCatalog.MediaCatalog, mcn.medium_catalog_number, 14);
            data->MediaCatalog.MediaCatalog[14] = 0;
        }
        break;
    case IOCTL_CDROM_TRACK_ISRC:
979
        FIXME("TrackIsrc: NIY on linux\n");
980 981 982 983 984 985 986 987
        data->TrackIsrc.FormatCode = IOCTL_CDROM_TRACK_ISRC;
        data->TrackIsrc.Tcval = 0;
        io = 0;
        break;
    }

 end:
    ret = CDROM_GetStatusCode(io);
988
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
989 990
    SUB_Q_HEADER*       hdr = (SUB_Q_HEADER*)data;
    int                 io;
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    struct ioc_read_subchannel	read_sc;
    struct cd_sub_channel_info	sc;

    read_sc.address_format = CD_MSF_FORMAT;
    read_sc.track          = 0;
    read_sc.data_len       = sizeof(sc);
    read_sc.data           = &sc;
    switch (fmt->Format)
    {
    case IOCTL_CDROM_CURRENT_POSITION:
        read_sc.data_format    = CD_CURRENT_POSITION;
        break;
    case IOCTL_CDROM_MEDIA_CATALOG:
        read_sc.data_format    = CD_MEDIA_CATALOG;
        break;
    case IOCTL_CDROM_TRACK_ISRC:
        read_sc.data_format    = CD_TRACK_INFO;
1008
        sc.what.track_info.track_number = data->TrackIsrc.Track;
1009 1010
        break;
    }
1011
    io = ioctl(fd, CDIOCREADSUBCHANNEL, &read_sc);
1012 1013 1014
    if (io == -1)
    {
	TRACE("opened or no_media (%s)!\n", strerror(errno));
1015
	CDROM_ClearCacheEntry(dev);
1016 1017 1018 1019 1020 1021 1022 1023
	hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
	goto end;
    }

    hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;

    switch (sc.header.audio_status) {
    case CD_AS_AUDIO_INVALID:
1024
	CDROM_ClearCacheEntry(dev);
1025 1026 1027
	hdr->AudioStatus = AUDIO_STATUS_NOT_SUPPORTED;
	break;
    case CD_AS_NO_STATUS:
1028
	CDROM_ClearCacheEntry(dev);
1029 1030 1031 1032 1033 1034
	hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
        break;
    case CD_AS_PLAY_IN_PROGRESS:
        hdr->AudioStatus = AUDIO_STATUS_IN_PROGRESS;
        break;
    case CD_AS_PLAY_PAUSED:
1035
        hdr->AudioStatus = AUDIO_STATUS_PAUSED;
1036
        break;
1037
    case CD_AS_PLAY_COMPLETED:
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        hdr->AudioStatus = AUDIO_STATUS_PLAY_COMPLETE;
        break;
    case CD_AS_PLAY_ERROR:
        hdr->AudioStatus = AUDIO_STATUS_PLAY_ERROR;
        break;
    default:
	TRACE("status=%02X !\n", sc.header.audio_status);
    }
    switch (fmt->Format)
    {
    case IOCTL_CDROM_CURRENT_POSITION:
1049
        RtlEnterCriticalSection( &cache_section );
1050
	if (hdr->AudioStatus==AUDIO_STATUS_IN_PROGRESS) {
1051
          data->CurrentPosition.FormatCode = IOCTL_CDROM_CURRENT_POSITION;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
          data->CurrentPosition.Control = sc.what.position.control;
          data->CurrentPosition.ADR = sc.what.position.addr_type;
          data->CurrentPosition.TrackNumber = sc.what.position.track_number;
          data->CurrentPosition.IndexNumber = sc.what.position.index_number;

          data->CurrentPosition.AbsoluteAddress[0] = 0;
          data->CurrentPosition.AbsoluteAddress[1] = sc.what.position.absaddr.msf.minute;
          data->CurrentPosition.AbsoluteAddress[2] = sc.what.position.absaddr.msf.second;
          data->CurrentPosition.AbsoluteAddress[3] = sc.what.position.absaddr.msf.frame;
          data->CurrentPosition.TrackRelativeAddress[0] = 0;
          data->CurrentPosition.TrackRelativeAddress[1] = sc.what.position.reladdr.msf.minute;
          data->CurrentPosition.TrackRelativeAddress[2] = sc.what.position.reladdr.msf.second;
          data->CurrentPosition.TrackRelativeAddress[3] = sc.what.position.reladdr.msf.frame;
	  cdrom_cache[dev].CurrentPosition = data->CurrentPosition;
	}
	else { /* not playing */
	  cdrom_cache[dev].CurrentPosition.Header = *hdr; /* Preserve header info */
	  data->CurrentPosition = cdrom_cache[dev].CurrentPosition;
	}
1071
        RtlLeaveCriticalSection( &cache_section );
1072 1073 1074
        break;
    case IOCTL_CDROM_MEDIA_CATALOG:
        data->MediaCatalog.FormatCode = IOCTL_CDROM_MEDIA_CATALOG;
1075 1076
        data->MediaCatalog.Mcval = sc.what.media_catalog.mc_valid;
        memcpy(data->MediaCatalog.MediaCatalog, sc.what.media_catalog.mc_number, 15);
1077 1078
        break;
    case IOCTL_CDROM_TRACK_ISRC:
1079
        data->TrackIsrc.FormatCode = IOCTL_CDROM_TRACK_ISRC;
1080 1081
        data->TrackIsrc.Tcval = sc.what.track_info.ti_valid;
        memcpy(data->TrackIsrc.TrackIsrc, sc.what.track_info.ti_number, 15);
1082 1083 1084 1085 1086
        break;
    }

 end:
    ret = CDROM_GetStatusCode(io);
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
#elif defined(__APPLE__)
    SUB_Q_HEADER* hdr = (SUB_Q_HEADER*)data;
    int io = 0;
    union
    {
        dk_cd_read_mcn_t mcn;
        dk_cd_read_isrc_t isrc;
    } ioc;
    /* We need IOCDAudioControl for IOCTL_CDROM_CURRENT_POSITION */
    if (fmt->Format == IOCTL_CDROM_CURRENT_POSITION)
    {
1098
        FIXME("NIY\n");
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
        return STATUS_NOT_SUPPORTED;
    }
    /* No IOCDAudioControl support; just set the audio status to none */
    hdr->AudioStatus = AUDIO_STATUS_NO_STATUS;
    switch(fmt->Format)
    {
    case IOCTL_CDROM_MEDIA_CATALOG:
        if ((io = ioctl(fd, DKIOCCDREADMCN, &ioc.mcn)) == -1) break;
        memcpy(data->MediaCatalog.MediaCatalog, ioc.mcn.mcn, kCDMCNMaxLength);
        data->MediaCatalog.Mcval = 1;
        break;
    case IOCTL_CDROM_TRACK_ISRC:
        ioc.isrc.track = fmt->Track;
        if ((io = ioctl(fd, DKIOCCDREADISRC, &ioc.isrc)) == -1) break;
        memcpy(data->TrackIsrc.TrackIsrc, ioc.isrc.isrc, kCDISRCMaxLength);
        data->TrackIsrc.Tcval = 1;
        data->TrackIsrc.Track = ioc.isrc.track;
    }
    ret = CDROM_GetStatusCode(io);
1118 1119 1120 1121 1122 1123
#endif
    return ret;
}

/******************************************************************
 *		CDROM_Verify
1124 1125
 *  Implements: IOCTL_STORAGE_CHECK_VERIFY
 *              IOCTL_CDROM_CHECK_VERIFY
1126
 *              IOCTL_DISK_CHECK_VERIFY
1127 1128
 *
 */
1129
static NTSTATUS CDROM_Verify(int dev, int fd)
1130
{
1131 1132 1133 1134 1135 1136 1137 1138
#if defined(linux)
    int ret;

    ret = ioctl(fd,  CDROM_DRIVE_STATUS, NULL);
    if(ret == -1) {
        TRACE("ioctl CDROM_DRIVE_STATUS failed(%s)!\n", strerror(errno));
        return CDROM_GetStatusCode(ret);
    }
1139

1140 1141 1142 1143
    if(ret == CDS_DISC_OK)
        return STATUS_SUCCESS;
    else
        return STATUS_NO_MEDIA_IN_DEVICE;
1144
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1145 1146 1147 1148 1149 1150
    int ret;
    ret = ioctl(fd, CDIOCSTART, NULL);
    if(ret == 0)
        return STATUS_SUCCESS;
    else
        return STATUS_NO_MEDIA_IN_DEVICE;
1151 1152 1153 1154
#elif defined(__APPLE__)
	/* At this point, we know that we have media, because in Mac OS X, the
	 * device file is only created when media is present. */
	return STATUS_SUCCESS;
1155
#else
1156
    FIXME("not supported on this O/S\n");
1157
    return STATUS_NOT_SUPPORTED;
1158
#endif
1159 1160 1161 1162 1163 1164 1165
}

/******************************************************************
 *		CDROM_PlayAudioMSF
 *
 *
 */
1166
static NTSTATUS CDROM_PlayAudioMSF(int fd, const CDROM_PLAY_AUDIO_MSF* audio_msf)
1167
{
1168
    NTSTATUS       ret = STATUS_NOT_SUPPORTED;
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
#ifdef linux
    struct 	cdrom_msf	msf;
    int         io;

    msf.cdmsf_min0   = audio_msf->StartingM;
    msf.cdmsf_sec0   = audio_msf->StartingS;
    msf.cdmsf_frame0 = audio_msf->StartingF;
    msf.cdmsf_min1   = audio_msf->EndingM;
    msf.cdmsf_sec1   = audio_msf->EndingS;
    msf.cdmsf_frame1 = audio_msf->EndingF;

1180
    io = ioctl(fd, CDROMSTART);
1181 1182 1183 1184 1185
    if (io == -1)
    {
	WARN("motor doesn't start !\n");
	goto end;
    }
1186
    io = ioctl(fd, CDROMPLAYMSF, &msf);
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    if (io == -1)
    {
	WARN("device doesn't play !\n");
	goto end;
    }
    TRACE("msf = %d:%d:%d %d:%d:%d\n",
	  msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0,
	  msf.cdmsf_min1, msf.cdmsf_sec1, msf.cdmsf_frame1);
 end:
    ret = CDROM_GetStatusCode(io);
1197
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    struct	ioc_play_msf	msf;
    int         io;

    msf.start_m      = audio_msf->StartingM;
    msf.start_s      = audio_msf->StartingS;
    msf.start_f      = audio_msf->StartingF;
    msf.end_m        = audio_msf->EndingM;
    msf.end_s        = audio_msf->EndingS;
    msf.end_f        = audio_msf->EndingF;

1208
    io = ioctl(fd, CDIOCSTART, NULL);
1209 1210 1211 1212 1213
    if (io == -1)
    {
	WARN("motor doesn't start !\n");
	goto end;
    }
1214
    io = ioctl(fd, CDIOCPLAYMSF, &msf);
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    if (io == -1)
    {
	WARN("device doesn't play !\n");
	goto end;
    }
    TRACE("msf = %d:%d:%d %d:%d:%d\n",
	  msf.start_m, msf.start_s, msf.start_f,
	  msf.end_m,   msf.end_s,   msf.end_f);
end:
    ret = CDROM_GetStatusCode(io);
#endif
    return ret;
}

/******************************************************************
 *		CDROM_SeekAudioMSF
 *
 *
 */
1234
static NTSTATUS CDROM_SeekAudioMSF(int dev, int fd, const CDROM_SEEK_AUDIO_MSF* audio_msf)
1235
{
1236 1237 1238
    CDROM_TOC toc;
    int i, io, frame;
    SUB_Q_CURRENT_POSITION *cp;
1239 1240
#if defined(linux)
    struct cdrom_msf0	msf;
1241
    struct cdrom_subchnl sc;
1242
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1243 1244 1245 1246 1247 1248 1249 1250 1251
    struct ioc_play_msf	msf;
    struct ioc_read_subchannel	read_sc;
    struct cd_sub_channel_info	sc;
    int final_frame;
#endif

    /* Use the information on the TOC to compute the new current
     * position, which is shadowed on the cache. [Portable]. */
    frame = FRAME_OF_MSF(*audio_msf);
1252 1253 1254

    if ((io = CDROM_ReadTOC(dev, fd, &toc)) != 0) return io;

1255 1256 1257 1258 1259
    for(i=toc.FirstTrack;i<=toc.LastTrack+1;i++)
      if (FRAME_OF_TOC(toc,i)>frame) break;
    if (i <= toc.FirstTrack || i > toc.LastTrack+1)
      return STATUS_INVALID_PARAMETER;
    i--;
1260 1261
    RtlEnterCriticalSection( &cache_section );
    cp = &cdrom_cache[dev].CurrentPosition;
1262
    cp->FormatCode = IOCTL_CDROM_CURRENT_POSITION; 
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
    cp->Control = toc.TrackData[i-toc.FirstTrack].Control; 
    cp->ADR = toc.TrackData[i-toc.FirstTrack].Adr; 
    cp->TrackNumber = toc.TrackData[i-toc.FirstTrack].TrackNumber;
    cp->IndexNumber = 0; /* FIXME: where do they keep these? */
    cp->AbsoluteAddress[0] = 0; 
    cp->AbsoluteAddress[1] = toc.TrackData[i-toc.FirstTrack].Address[1];
    cp->AbsoluteAddress[2] = toc.TrackData[i-toc.FirstTrack].Address[2];
    cp->AbsoluteAddress[3] = toc.TrackData[i-toc.FirstTrack].Address[3];
    frame -= FRAME_OF_TOC(toc,i);
    cp->TrackRelativeAddress[0] = 0;
    MSF_OF_FRAME(cp->TrackRelativeAddress[1], frame); 
1274
    RtlLeaveCriticalSection( &cache_section );
1275 1276 1277 1278

    /* If playing, then issue a seek command, otherwise do nothing */
#ifdef linux
    sc.cdsc_format = CDROM_MSF;
1279

1280
    io = ioctl(fd, CDROMSUBCHNL, &sc);
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    if (io == -1)
    {
	TRACE("opened or no_media (%s)!\n", strerror(errno));
	CDROM_ClearCacheEntry(dev);
        return CDROM_GetStatusCode(io);
    }
    if (sc.cdsc_audiostatus==CDROM_AUDIO_PLAY)
    {
      msf.minute = audio_msf->M;
      msf.second = audio_msf->S;
      msf.frame  = audio_msf->F;
1292
      return CDROM_GetStatusCode(ioctl(fd, CDROMSEEK, &msf));
1293
    }
1294
    return STATUS_SUCCESS;
1295
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1296 1297 1298 1299 1300 1301
    read_sc.address_format = CD_MSF_FORMAT;
    read_sc.track          = 0;
    read_sc.data_len       = sizeof(sc);
    read_sc.data           = &sc;
    read_sc.data_format    = CD_CURRENT_POSITION;

1302
    io = ioctl(fd, CDIOCREADSUBCHANNEL, &read_sc);
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
    if (io == -1)
    {
	TRACE("opened or no_media (%s)!\n", strerror(errno));
	CDROM_ClearCacheEntry(dev);
        return CDROM_GetStatusCode(io);
    }
    if (sc.header.audio_status==CD_AS_PLAY_IN_PROGRESS) 
    {

      msf.start_m      = audio_msf->M;
      msf.start_s      = audio_msf->S;
      msf.start_f      = audio_msf->F;
      final_frame = FRAME_OF_TOC(toc,toc.LastTrack+1)-1;
      MSF_OF_FRAME(msf.end_m, final_frame);

1318
      return CDROM_GetStatusCode(ioctl(fd, CDIOCPLAYMSF, &msf));
1319
    }
1320
    return STATUS_SUCCESS;
1321
#else
1322
    FIXME("not supported on this O/S\n");
1323 1324 1325 1326 1327 1328 1329 1330 1331
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_PauseAudio
 *
 *
 */
1332
static NTSTATUS CDROM_PauseAudio(int fd)
1333 1334
{
#if defined(linux)
1335
    return CDROM_GetStatusCode(ioctl(fd, CDROMPAUSE));
1336
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1337
    return CDROM_GetStatusCode(ioctl(fd, CDIOCPAUSE, NULL));
1338
#else
1339
    FIXME(": not supported on this O/S\n");
1340 1341 1342 1343 1344 1345 1346 1347 1348
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_ResumeAudio
 *
 *
 */
1349
static NTSTATUS CDROM_ResumeAudio(int fd)
1350 1351
{
#if defined(linux)
1352
    return CDROM_GetStatusCode(ioctl(fd, CDROMRESUME));
1353
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1354
    return CDROM_GetStatusCode(ioctl(fd, CDIOCRESUME, NULL));
1355
#else
1356
    FIXME("not supported on this O/S\n");
1357 1358 1359 1360 1361 1362 1363 1364 1365
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_StopAudio
 *
 *
 */
1366
static NTSTATUS CDROM_StopAudio(int fd)
1367 1368
{
#if defined(linux)
1369
    return CDROM_GetStatusCode(ioctl(fd, CDROMSTOP));
1370
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1371
    return CDROM_GetStatusCode(ioctl(fd, CDIOCSTOP, NULL));
1372
#else
1373
    FIXME("not supported on this O/S\n");
1374 1375 1376 1377 1378 1379 1380 1381 1382
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_GetVolume
 *
 *
 */
1383
static NTSTATUS CDROM_GetVolume(int fd, VOLUME_CONTROL* vc)
1384 1385 1386 1387
{
#if defined(linux)
    struct cdrom_volctrl volc;
    int io;
1388

1389
    io = ioctl(fd, CDROMVOLREAD, &volc);
1390 1391 1392 1393 1394 1395 1396 1397
    if (io != -1)
    {
        vc->PortVolume[0] = volc.channel0;
        vc->PortVolume[1] = volc.channel1;
        vc->PortVolume[2] = volc.channel2;
        vc->PortVolume[3] = volc.channel3;
    }
    return CDROM_GetStatusCode(io);
1398
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1399 1400
    struct  ioc_vol     volc;
    int io;
1401

1402
    io = ioctl(fd, CDIOCGETVOL, &volc);
1403 1404 1405 1406 1407 1408
    if (io != -1)
    {
        vc->PortVolume[0] = volc.vol[0];
        vc->PortVolume[1] = volc.vol[1];
        vc->PortVolume[2] = volc.vol[2];
        vc->PortVolume[3] = volc.vol[3];
1409
    }
1410 1411
    return CDROM_GetStatusCode(io);
#else
1412
    FIXME("not supported on this O/S\n");
1413 1414 1415 1416 1417 1418 1419 1420 1421
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_SetVolume
 *
 *
 */
1422
static NTSTATUS CDROM_SetVolume(int fd, const VOLUME_CONTROL* vc)
1423 1424 1425 1426 1427 1428 1429 1430
{
#if defined(linux)
    struct cdrom_volctrl volc;

    volc.channel0 = vc->PortVolume[0];
    volc.channel1 = vc->PortVolume[1];
    volc.channel2 = vc->PortVolume[2];
    volc.channel3 = vc->PortVolume[3];
1431

1432
    return CDROM_GetStatusCode(ioctl(fd, CDROMVOLCTRL, &volc));
1433
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1434 1435 1436 1437 1438 1439 1440
    struct  ioc_vol     volc;

    volc.vol[0] = vc->PortVolume[0];
    volc.vol[1] = vc->PortVolume[1];
    volc.vol[2] = vc->PortVolume[2];
    volc.vol[3] = vc->PortVolume[3];

1441
    return CDROM_GetStatusCode(ioctl(fd, CDIOCSETVOL, &volc));
1442
#else
1443
    FIXME(": not supported on this O/S\n");
1444 1445 1446 1447 1448 1449 1450
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		CDROM_RawRead
 *
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
 * Some features of this IOCTL are rather poorly documented and
 * not really intuitive either:
 *
 *   1. Although the DiskOffset parameter is meant to be a
 *      byte offset into the disk, it is in fact the sector
 *      number multiplied by 2048 regardless of the actual
 *      sector size.
 *
 *   2. The least significant 11 bits of DiskOffset are ignored.
 *
 *   3. The TrackMode parameter has no effect on the sector
 *      size. The entire raw sector (i.e. 2352 bytes of data)
 *      is always returned. IMO the TrackMode is only used
 *      to check the correct sector type.
1465 1466
 *
 */
1467
static NTSTATUS CDROM_RawRead(int fd, const RAW_READ_INFO* raw, void* buffer, DWORD len, DWORD* sz)
1468
{
1469
    int         ret = STATUS_NOT_SUPPORTED;
1470
    int         io = -1;
1471 1472 1473
#ifdef __APPLE__
    dk_cd_read_t cdrd;
#endif
1474

1475
    TRACE("RAW_READ_INFO: DiskOffset=%i,%i SectorCount=%i TrackMode=%i\n buffer=%p len=%i sz=%p\n",
1476 1477
          raw->DiskOffset.u.HighPart, raw->DiskOffset.u.LowPart, raw->SectorCount, raw->TrackMode, buffer, len, sz);

1478 1479 1480 1481 1482 1483 1484 1485
    if (len < raw->SectorCount * 2352) return STATUS_BUFFER_TOO_SMALL;

#if defined(linux)
    if (raw->DiskOffset.u.HighPart & ~2047) {
        WARN("DiskOffset points to a sector >= 2**32\n");
        return ret;
    }

1486 1487
    switch (raw->TrackMode)
    {
1488 1489
    case YellowMode2:
    case XAForm2:
1490
    {
1491
        DWORD lba = raw->DiskOffset.QuadPart >> 11;
1492
        struct cdrom_msf*       msf;
1493
        PBYTE                   *bp; /* current buffer pointer */
1494
        DWORD i;
1495

1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
        if ((lba + raw->SectorCount) >
            ((1 << 8*sizeof(msf->cdmsf_min0)) * CD_SECS * CD_FRAMES
             - CD_MSF_OFFSET)) {
            WARN("DiskOffset not accessible with MSF\n");
            return ret;
        }

        /* Linux reads only one sector at a time.
         * ioctl CDROMREADRAW takes struct cdrom_msf as an argument
         * on the contrary to what header comments state.
         */
        lba += CD_MSF_OFFSET;
        for (i = 0, bp = buffer; i < raw->SectorCount;
             i++, lba++, bp += 2352)
1510
        {
1511 1512 1513 1514 1515 1516
            msf = (struct cdrom_msf*)bp;
            msf->cdmsf_min0   = lba / CD_FRAMES / CD_SECS;
            msf->cdmsf_sec0   = lba / CD_FRAMES % CD_SECS;
            msf->cdmsf_frame0 = lba % CD_FRAMES;
            io = ioctl(fd, CDROMREADRAW, msf);
            if (io != 0)
1517
            {
1518 1519
                *sz = 2352 * i;
                return CDROM_GetStatusCode(io);
1520
            }
1521
        }
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
        break;
    }

    case CDDA:
    {
        struct cdrom_read_audio cdra;

        cdra.addr.lba = raw->DiskOffset.QuadPart >> 11;
        TRACE("reading at %u\n", cdra.addr.lba);
        cdra.addr_format = CDROM_LBA;
        cdra.nframes = raw->SectorCount;
        cdra.buf = buffer;
        io = ioctl(fd, CDROMREADAUDIO, &cdra);
        break;
    }

1538 1539 1540 1541 1542
    default:
        FIXME("NIY: %d\n", raw->TrackMode);
        return STATUS_INVALID_PARAMETER;
    }
#elif defined(__APPLE__)
1543 1544 1545 1546 1547 1548 1549
    /* Mac OS lets us read multiple parts of the sector at a time.
     * We can read all the sectors in at once, unlike Linux.
     */
    memset(&cdrd, 0, sizeof(cdrd));
    cdrd.offset = (raw->DiskOffset.QuadPart >> 11) * kCDSectorSizeWhole;
    cdrd.buffer = buffer;
    cdrd.bufferLength = raw->SectorCount * kCDSectorSizeWhole;
1550 1551 1552
    switch (raw->TrackMode)
    {
    case YellowMode2:
1553 1554
        cdrd.sectorType = kCDSectorTypeMode2;
        cdrd.sectorArea = kCDSectorAreaSync | kCDSectorAreaHeader | kCDSectorAreaUser;
1555 1556 1557
        break;

    case XAForm2:
1558 1559
        cdrd.sectorType = kCDSectorTypeMode2Form2;
        cdrd.sectorArea = kCDSectorAreaSync | kCDSectorAreaHeader | kCDSectorAreaSubHeader | kCDSectorAreaUser;
1560 1561 1562 1563
        break;

    case CDDA:
        cdrd.sectorType = kCDSectorTypeCDDA;
1564
        cdrd.sectorArea = kCDSectorAreaUser;
1565 1566
        break;

1567 1568 1569
    default:
        FIXME("NIY: %d\n", raw->TrackMode);
        return STATUS_INVALID_PARAMETER;
1570
    }
1571 1572 1573 1574 1575 1576
    io = ioctl(fd, DKIOCCDREAD, &cdrd);
    if (io != 0)
    {
        *sz = cdrd.bufferLength;
        return CDROM_GetStatusCode(io);
    }
1577
#else
1578
    switch (raw->TrackMode)
1579
    {
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
    case YellowMode2:
        FIXME("YellowMode2: NIY\n");
        return ret;
    case XAForm2:
        FIXME("XAForm2: NIY\n");
        return ret;
    case CDDA:
        FIXME("CDDA: NIY\n");
        return ret;
    default:
        FIXME("NIY: %d\n", raw->TrackMode);
        return STATUS_INVALID_PARAMETER;
1592 1593
    }
#endif
1594

1595
    *sz = 2352 * raw->SectorCount;
1596 1597 1598 1599
    ret = CDROM_GetStatusCode(io);
    return ret;
}

1600
/******************************************************************
1601 1602
 *        CDROM_ScsiPassThroughDirect
 *        Implements IOCTL_SCSI_PASS_THROUGH_DIRECT
1603 1604
 *
 */
1605
static NTSTATUS CDROM_ScsiPassThroughDirect(int fd, PSCSI_PASS_THROUGH_DIRECT pPacket)
1606 1607
{
    int ret = STATUS_NOT_SUPPORTED;
1608
#ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1609
    sg_io_hdr_t cmd;
1610
    int io;
1611 1612
#elif defined HAVE_SCSIREQ_T_CMD
    scsireq_t cmd;
1613
    int io;
1614 1615 1616
#elif defined __APPLE__
    dk_scsi_command_t cmd;
    int io;
1617
#endif
1618 1619

    if (pPacket->Length < sizeof(SCSI_PASS_THROUGH_DIRECT))
1620
        return STATUS_BUFFER_TOO_SMALL;
1621

1622
    if (pPacket->CdbLength > 16)
1623 1624
        return STATUS_INVALID_PARAMETER;

1625 1626
#ifdef SENSEBUFLEN
    if (pPacket->SenseInfoLength > SENSEBUFLEN)
1627 1628
        return STATUS_INVALID_PARAMETER;
#elif defined HAVE_REQUEST_SENSE
1629
    if (pPacket->SenseInfoLength > sizeof(struct request_sense))
1630
        return STATUS_INVALID_PARAMETER;
1631
#endif
1632

1633 1634
    if (pPacket->DataTransferLength > 0 && !pPacket->DataBuffer)
        return STATUS_INVALID_PARAMETER;
1635

1636
#ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1637
    RtlZeroMemory(&cmd, sizeof(cmd));
1638

1639 1640 1641 1642 1643 1644
    cmd.interface_id   = 'S';
    cmd.cmd_len        = pPacket->CdbLength;
    cmd.mx_sb_len      = pPacket->SenseInfoLength;
    cmd.dxfer_len      = pPacket->DataTransferLength;
    cmd.dxferp         = pPacket->DataBuffer;
    cmd.cmdp           = pPacket->Cdb;
Mike McCormack's avatar
Mike McCormack committed
1645
    cmd.sbp            = (unsigned char*)pPacket + pPacket->SenseInfoOffset;
1646
    cmd.timeout        = pPacket->TimeOutValue*1000;
1647 1648 1649 1650

    switch (pPacket->DataIn)
    {
    case SCSI_IOCTL_DATA_IN:
1651
        cmd.dxfer_direction = SG_DXFER_FROM_DEV;
1652 1653
        break;
    case SCSI_IOCTL_DATA_OUT:
1654
        cmd.dxfer_direction = SG_DXFER_TO_DEV;
1655
        break;
1656
    case SCSI_IOCTL_DATA_UNSPECIFIED:
1657 1658
        cmd.dxfer_direction = SG_DXFER_NONE;
        break;
1659 1660 1661 1662
    default:
       return STATUS_INVALID_PARAMETER;
    }

1663
    io = ioctl(fd, SG_IO, &cmd);
1664

1665 1666 1667
    pPacket->ScsiStatus         = cmd.status;
    pPacket->DataTransferLength = cmd.resid;
    pPacket->SenseInfoLength    = cmd.sb_len_wr;
1668

1669 1670
    ret = CDROM_GetStatusCode(io);

1671
#elif defined HAVE_SCSIREQ_T_CMD
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696

    memset(&cmd, 0, sizeof(cmd));
    memcpy(&(cmd.cmd), &(pPacket->Cdb), pPacket->CdbLength);

    cmd.cmdlen         = pPacket->CdbLength;
    cmd.databuf        = pPacket->DataBuffer;
    cmd.datalen        = pPacket->DataTransferLength;
    cmd.senselen       = pPacket->SenseInfoLength;
    cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */

    switch (pPacket->DataIn)
    {
    case SCSI_IOCTL_DATA_OUT:
        cmd.flags |= SCCMD_WRITE;
	break;
    case SCSI_IOCTL_DATA_IN:
        cmd.flags |= SCCMD_READ;
	break;
    case SCSI_IOCTL_DATA_UNSPECIFIED:
        cmd.flags = 0;
	break;
    default:
       return STATUS_INVALID_PARAMETER;
    }

1697
    io = ioctl(fd, SCIOCCOMMAND, &cmd);
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718

    switch (cmd.retsts)
    {
    case SCCMD_OK:         break;
    case SCCMD_TIMEOUT:    return STATUS_TIMEOUT;
                           break;
    case SCCMD_BUSY:       return STATUS_DEVICE_BUSY;
                           break;
    case SCCMD_SENSE:      break;
    case SCCMD_UNKNOWN:    return STATUS_UNSUCCESSFUL;
                           break;
    }

    if (pPacket->SenseInfoLength != 0)
    {
        memcpy((char*)pPacket + pPacket->SenseInfoOffset,
	       cmd.sense, pPacket->SenseInfoLength);
    }

    pPacket->ScsiStatus = cmd.status;

1719
    ret = CDROM_GetStatusCode(io);
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777

#elif defined(__APPLE__)

    memset(&cmd, 0, sizeof(cmd));
    memcpy(cmd.cdb, pPacket->Cdb, pPacket->CdbLength);

    cmd.cdbSize        = pPacket->CdbLength;
    cmd.buffer         = pPacket->DataBuffer;
    cmd.bufferSize     = pPacket->DataTransferLength;
    cmd.sense          = (char*)pPacket + pPacket->SenseInfoOffset;
    cmd.senseLen       = pPacket->SenseInfoLength;
    cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */

    switch (pPacket->DataIn)
    {
    case SCSI_IOCTL_DATA_OUT:
        cmd.direction = kSCSIDataTransfer_FromInitiatorToTarget;
	break;
    case SCSI_IOCTL_DATA_IN:
        cmd.direction = kSCSIDataTransfer_FromTargetToInitiator;
	break;
    case SCSI_IOCTL_DATA_UNSPECIFIED:
        cmd.direction = kSCSIDataTransfer_NoDataTransfer;
	break;
    default:
       return STATUS_INVALID_PARAMETER;
    }

    io = ioctl(fd, DKIOCSCSICOMMAND, &cmd);

    if (cmd.response == kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE)
    {
        /* Command failed */
        switch (cmd.status)
        {
        case kSCSITaskStatus_TaskTimeoutOccurred:     return STATUS_TIMEOUT;
                                                      break;
        case kSCSITaskStatus_ProtocolTimeoutOccurred: return STATUS_IO_TIMEOUT;
                                                      break;
        case kSCSITaskStatus_DeviceNotResponding:     return STATUS_DEVICE_BUSY;
                                                      break;
        case kSCSITaskStatus_DeviceNotPresent:
            return STATUS_NO_SUCH_DEVICE;
            break;
        case kSCSITaskStatus_DeliveryFailure:
            return STATUS_DEVICE_PROTOCOL_ERROR;
            break;
        case kSCSITaskStatus_No_Status:
        default:
            return STATUS_UNSUCCESSFUL;
            break;
        }
    }

    if (cmd.status != kSCSITaskStatus_No_Status)
        pPacket->ScsiStatus = cmd.status;

    ret = CDROM_GetStatusCode(io);
1778 1779 1780 1781 1782
#endif
    return ret;
}

/******************************************************************
1783 1784
 *              CDROM_ScsiPassThrough
 *              Implements IOCTL_SCSI_PASS_THROUGH
1785 1786
 *
 */
1787
static NTSTATUS CDROM_ScsiPassThrough(int fd, PSCSI_PASS_THROUGH pPacket)
1788 1789
{
    int ret = STATUS_NOT_SUPPORTED;
1790
#ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1791
    sg_io_hdr_t cmd;
1792
    int io;
1793 1794
#elif defined HAVE_SCSIREQ_T_CMD
    scsireq_t cmd;
1795
    int io;
1796 1797 1798
#elif defined __APPLE__
    dk_scsi_command_t cmd;
    int io;
1799
#endif
1800 1801

    if (pPacket->Length < sizeof(SCSI_PASS_THROUGH))
1802
        return STATUS_BUFFER_TOO_SMALL;
1803

1804
    if (pPacket->CdbLength > 16)
1805 1806
        return STATUS_INVALID_PARAMETER;

1807 1808
#ifdef SENSEBUFLEN
    if (pPacket->SenseInfoLength > SENSEBUFLEN)
1809 1810
        return STATUS_INVALID_PARAMETER;
#elif defined HAVE_REQUEST_SENSE
1811
    if (pPacket->SenseInfoLength > sizeof(struct request_sense))
1812
        return STATUS_INVALID_PARAMETER;
1813
#endif
1814

1815 1816
    if (pPacket->DataTransferLength > 0 && pPacket->DataBufferOffset < sizeof(SCSI_PASS_THROUGH))
        return STATUS_INVALID_PARAMETER;
1817

1818
#ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
1819
    RtlZeroMemory(&cmd, sizeof(cmd));
1820

1821 1822 1823 1824 1825 1826 1827 1828 1829
    cmd.interface_id   = 'S';
    cmd.dxfer_len      = pPacket->DataTransferLength;
    cmd.dxferp         = (char*)pPacket + pPacket->DataBufferOffset;
    cmd.cmd_len        = pPacket->CdbLength;
    cmd.cmdp           = pPacket->Cdb;
    cmd.mx_sb_len      = pPacket->SenseInfoLength;
    cmd.timeout        = pPacket->TimeOutValue*1000;

    if(cmd.mx_sb_len > 0)
Mike McCormack's avatar
Mike McCormack committed
1830
        cmd.sbp = (unsigned char*)pPacket + pPacket->SenseInfoOffset;
1831 1832 1833 1834

    switch (pPacket->DataIn)
    {
    case SCSI_IOCTL_DATA_IN:
1835
        cmd.dxfer_direction = SG_DXFER_FROM_DEV;
1836 1837
                             break;
    case SCSI_IOCTL_DATA_OUT:
1838
        cmd.dxfer_direction = SG_DXFER_TO_DEV;
1839
                             break;
1840
    case SCSI_IOCTL_DATA_UNSPECIFIED:
1841 1842
        cmd.dxfer_direction = SG_DXFER_NONE;
                             break;
1843 1844 1845 1846
    default:
       return STATUS_INVALID_PARAMETER;
    }

1847
    io = ioctl(fd, SG_IO, &cmd);
1848

1849 1850 1851
    pPacket->ScsiStatus         = cmd.status;
    pPacket->DataTransferLength = cmd.resid;
    pPacket->SenseInfoLength    = cmd.sb_len_wr;
1852

1853 1854
    ret = CDROM_GetStatusCode(io);

1855
#elif defined HAVE_SCSIREQ_T_CMD
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888

    memset(&cmd, 0, sizeof(cmd));
    memcpy(&(cmd.cmd), &(pPacket->Cdb), pPacket->CdbLength);

    if ( pPacket->DataBufferOffset > 0x1000 )
    {
        cmd.databuf     = (void*)pPacket->DataBufferOffset;
    }
    else
    {
        cmd.databuf     = (char*)pPacket + pPacket->DataBufferOffset;
    }

    cmd.cmdlen         = pPacket->CdbLength;
    cmd.datalen        = pPacket->DataTransferLength;
    cmd.senselen       = pPacket->SenseInfoLength;
    cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */

    switch (pPacket->DataIn)
    {
    case SCSI_IOCTL_DATA_OUT:
        cmd.flags |= SCCMD_WRITE;
	break;
    case SCSI_IOCTL_DATA_IN:
        cmd.flags |= SCCMD_READ;
	break;
    case SCSI_IOCTL_DATA_UNSPECIFIED:
        cmd.flags = 0;
	break;
    default:
       return STATUS_INVALID_PARAMETER;
    }

1889
    io = ioctl(fd, SCIOCCOMMAND, &cmd);
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910

    switch (cmd.retsts)
    {
    case SCCMD_OK:         break;
    case SCCMD_TIMEOUT:    return STATUS_TIMEOUT;
                           break;
    case SCCMD_BUSY:       return STATUS_DEVICE_BUSY;
                           break;
    case SCCMD_SENSE:      break;
    case SCCMD_UNKNOWN:    return STATUS_UNSUCCESSFUL;
                           break;
    }

    if (pPacket->SenseInfoLength != 0)
    {
        memcpy((char*)pPacket + pPacket->SenseInfoOffset,
	       cmd.sense, pPacket->SenseInfoLength);
    }

    pPacket->ScsiStatus = cmd.status;

1911
    ret = CDROM_GetStatusCode(io);
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972

#elif defined(__APPLE__)

    memset(&cmd, 0, sizeof(cmd));
    memcpy(cmd.cdb, pPacket->Cdb, pPacket->CdbLength);

    cmd.cdbSize        = pPacket->CdbLength;
    cmd.buffer         = (char*)pPacket + pPacket->DataBufferOffset;
    cmd.bufferSize     = pPacket->DataTransferLength;
    cmd.sense          = (char*)pPacket + pPacket->SenseInfoOffset;
    cmd.senseLen       = pPacket->SenseInfoLength;
    cmd.timeout        = pPacket->TimeOutValue*1000; /* in milliseconds */

    switch (pPacket->DataIn)
    {
    case SCSI_IOCTL_DATA_OUT:
        cmd.direction = kSCSIDataTransfer_FromInitiatorToTarget;
	break;
    case SCSI_IOCTL_DATA_IN:
        cmd.direction = kSCSIDataTransfer_FromTargetToInitiator;
	break;
    case SCSI_IOCTL_DATA_UNSPECIFIED:
        cmd.direction = kSCSIDataTransfer_NoDataTransfer;
	break;
    default:
       return STATUS_INVALID_PARAMETER;
    }

    io = ioctl(fd, DKIOCSCSICOMMAND, &cmd);

    if (cmd.response == kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE)
    {
        /* Command failed */
        switch (cmd.status)
        {
        case kSCSITaskStatus_TaskTimeoutOccurred:
            return STATUS_TIMEOUT;
            break;
        case kSCSITaskStatus_ProtocolTimeoutOccurred:
            return STATUS_IO_TIMEOUT;
            break;
        case kSCSITaskStatus_DeviceNotResponding:
            return STATUS_DEVICE_BUSY;
            break;
        case kSCSITaskStatus_DeviceNotPresent:
            return STATUS_NO_SUCH_DEVICE;
            break;
        case kSCSITaskStatus_DeliveryFailure:
            return STATUS_DEVICE_PROTOCOL_ERROR;
            break;
        case kSCSITaskStatus_No_Status:
        default:
            return STATUS_UNSUCCESSFUL;
            break;
        }
    }

    if (cmd.status != kSCSITaskStatus_No_Status)
        pPacket->ScsiStatus = cmd.status;

    ret = CDROM_GetStatusCode(io);
1973 1974 1975 1976
#endif
    return ret;
}

1977 1978 1979 1980 1981
/******************************************************************
 *		CDROM_ScsiGetCaps
 *
 *
 */
1982
static NTSTATUS CDROM_ScsiGetCaps(int fd, PIO_SCSI_CAPABILITIES caps)
1983 1984 1985
{
    NTSTATUS    ret = STATUS_NOT_IMPLEMENTED;

1986
#ifdef SG_SCATTER_SZ
1987
    caps->Length = sizeof(*caps);
1988 1989 1990 1991 1992 1993 1994 1995
    caps->MaximumTransferLength = SG_SCATTER_SZ; /* FIXME */
    caps->MaximumPhysicalPages = SG_SCATTER_SZ / getpagesize();
    caps->SupportedAsynchronousEvents = TRUE;
    caps->AlignmentMask = getpagesize();
    caps->TaggedQueuing = FALSE; /* we could check that it works and answer TRUE */
    caps->AdapterScansDown = FALSE; /* FIXME ? */
    caps->AdapterUsesPio = FALSE; /* FIXME ? */
    ret = STATUS_SUCCESS;
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
#elif defined __APPLE__
    uint64_t bytesr, bytesw, align;
    int io = ioctl(fd, DKIOCGETMAXBYTECOUNTREAD, &bytesr);
    if (io != 0) return CDROM_GetStatusCode(io);
    io = ioctl(fd, DKIOCGETMAXBYTECOUNTWRITE, &bytesw);
    if (io != 0) return CDROM_GetStatusCode(io);
    io = ioctl(fd, DKIOCGETMINSEGMENTALIGNMENTBYTECOUNT, &align);
    if (io != 0) return CDROM_GetStatusCode(io);
    caps->Length = sizeof(*caps);
    caps->MaximumTransferLength = bytesr < bytesw ? bytesr : bytesw;
    caps->MaximumPhysicalPages = caps->MaximumTransferLength / getpagesize();
    caps->SupportedAsynchronousEvents = TRUE;
    caps->AlignmentMask = align-1;
    caps->TaggedQueuing = FALSE; /* we could check that it works and answer TRUE */
    caps->AdapterScansDown = FALSE; /* FIXME ? */
    caps->AdapterUsesPio = FALSE; /* FIXME ? */
    ret = STATUS_SUCCESS;
2013 2014 2015 2016 2017 2018
#else
    FIXME("Unimplemented\n");
#endif
    return ret;
}

2019
/******************************************************************
2020
 *		CDROM_GetAddress
2021
 *
2022
 * implements IOCTL_SCSI_GET_ADDRESS
2023
 */
2024
static NTSTATUS CDROM_GetAddress(int fd, SCSI_ADDRESS* address)
2025
{
2026
    UCHAR portnum, busid, targetid, lun;
2027

2028
    address->Length = sizeof(SCSI_ADDRESS);
2029
    if ( ! CDROM_GetInterfaceInfo(fd, &portnum, &busid, &targetid, &lun))
2030
        return STATUS_NOT_SUPPORTED;
2031

2032 2033 2034
    address->PortNumber = portnum; /* primary=0 secondary=1 for ide */
    address->PathId = busid;       /* always 0 for ide */
    address->TargetId = targetid;  /* master=0 slave=1 for ide */
2035
    address->Lun = lun;
2036
    return STATUS_SUCCESS;
2037 2038
}

2039 2040 2041 2042 2043
/******************************************************************
 *		DVD_StartSession
 *
 *
 */
2044
static NTSTATUS DVD_StartSession(int fd, const DVD_SESSION_ID *sid_in, PDVD_SESSION_ID sid_out)
2045 2046 2047 2048 2049 2050 2051
{
#if defined(linux)
    NTSTATUS ret = STATUS_NOT_SUPPORTED;
    dvd_authinfo auth_info;

    memset( &auth_info, 0, sizeof( auth_info ) );
    auth_info.type = DVD_LU_SEND_AGID;
2052
    if (sid_in) auth_info.lsa.agid = *(const int*)sid_in; /* ?*/
2053 2054 2055 2056 2057

    TRACE("fd 0x%08x\n",fd);
    ret =CDROM_GetStatusCode(ioctl(fd, DVD_AUTH, &auth_info));
    *sid_out = auth_info.lsa.agid;
    return ret;
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
#elif defined(__APPLE__)
    NTSTATUS ret = STATUS_NOT_SUPPORTED;
    dk_dvd_report_key_t dvdrk;
    DVDAuthenticationGrantIDInfo agid_info;

    dvdrk.format = kDVDKeyFormatAGID_CSS;
    dvdrk.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
    if(sid_in) dvdrk.grantID = *(uint8_t*)sid_in; /* ? */
    dvdrk.bufferLength = sizeof(DVDAuthenticationGrantIDInfo);
    dvdrk.buffer = &agid_info;

    ret = CDROM_GetStatusCode(ioctl(fd, DKIOCDVDREPORTKEY, &dvdrk));
    *sid_out = agid_info.grantID;
    return ret;
2072
#else
2073
    FIXME("not supported on this O/S\n");
2074 2075 2076 2077 2078 2079 2080 2081 2082
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		DVD_EndSession
 *
 *
 */
2083
static NTSTATUS DVD_EndSession(int fd, const DVD_SESSION_ID *sid)
2084 2085 2086 2087 2088 2089
{
#if defined(linux)
    dvd_authinfo auth_info;

    memset( &auth_info, 0, sizeof( auth_info ) );
    auth_info.type = DVD_INVALIDATE_AGID;
2090
    auth_info.lsa.agid = *(const int*)sid;
2091 2092 2093

    TRACE("\n");
    return CDROM_GetStatusCode(ioctl(fd, DVD_AUTH, &auth_info));
2094 2095 2096 2097 2098 2099 2100 2101
#elif defined(__APPLE__)
    dk_dvd_send_key_t dvdsk;

    dvdsk.format = kDVDKeyFormatAGID_Invalidate;
    dvdsk.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
    dvdsk.grantID = (uint8_t)*sid;

    return CDROM_GetStatusCode(ioctl(fd, DKIOCDVDSENDKEY, &dvdsk));
2102
#else
2103
    FIXME("not supported on this O/S\n");
2104 2105 2106 2107 2108 2109 2110 2111 2112
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		DVD_SendKey
 *
 *
 */
2113
static NTSTATUS DVD_SendKey(int fd, const DVD_COPY_PROTECT_KEY *key)
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
{
#if defined(linux)
    NTSTATUS ret = STATUS_NOT_SUPPORTED;
    dvd_authinfo auth_info;

    memset( &auth_info, 0, sizeof( auth_info ) );
    switch (key->KeyType)
    {
    case DvdChallengeKey:
	auth_info.type = DVD_HOST_SEND_CHALLENGE;
	auth_info.hsc.agid = (int)key->SessionId;
	TRACE("DvdChallengeKey ioc 0x%x\n", DVD_AUTH );
	memcpy( auth_info.hsc.chal, key->KeyData, DVD_CHALLENGE_SIZE );
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
	break;
    case DvdBusKey2:
	auth_info.type = DVD_HOST_SEND_KEY2;
	auth_info.hsk.agid = (int)key->SessionId;

	memcpy( auth_info.hsk.key, key->KeyData, DVD_KEY_SIZE );
	
	TRACE("DvdBusKey2\n");
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
	break;

    default:
	FIXME("Unknown Keytype 0x%x\n",key->KeyType);
    }
    return ret;
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
#elif defined(__APPLE__)
    dk_dvd_send_key_t dvdsk;
    union
    {
        DVDChallengeKeyInfo chal;
        DVDKey2Info key2;
    } key_desc;

    switch(key->KeyType)
    {
    case DvdChallengeKey:
        dvdsk.format = kDVDKeyFormatChallengeKey;
        dvdsk.bufferLength = sizeof(key_desc.chal);
        dvdsk.buffer = &key_desc.chal;
        OSWriteBigInt16(key_desc.chal.dataLength, 0, key->KeyLength);
        memcpy(key_desc.chal.challengeKeyValue, key->KeyData, key->KeyLength);
        break;
    case DvdBusKey2:
        dvdsk.format = kDVDKeyFormatKey2;
        dvdsk.bufferLength = sizeof(key_desc.key2);
        dvdsk.buffer = &key_desc.key2;
        OSWriteBigInt16(key_desc.key2.dataLength, 0, key->KeyLength);
        memcpy(key_desc.key2.key2Value, key->KeyData, key->KeyLength);
        break;
    case DvdInvalidateAGID:
        dvdsk.format = kDVDKeyFormatAGID_Invalidate;
        break;
    case DvdBusKey1:
    case DvdTitleKey:
    case DvdAsf:
    case DvdGetRpcKey:
    case DvdDiskKey:
        ERR("attempted to write read-only key type 0x%x\n", key->KeyType);
        return STATUS_NOT_SUPPORTED;
    case DvdSetRpcKey:
        FIXME("DvdSetRpcKey NIY\n");
        return STATUS_NOT_SUPPORTED;
    default:
        FIXME("got unknown key type 0x%x\n", key->KeyType);
        return STATUS_NOT_SUPPORTED;
    }
    dvdsk.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
    dvdsk.grantID = (uint8_t)key->SessionId;

    return CDROM_GetStatusCode(ioctl(fd, DKIOCDVDSENDKEY, &dvdsk));
2188
#else
2189
    FIXME("not supported on this O/S\n");
2190
    return STATUS_NOT_SUPPORTED;
Mike Hearn's avatar
Mike Hearn committed
2191
#endif    
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
}

/******************************************************************
 *		DVD_ReadKey
 *
 *
 */
static NTSTATUS DVD_ReadKey(int fd, PDVD_COPY_PROTECT_KEY key)
{
#if defined(linux)
    NTSTATUS ret = STATUS_NOT_SUPPORTED;
    dvd_struct dvd;
    dvd_authinfo auth_info;

    memset( &dvd, 0, sizeof( dvd_struct ) );
    memset( &auth_info, 0, sizeof( auth_info ) );
    switch (key->KeyType)
    {
    case DvdDiskKey:
	
	dvd.type = DVD_STRUCT_DISCKEY;
	dvd.disckey.agid = (int)key->SessionId;
	memset( dvd.disckey.value, 0, DVD_DISCKEY_SIZE );
	
	TRACE("DvdDiskKey\n");
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_READ_STRUCT, &dvd ));
	if (ret == STATUS_SUCCESS)
	    memcpy(key->KeyData,dvd.disckey.value,DVD_DISCKEY_SIZE);
	break;
    case DvdTitleKey:
	auth_info.type = DVD_LU_SEND_TITLE_KEY;
	auth_info.lstk.agid = (int)key->SessionId;
	auth_info.lstk.lba = (int)(key->Parameters.TitleOffset.QuadPart>>11);
	TRACE("DvdTitleKey session %d Quadpart 0x%08lx offset 0x%08x\n",
	      (int)key->SessionId, (long)key->Parameters.TitleOffset.QuadPart, 
	      auth_info.lstk.lba);
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
	if (ret == STATUS_SUCCESS)
	    memcpy(key->KeyData, auth_info.lstk.title_key, DVD_KEY_SIZE );
	break;
    case DvdChallengeKey:

	auth_info.type = DVD_LU_SEND_CHALLENGE;
	auth_info.lsc.agid = (int)key->SessionId;

	TRACE("DvdChallengeKey\n");
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
	if (ret == STATUS_SUCCESS)
	    memcpy( key->KeyData, auth_info.lsc.chal, DVD_CHALLENGE_SIZE );
	break;
    case DvdAsf:
	auth_info.type = DVD_LU_SEND_ASF;
	TRACE("DvdAsf\n");
	auth_info.lsasf.asf=((PDVD_ASF)key->KeyData)->SuccessFlag;
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
	((PDVD_ASF)key->KeyData)->SuccessFlag = auth_info.lsasf.asf;
	break;
    case DvdBusKey1:
	auth_info.type = DVD_LU_SEND_KEY1;
	auth_info.lsk.agid = (int)key->SessionId;

	TRACE("DvdBusKey1\n");
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));

	if (ret == STATUS_SUCCESS)
	    memcpy( key->KeyData, auth_info.lsk.key, DVD_KEY_SIZE );
	break;
    case DvdGetRpcKey:
	auth_info.type = DVD_LU_SEND_RPC_STATE;

	TRACE("DvdGetRpcKey\n");
	ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));

	if (ret == STATUS_SUCCESS)
	{
	    ((PDVD_RPC_KEY)key->KeyData)->TypeCode = auth_info.lrpcs.type;
	    ((PDVD_RPC_KEY)key->KeyData)->RegionMask = auth_info.lrpcs.region_mask;
	    ((PDVD_RPC_KEY)key->KeyData)->RpcScheme = auth_info.lrpcs.rpc_scheme;
2270 2271
	    ((PDVD_RPC_KEY)key->KeyData)->UserResetsAvailable = auth_info.lrpcs.ucca;
	    ((PDVD_RPC_KEY)key->KeyData)->ManufacturerResetsAvailable = auth_info.lrpcs.vra;
2272 2273 2274 2275 2276 2277
	}
	break;
    default:
	FIXME("Unknown keytype 0x%x\n",key->KeyType);
    }
    return ret;
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
#elif defined(__APPLE__)
    union
    {
        dk_dvd_report_key_t key;
        dk_dvd_read_structure_t disk_key;
    } ioc;
    union
    {
        DVDDiscKeyInfo disk_key;
        DVDChallengeKeyInfo chal;
        DVDKey1Info key1;
        DVDTitleKeyInfo title;
        DVDAuthenticationSuccessFlagInfo asf;
        DVDRegionPlaybackControlInfo rpc;
    } desc;
    NTSTATUS ret = STATUS_NOT_SUPPORTED;

    switch(key->KeyType)
    {
    case DvdChallengeKey:
        ioc.key.format = kDVDKeyFormatChallengeKey;
        ioc.key.grantID = (uint8_t)key->SessionId;
        ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
        ioc.key.bufferLength = sizeof(desc.chal);
        ioc.key.buffer = &desc.chal;
        OSWriteBigInt16(desc.chal.dataLength, 0, key->KeyLength);
        break;
    case DvdBusKey1:
        ioc.key.format = kDVDKeyFormatKey1;
        ioc.key.grantID = (uint8_t)key->SessionId;
        ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
        ioc.key.bufferLength = sizeof(desc.key1);
        ioc.key.buffer = &desc.key1;
        OSWriteBigInt16(desc.key1.dataLength, 0, key->KeyLength);
        break;
    case DvdTitleKey:
        ioc.key.format = kDVDKeyFormatTitleKey;
        ioc.key.grantID = (uint8_t)key->SessionId;
        ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
        ioc.key.bufferLength = sizeof(desc.title);
        ioc.key.buffer = &desc.title;
        ioc.key.address = (uint32_t)(key->Parameters.TitleOffset.QuadPart>>11);
        OSWriteBigInt16(desc.title.dataLength, 0, key->KeyLength);
        break;
    case DvdAsf:
        ioc.key.format = kDVDKeyFormatASF;
        ioc.key.grantID = (uint8_t)key->SessionId;
        ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
        ioc.key.bufferLength = sizeof(desc.asf);
        ioc.key.buffer = &desc.asf;
        OSWriteBigInt16(desc.asf.dataLength, 0, key->KeyLength);
        break;
    case DvdGetRpcKey:
        ioc.key.format = kDVDKeyFormatRegionState;
        ioc.key.grantID = (uint8_t)key->SessionId;
        ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
        ioc.key.bufferLength = sizeof(desc.rpc);
        ioc.key.buffer = &desc.rpc;
        OSWriteBigInt16(desc.rpc.dataLength, 0, key->KeyLength);
        break;
    case DvdDiskKey:
        ioc.disk_key.format = kDVDStructureFormatDiscKeyInfo;
        ioc.disk_key.grantID = (uint8_t)key->SessionId;
        ioc.disk_key.bufferLength = sizeof(desc.disk_key);
        ioc.disk_key.buffer = &desc.disk_key;
        break;
    case DvdInvalidateAGID:
        ioc.key.format = kDVDKeyFormatAGID_Invalidate;
        ioc.key.grantID = (uint8_t)key->SessionId;
        ioc.key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
        break;
    case DvdBusKey2:
    case DvdSetRpcKey:
        ERR("attempted to read write-only key type 0x%x\n", key->KeyType);
        return STATUS_NOT_SUPPORTED;
    default:
        FIXME("got unknown key type 0x%x\n", key->KeyType);
        return STATUS_NOT_SUPPORTED;
    }

    ret = CDROM_GetStatusCode(ioctl(fd, (key->KeyType == DvdDiskKey ? DKIOCDVDREADSTRUCTURE : DKIOCDVDREPORTKEY), &ioc));

    if (ret == STATUS_SUCCESS)
    {
        switch(key->KeyType)
        {
        case DvdChallengeKey:
            key->KeyLength = OSReadBigInt16(desc.chal.dataLength, 0);
            memcpy(key->KeyData, desc.chal.challengeKeyValue, key->KeyLength);
            break;
        case DvdBusKey1:
            key->KeyLength = OSReadBigInt16(desc.key1.dataLength, 0);
            memcpy(key->KeyData, desc.key1.key1Value, key->KeyLength);
            break;
        case DvdTitleKey:
            key->KeyLength = OSReadBigInt16(desc.title.dataLength, 0);
            memcpy(key->KeyData, desc.title.titleKeyValue, key->KeyLength);
            key->KeyFlags = 0;
            if (desc.title.CPM)
            {
                /*key->KeyFlags |= DVD_COPYRIGHTED;*/
                if (desc.title.CP_SEC) key->KeyFlags |= DVD_SECTOR_PROTECTED;
                /*else key->KeyFlags |= DVD_SECTOR_NOT_PROTECTED;*/
#if 0
                switch (desc.title.CGMS)
                {
                case 0:
                    key->KeyFlags |= DVD_CGMS_COPY_PERMITTED;
                    break;
                case 2:
                    key->KeyFlags |= DVD_CGMS_COPY_ONCE;
                    break;
                case 3:
                    key->KeyFlags |= DVD_CGMS_NO_COPY;
                    break;
                }
#endif
            } /*else key->KeyFlags |= DVD_NOT_COPYRIGHTED;*/
            break;
        case DvdAsf:
            key->KeyLength = OSReadBigInt16(desc.title.dataLength, 0);
            ((PDVD_ASF)key->KeyData)->SuccessFlag = desc.asf.successFlag;
            break;
        case DvdGetRpcKey:
            key->KeyLength = OSReadBigInt16(desc.rpc.dataLength, 0);
            ((PDVD_RPC_KEY)key->KeyData)->UserResetsAvailable =
                desc.rpc.numberUserResets;
            ((PDVD_RPC_KEY)key->KeyData)->ManufacturerResetsAvailable =
                desc.rpc.numberVendorResets;
            ((PDVD_RPC_KEY)key->KeyData)->TypeCode =
                desc.rpc.typeCode;
            ((PDVD_RPC_KEY)key->KeyData)->RegionMask =
                desc.rpc.driveRegion;
            ((PDVD_RPC_KEY)key->KeyData)->RpcScheme =
                desc.rpc.rpcScheme;
        case DvdDiskKey:
            key->KeyLength = OSReadBigInt16(desc.disk_key.dataLength, 0);
            memcpy(key->KeyData, desc.disk_key.discKeyStructures, key->KeyLength);
            break;
        case DvdBusKey2:
        case DvdSetRpcKey:
        case DvdInvalidateAGID:
        default:
            /* Silence warning */
            ;
        }
    }
    return ret;
2426
#else
2427
    FIXME("not supported on this O/S\n");
2428 2429 2430 2431 2432 2433 2434
    return STATUS_NOT_SUPPORTED;
#endif
}

/******************************************************************
 *		DVD_GetRegion
 *
2435 2436 2437
 * This IOCTL combines information from both IOCTL_DVD_READ_KEY
 * with key type DvdGetRpcKey and IOCTL_DVD_READ_STRUCTURE with
 * structure type DvdCopyrightInformation into one structure.
2438
 */
2439
static NTSTATUS DVD_GetRegion(int fd, PDVD_REGION region)
2440
{
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
#if defined(linux)
    NTSTATUS ret = STATUS_NOT_SUPPORTED;
    dvd_struct dvd;
    dvd_authinfo auth_info;

    dvd.type = DVD_STRUCT_COPYRIGHT;
    dvd.copyright.layer_num = 0;
    auth_info.type = DVD_LU_SEND_RPC_STATE;

    ret = CDROM_GetStatusCode(ioctl( fd, DVD_AUTH, &auth_info ));
2451

2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
    if (ret == STATUS_SUCCESS)
    {
        ret = CDROM_GetStatusCode(ioctl( fd, DVD_READ_STRUCT, &dvd ));

        if (ret == STATUS_SUCCESS)
        {
            region->CopySystem = dvd.copyright.cpst;
            region->RegionData = dvd.copyright.rmi;
            region->SystemRegion = auth_info.lrpcs.region_mask;
            region->ResetCount = auth_info.lrpcs.ucca;
        }
    }
    return ret;
#elif defined(__APPLE__)
    dk_dvd_report_key_t key;
    dk_dvd_read_structure_t dvd;
    DVDRegionPlaybackControlInfo rpc;
    DVDCopyrightInfo copy;
    NTSTATUS ret = STATUS_NOT_SUPPORTED;

    key.format = kDVDKeyFormatRegionState;
    key.keyClass = kDVDKeyClassCSS_CPPM_CPRM;
    key.bufferLength = sizeof(rpc);
    key.buffer = &rpc;
    dvd.format = kDVDStructureFormatCopyrightInfo;
    dvd.bufferLength = sizeof(copy);
    dvd.buffer = &copy;

    ret = CDROM_GetStatusCode(ioctl( fd, DKIOCDVDREPORTKEY, &key ));

    if (ret == STATUS_SUCCESS)
    {
        ret = CDROM_GetStatusCode(ioctl( fd, DKIOCDVDREADSTRUCTURE, &dvd ));

        if (ret == STATUS_SUCCESS)
        {
            region->CopySystem = copy.copyrightProtectionSystemType;
            region->RegionData = copy.regionMask;
            region->SystemRegion = rpc.driveRegion;
            region->ResetCount = rpc.numberUserResets;
        }
    }
    return ret;
#else
2496
    FIXME("not supported on this O/S\n");
2497 2498
    return STATUS_NOT_SUPPORTED;
#endif
2499 2500 2501
}

/******************************************************************
2502
 *		DVD_ReadStructure
2503 2504 2505
 *
 *
 */
2506
static NTSTATUS DVD_ReadStructure(int dev, const DVD_READ_STRUCTURE *structure, PDVD_LAYER_DESCRIPTOR layer)
2507
{
2508
#ifdef DVD_READ_STRUCT
2509 2510 2511 2512 2513 2514 2515 2516 2517
    /* dvd_struct is not defined consistently across platforms */
    union
    {
	struct dvd_physical	physical;
	struct dvd_copyright	copyright;
	struct dvd_disckey	disckey;
	struct dvd_bca		bca;
	struct dvd_manufact	manufact;
    } s;
2518 2519 2520 2521 2522 2523 2524

    if (structure->BlockByteOffset.u.HighPart || structure->BlockByteOffset.u.LowPart)
        FIXME(": BlockByteOffset is not handled\n");

    switch (structure->Format)
    {
    case DvdPhysicalDescriptor:
2525
        s.physical.type = DVD_STRUCT_PHYSICAL;
2526 2527 2528 2529
        s.physical.layer_num = structure->LayerNumber;
        break;

    case DvdCopyrightDescriptor:
2530
        s.copyright.type = DVD_STRUCT_COPYRIGHT;
2531 2532 2533 2534
        s.copyright.layer_num = structure->LayerNumber;
        break;

    case DvdDiskKeyDescriptor:
2535
        s.disckey.type = DVD_STRUCT_DISCKEY;
2536 2537 2538 2539
        s.disckey.agid = structure->SessionId;
        break;

    case DvdBCADescriptor:
2540
        s.bca.type = DVD_STRUCT_BCA;
2541 2542 2543
        break;

    case DvdManufacturerDescriptor:
2544
        s.manufact.type = DVD_STRUCT_MANUFACT;
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
        s.manufact.layer_num = structure->LayerNumber;
        break;

    case DvdMaxDescriptor: /* This is not a real request, no matter what MSDN says! */
    default:
        return STATUS_INVALID_PARAMETER;
    }

    if (ioctl(dev, DVD_READ_STRUCT, &s) < 0)
       return STATUS_INVALID_PARAMETER;

    switch (structure->Format)
    {
    case DvdPhysicalDescriptor:
        {
2560
            internal_dvd_layer_descriptor *p = (internal_dvd_layer_descriptor *) layer;
2561 2562
            struct dvd_layer *l = &s.physical.layer[s.physical.layer_num];

2563 2564 2565 2566
            p->DataLength[0] = 2;
            p->DataLength[1] = 8;
            p->Reserved0[0] = 0;
            p->Reserved0[1] = 0;
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
            p->BookVersion = l->book_version;
            p->BookType = l->book_type;
            p->MinimumRate = l->min_rate;
            p->DiskSize = l->disc_size;
            p->LayerType = l->layer_type;
            p->TrackPath = l->track_path;
            p->NumberOfLayers = l->nlayers;
            p->Reserved1 = 0;
            p->TrackDensity = l->track_density;
            p->LinearDensity = l->linear_density;
2577 2578 2579
            p->StartingDataSector = GET_BE_DWORD(l->start_sector);
            p->EndDataSector = GET_BE_DWORD(l->end_sector);
            p->EndLayerZeroSector = GET_BE_DWORD(l->end_sector_l0);
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
            p->Reserved5 = 0;
            p->BCAFlag = l->bca;
            p->Reserved6 = 0;
        }
        break;

    case DvdCopyrightDescriptor:
        {
            PDVD_COPYRIGHT_DESCRIPTOR p = (PDVD_COPYRIGHT_DESCRIPTOR) layer;

            p->CopyrightProtectionType = s.copyright.cpst;
            p->RegionManagementInformation = s.copyright.rmi;
            p->Reserved = 0;
        }
        break;

    case DvdDiskKeyDescriptor:
        {
            PDVD_DISK_KEY_DESCRIPTOR p = (PDVD_DISK_KEY_DESCRIPTOR) layer;

            memcpy(p->DiskKeyData, s.disckey.value, 2048);
        }
        break;

    case DvdBCADescriptor:
        {
            PDVD_BCA_DESCRIPTOR p = (PDVD_BCA_DESCRIPTOR) layer;

            memcpy(p->BCAInformation, s.bca.value, s.bca.len);
        }
        break;

    case DvdManufacturerDescriptor:
        {
            PDVD_MANUFACTURER_DESCRIPTOR p = (PDVD_MANUFACTURER_DESCRIPTOR) layer;

            memcpy(p->ManufacturingInformation, s.manufact.value, 2048);
        }
        break;

    case DvdMaxDescriptor: /* Suppress warning */
	break;
    }
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
#elif defined(__APPLE__)
    NTSTATUS ret = STATUS_NOT_SUPPORTED;
    dk_dvd_read_structure_t dvdrs;
    union
    {
        DVDPhysicalFormatInfo phys;
        DVDCopyrightInfo copy;
        DVDDiscKeyInfo disk_key;
        DVDManufacturingInfo manf;
    } desc;
    union
    {
        PDVD_LAYER_DESCRIPTOR layer;
        internal_dvd_layer_descriptor *xlayer;
        PDVD_COPYRIGHT_DESCRIPTOR copy;
        PDVD_DISK_KEY_DESCRIPTOR disk_key;
        PDVD_MANUFACTURER_DESCRIPTOR manf;
    } nt_desc;

    nt_desc.layer = layer;
2643
    RtlZeroMemory(&dvdrs, sizeof(dvdrs));
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
    dvdrs.address = (uint32_t)(structure->BlockByteOffset.QuadPart>>11);
    dvdrs.grantID = (uint8_t)structure->SessionId;
    dvdrs.layer = structure->LayerNumber;
    switch(structure->Format)
    {
    case DvdPhysicalDescriptor:
        dvdrs.format = kDVDStructureFormatPhysicalFormatInfo;
        dvdrs.bufferLength = sizeof(desc.phys);
        dvdrs.buffer = &desc.phys;
        break;

    case DvdCopyrightDescriptor:
        dvdrs.format = kDVDStructureFormatCopyrightInfo;
        dvdrs.bufferLength = sizeof(desc.copy);
        dvdrs.buffer = &desc.copy;
        break;

    case DvdDiskKeyDescriptor:
        dvdrs.format = kDVDStructureFormatDiscKeyInfo;
        dvdrs.bufferLength = sizeof(desc.disk_key);
        dvdrs.buffer = &desc.disk_key;
        break;

    case DvdBCADescriptor:
        FIXME("DvdBCADescriptor NIY\n");
        return STATUS_NOT_SUPPORTED;

    case DvdManufacturerDescriptor:
        dvdrs.format = kDVDStructureFormatManufacturingInfo;
        dvdrs.bufferLength = sizeof(desc.manf);
        dvdrs.buffer = &desc.manf;
        break;

    case DvdMaxDescriptor:
    default:
        FIXME("got unknown structure type 0x%x\n", structure->Format);
        return STATUS_NOT_SUPPORTED;
    }
    ret = CDROM_GetStatusCode(ioctl(dev, DKIOCDVDREADSTRUCTURE, &dvdrs));
    if(ret == STATUS_SUCCESS)
    {
        switch(structure->Format)
        {
        case DvdPhysicalDescriptor:
            nt_desc.xlayer->DataLength[0] = 2;
            nt_desc.xlayer->DataLength[1] = 8;
            nt_desc.xlayer->Reserved0[0] = 0;
            nt_desc.xlayer->Reserved0[1] = 0;
            nt_desc.xlayer->BookVersion = desc.phys.partVersion;
            nt_desc.xlayer->BookType = desc.phys.bookType;
            nt_desc.xlayer->MinimumRate = desc.phys.minimumRate;
            nt_desc.xlayer->DiskSize = desc.phys.discSize;
            nt_desc.xlayer->LayerType = desc.phys.layerType;
            nt_desc.xlayer->TrackPath = desc.phys.trackPath;
            nt_desc.xlayer->NumberOfLayers = desc.phys.numberOfLayers;
            nt_desc.xlayer->Reserved1 = 0;
            nt_desc.xlayer->TrackDensity = desc.phys.trackDensity;
            nt_desc.xlayer->LinearDensity = desc.phys.linearDensity;
            nt_desc.xlayer->BCAFlag = desc.phys.bcaFlag;
2703 2704 2705
            nt_desc.xlayer->StartingDataSector = *(DWORD *)&desc.phys.zero1;
            nt_desc.xlayer->EndDataSector = *(DWORD *)&desc.phys.zero2;
            nt_desc.xlayer->EndLayerZeroSector = *(DWORD *)&desc.phys.zero3;
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
            nt_desc.xlayer->Reserved5 = 0;
            nt_desc.xlayer->Reserved6 = 0;
            break;

        case DvdCopyrightDescriptor:
            nt_desc.copy->CopyrightProtectionType =
                desc.copy.copyrightProtectionSystemType;
            nt_desc.copy->RegionManagementInformation =
                desc.copy.regionMask;
            nt_desc.copy->Reserved = 0;
            break;

        case DvdDiskKeyDescriptor:
            memcpy(
                nt_desc.disk_key->DiskKeyData,
                desc.disk_key.discKeyStructures,
                2048);
            break;

        case DvdManufacturerDescriptor:
            memcpy(
                nt_desc.manf->ManufacturingInformation,
                desc.manf.discManufacturingInfo,
                2048);
            break;

        case DvdBCADescriptor:
        case DvdMaxDescriptor:
        default:
            /* Silence warning */
            break;
        }
    }
    return ret;
2740
#else
2741
    FIXME("\n");
2742
#endif
2743 2744 2745
    return STATUS_SUCCESS;

}
2746 2747 2748 2749 2750

/******************************************************************
 *        GetInquiryData
 *        Implements the IOCTL_GET_INQUIRY_DATA ioctl.
 *        Returns Inquiry data for all devices on the specified scsi bus
2751
 *        Returns STATUS_BUFFER_TOO_SMALL if the output buffer is too small, 
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
 *        STATUS_INVALID_DEVICE_REQUEST if the given handle isn't to a SCSI device,
 *        or STATUS_NOT_SUPPORTED if the OS driver is too old
 */
static NTSTATUS GetInquiryData(int fd, PSCSI_ADAPTER_BUS_INFO BufferOut, DWORD OutBufferSize)
{
#ifdef HAVE_SG_IO_HDR_T_INTERFACE_ID
    PSCSI_INQUIRY_DATA pInquiryData = NULL;
    UCHAR sense_buffer[32];
    int iochk, version;
    sg_io_hdr_t iocmd;
    UCHAR inquiry[INQ_CMD_LEN] = {INQUIRY, 0, 0, 0, INQ_REPLY_LEN, 0};

    /* Check we have a SCSI device and a supported driver */
    if(ioctl(fd, SG_GET_VERSION_NUM, &version) != 0)
    {
        WARN("IOCTL_SCSI_GET_INQUIRY_DATA sg driver is not loaded\n");
        return STATUS_INVALID_DEVICE_REQUEST;
    }
    if(version < 30000 )
        return STATUS_NOT_SUPPORTED;

    /* FIXME: Enumerate devices on the bus */
    BufferOut->NumberOfBuses = 1;
    BufferOut->BusData[0].NumberOfLogicalUnits = 1;
    BufferOut->BusData[0].InquiryDataOffset = sizeof(SCSI_ADAPTER_BUS_INFO);

    pInquiryData = (PSCSI_INQUIRY_DATA)(BufferOut + 1);

    RtlZeroMemory(&iocmd, sizeof(iocmd));
    iocmd.interface_id = 'S';
    iocmd.cmd_len = sizeof(inquiry);
    iocmd.mx_sb_len = sizeof(sense_buffer);
    iocmd.dxfer_direction = SG_DXFER_FROM_DEV;
    iocmd.dxfer_len = INQ_REPLY_LEN;
    iocmd.dxferp = pInquiryData->InquiryData;
    iocmd.cmdp = inquiry;
    iocmd.sbp = sense_buffer;
    iocmd.timeout = 1000;

    iochk = ioctl(fd, SG_IO, &iocmd);
    if(iochk != 0)
        WARN("ioctl SG_IO returned %d, error (%s)\n", iochk, strerror(errno));

    CDROM_GetInterfaceInfo(fd, &BufferOut->BusData[0].InitiatorBusId, &pInquiryData->PathId, &pInquiryData->TargetId, &pInquiryData->Lun);
    pInquiryData->DeviceClaimed = TRUE;
    pInquiryData->InquiryDataLength = INQ_REPLY_LEN;
    pInquiryData->NextInquiryDataOffset = 0;
    return STATUS_SUCCESS;
#else
2801
    FIXME("not supported on this O/S\n");
2802 2803 2804 2805
    return STATUS_NOT_SUPPORTED;
#endif
}

2806 2807 2808 2809 2810
/******************************************************************
 *		CDROM_DeviceIoControl
 *
 *
 */
2811
NTSTATUS CDROM_DeviceIoControl(HANDLE hDevice, 
2812 2813 2814 2815
                               HANDLE hEvent, PIO_APC_ROUTINE UserApcRoutine,
                               PVOID UserApcContext, 
                               PIO_STATUS_BLOCK piosb, 
                               ULONG dwIoControlCode,
2816
                               LPVOID lpInBuffer, DWORD nInBufferSize,
2817
                               LPVOID lpOutBuffer, DWORD nOutBufferSize)
2818
{
2819
    DWORD       sz = 0;
2820
    NTSTATUS    status = STATUS_SUCCESS;
2821
    int fd, needs_close, dev;
2822

2823
    TRACE("%p %s %p %d %p %d %p\n",
2824 2825
          hDevice, iocodex(dwIoControlCode), lpInBuffer, nInBufferSize,
          lpOutBuffer, nOutBufferSize, piosb);
2826

2827
    piosb->Information = 0;
2828

2829 2830 2831 2832 2833 2834
    if ((status = server_get_unix_fd( hDevice, 0, &fd, &needs_close, NULL, NULL )))
    {
        if (status == STATUS_BAD_DEVICE_TYPE) return status;  /* no associated fd */
        goto error;
    }

2835 2836
    if ((status = CDROM_Open(fd, &dev)))
    {
2837
        if (needs_close) close( fd );
2838 2839
        goto error;
    }
2840

2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
#ifdef __APPLE__
    {
        char name[100];

        /* This is ugly as hell, but Mac OS is unable to do anything from the
         * partition fd, it wants an fd for the whole device, and it sometimes
         * also requires the device fd to be closed first, so we have to close
         * the handle that the caller gave us.
         * Also for some reason it wants the fd to be closed before we even
         * open the parent if we're trying to eject the disk.
         */
        if ((status = get_parent_device( fd, name, sizeof(name) ))) goto error;
        if (dwIoControlCode == IOCTL_STORAGE_EJECT_MEDIA)
            NtClose( hDevice );
        if (needs_close) close( fd );
        TRACE("opening parent %s\n", name );
        if ((fd = open( name, O_RDONLY )) == -1)
        {
            status = FILE_GetNtStatus();
            goto error;
        }
        needs_close = 1;
    }
#endif

2866 2867 2868
    switch (dwIoControlCode)
    {
    case IOCTL_CDROM_CHECK_VERIFY:
2869
    case IOCTL_DISK_CHECK_VERIFY:
2870 2871
    case IOCTL_STORAGE_CHECK_VERIFY:
    case IOCTL_STORAGE_CHECK_VERIFY2:
2872
        sz = 0;
2873
	CDROM_ClearCacheEntry(dev);
2874
        if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2875
            status = STATUS_INVALID_PARAMETER;
2876
        else status = CDROM_Verify(dev, fd);
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
        break;

/* EPP     case IOCTL_STORAGE_CHECK_VERIFY2: */

/* EPP     case IOCTL_STORAGE_FIND_NEW_DEVICES: */
/* EPP     case IOCTL_CDROM_FIND_NEW_DEVICES: */

    case IOCTL_STORAGE_LOAD_MEDIA:
    case IOCTL_CDROM_LOAD_MEDIA:
        sz = 0;
2887
	CDROM_ClearCacheEntry(dev);
2888
        if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2889
            status = STATUS_INVALID_PARAMETER;
2890
        else status = CDROM_SetTray(fd, FALSE);
2891 2892 2893
        break;
     case IOCTL_STORAGE_EJECT_MEDIA:
        sz = 0;
2894
	CDROM_ClearCacheEntry(dev);
2895
        if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2896
            status = STATUS_INVALID_PARAMETER;
2897 2898
        else
            status = CDROM_SetTray(fd, TRUE);
2899 2900
        break;

2901
    case IOCTL_CDROM_MEDIA_REMOVAL:
2902 2903 2904
    case IOCTL_DISK_MEDIA_REMOVAL:
    case IOCTL_STORAGE_MEDIA_REMOVAL:
    case IOCTL_STORAGE_EJECTION_CONTROL:
2905
        /* FIXME the last ioctl:s is not the same as the two others...
2906 2907
         * lockcount/owner should be handled */
        sz = 0;
2908
	CDROM_ClearCacheEntry(dev);
2909 2910
        if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nInBufferSize < sizeof(PREVENT_MEDIA_REMOVAL)) status = STATUS_BUFFER_TOO_SMALL;
2911
        else status = CDROM_ControlEjection(fd, lpInBuffer);
2912 2913
        break;

2914 2915 2916 2917 2918 2919 2920
    case IOCTL_STORAGE_GET_MEDIA_TYPES:
    case IOCTL_STORAGE_GET_MEDIA_TYPES_EX:
        sz = sizeof(GET_MEDIA_TYPES);
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
        else status = CDROM_GetMediaType(dev, lpOutBuffer);
        break;
2921 2922 2923

    case IOCTL_STORAGE_GET_DEVICE_NUMBER:
        sz = sizeof(STORAGE_DEVICE_NUMBER);
2924 2925
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2926
        else status = CDROM_GetDeviceNumber(dev, lpOutBuffer);
2927 2928 2929 2930
        break;

    case IOCTL_STORAGE_RESET_DEVICE:
        sz = 0;
2931
	CDROM_ClearCacheEntry(dev);
2932
        if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2933
            status = STATUS_INVALID_PARAMETER;
2934
        else status = CDROM_ResetAudio(fd);
2935 2936 2937 2938
        break;

    case IOCTL_CDROM_GET_CONTROL:
        sz = sizeof(CDROM_AUDIO_CONTROL);
2939 2940
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2941
        else status = CDROM_GetControl(dev, fd, lpOutBuffer);
2942 2943 2944 2945
        break;

    case IOCTL_CDROM_GET_DRIVE_GEOMETRY:
        sz = sizeof(DISK_GEOMETRY);
2946 2947
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2948
        else status = CDROM_GetDriveGeometry(dev, fd, lpOutBuffer);
2949 2950 2951 2952
        break;

    case IOCTL_CDROM_DISK_TYPE:
        sz = sizeof(CDROM_DISK_DATA);
2953
	/* CDROM_ClearCacheEntry(dev); */
2954 2955
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2956
        else status = CDROM_GetDiskData(dev, fd, lpOutBuffer);
2957 2958 2959 2960 2961 2962
        break;

/* EPP     case IOCTL_CDROM_GET_LAST_SESSION: */

    case IOCTL_CDROM_READ_Q_CHANNEL:
        sz = sizeof(SUB_Q_CHANNEL_DATA);
2963
        if (lpInBuffer == NULL || nInBufferSize < sizeof(CDROM_SUB_Q_DATA_FORMAT))
2964 2965
            status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2966
        else status = CDROM_ReadQChannel(dev, fd, lpInBuffer, lpOutBuffer);
2967 2968 2969 2970
        break;

    case IOCTL_CDROM_READ_TOC:
        sz = sizeof(CDROM_TOC);
2971 2972
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
2973
        else status = CDROM_ReadTOC(dev, fd, lpOutBuffer);
2974 2975 2976 2977 2978 2979 2980
        break;

/* EPP     case IOCTL_CDROM_READ_TOC_EX: */

    case IOCTL_CDROM_PAUSE_AUDIO:
        sz = 0;
        if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2981
            status = STATUS_INVALID_PARAMETER;
2982
        else status = CDROM_PauseAudio(fd);
2983 2984 2985
        break;
    case IOCTL_CDROM_PLAY_AUDIO_MSF:
        sz = 0;
2986 2987
        if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nInBufferSize < sizeof(CDROM_PLAY_AUDIO_MSF)) status = STATUS_BUFFER_TOO_SMALL;
2988
        else status = CDROM_PlayAudioMSF(fd, lpInBuffer);
2989 2990 2991 2992
        break;
    case IOCTL_CDROM_RESUME_AUDIO:
        sz = 0;
        if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
2993
            status = STATUS_INVALID_PARAMETER;
2994
        else status = CDROM_ResumeAudio(fd);
2995 2996 2997
        break;
    case IOCTL_CDROM_SEEK_AUDIO_MSF:
        sz = 0;
2998 2999
        if (lpOutBuffer != NULL || nOutBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nInBufferSize < sizeof(CDROM_SEEK_AUDIO_MSF)) status = STATUS_BUFFER_TOO_SMALL;
3000
        else status = CDROM_SeekAudioMSF(dev, fd, lpInBuffer);
3001 3002 3003
        break;
    case IOCTL_CDROM_STOP_AUDIO:
        sz = 0;
3004
	CDROM_ClearCacheEntry(dev); /* Maybe intention is to change media */
3005
        if (lpInBuffer != NULL || nInBufferSize != 0 || lpOutBuffer != NULL || nOutBufferSize != 0)
3006
            status = STATUS_INVALID_PARAMETER;
3007
        else status = CDROM_StopAudio(fd);
3008 3009 3010
        break;
    case IOCTL_CDROM_GET_VOLUME:
        sz = sizeof(VOLUME_CONTROL);
3011 3012
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3013
        else status = CDROM_GetVolume(fd, lpOutBuffer);
3014 3015 3016
        break;
    case IOCTL_CDROM_SET_VOLUME:
        sz = 0;
3017
	CDROM_ClearCacheEntry(dev);
3018
        if (lpInBuffer == NULL || nInBufferSize < sizeof(VOLUME_CONTROL) || lpOutBuffer != NULL)
3019
            status = STATUS_INVALID_PARAMETER;
3020
        else status = CDROM_SetVolume(fd, lpInBuffer);
3021 3022 3023
        break;
    case IOCTL_CDROM_RAW_READ:
        sz = 0;
3024 3025
        if (nInBufferSize < sizeof(RAW_READ_INFO)) status = STATUS_INVALID_PARAMETER;
        else if (lpOutBuffer == NULL) status = STATUS_BUFFER_TOO_SMALL;
3026 3027
        else status = CDROM_RawRead(fd, lpInBuffer, lpOutBuffer,
                                    nOutBufferSize, &sz);
3028
        break;
3029 3030
    case IOCTL_SCSI_GET_ADDRESS:
        sz = sizeof(SCSI_ADDRESS);
3031 3032
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3033
        else status = CDROM_GetAddress(fd, lpOutBuffer);
3034
        break;
3035 3036
    case IOCTL_SCSI_PASS_THROUGH_DIRECT:
        sz = sizeof(SCSI_PASS_THROUGH_DIRECT);
3037 3038
        if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sizeof(SCSI_PASS_THROUGH_DIRECT)) status = STATUS_BUFFER_TOO_SMALL;
3039
        else status = CDROM_ScsiPassThroughDirect(fd, lpOutBuffer);
3040 3041 3042
        break;
    case IOCTL_SCSI_PASS_THROUGH:
        sz = sizeof(SCSI_PASS_THROUGH);
3043 3044
        if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sizeof(SCSI_PASS_THROUGH)) status = STATUS_BUFFER_TOO_SMALL;
3045
        else status = CDROM_ScsiPassThrough(fd, lpOutBuffer);
3046 3047 3048 3049 3050
        break;
    case IOCTL_SCSI_GET_CAPABILITIES:
        sz = sizeof(IO_SCSI_CAPABILITIES);
        if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sizeof(IO_SCSI_CAPABILITIES)) status = STATUS_BUFFER_TOO_SMALL;
3051
        else status = CDROM_ScsiGetCaps(fd, lpOutBuffer);
3052
        break;
3053 3054 3055 3056 3057 3058
    case IOCTL_DVD_START_SESSION:
        sz = sizeof(DVD_SESSION_ID);
        if (lpOutBuffer == NULL) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
        else
        {
3059
            TRACE("before in 0x%08x out 0x%08x\n",(lpInBuffer)?*(PDVD_SESSION_ID)lpInBuffer:0,
3060
                  *(PDVD_SESSION_ID)lpOutBuffer);
3061
            status = DVD_StartSession(fd, lpInBuffer, lpOutBuffer);
3062
            TRACE("before in 0x%08x out 0x%08x\n",(lpInBuffer)?*(PDVD_SESSION_ID)lpInBuffer:0,
3063 3064 3065 3066 3067 3068
                  *(PDVD_SESSION_ID)lpOutBuffer);
        }
        break;
    case IOCTL_DVD_END_SESSION:
        sz = sizeof(DVD_SESSION_ID);
        if ((lpInBuffer == NULL) ||  (nInBufferSize < sz))status = STATUS_INVALID_PARAMETER;
3069
        else status = DVD_EndSession(fd, lpInBuffer);
3070 3071 3072 3073 3074 3075 3076 3077 3078
        break;
    case IOCTL_DVD_SEND_KEY:
        sz = 0;
        if (!lpInBuffer ||
            (((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength != nInBufferSize))
            status = STATUS_INVALID_PARAMETER;
        else
        {
            TRACE("doing DVD_SendKey\n");
3079
            status = DVD_SendKey(fd, lpInBuffer);
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
        }
        break;
    case IOCTL_DVD_READ_KEY:
        if (!lpInBuffer ||
            (((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength != nInBufferSize))
            status = STATUS_INVALID_PARAMETER;
        else if (lpInBuffer !=lpOutBuffer) status = STATUS_BUFFER_TOO_SMALL;
        else
        {
            TRACE("doing DVD_READ_KEY\n");
            sz = ((PDVD_COPY_PROTECT_KEY)lpInBuffer)->KeyLength;
3091
            status = DVD_ReadKey(fd, lpInBuffer);
3092 3093 3094 3095 3096 3097 3098
        }
        break;
    case IOCTL_DVD_GET_REGION:
        sz = sizeof(DVD_REGION);
        if (lpInBuffer != NULL || nInBufferSize != 0) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
        TRACE("doing DVD_Get_REGION\n");
3099
        status = DVD_GetRegion(fd, lpOutBuffer);
3100 3101 3102 3103 3104
        break;
    case IOCTL_DVD_READ_STRUCTURE:
        sz = sizeof(DVD_LAYER_DESCRIPTOR);
        if (lpInBuffer == NULL || nInBufferSize != sizeof(DVD_READ_STRUCTURE)) status = STATUS_INVALID_PARAMETER;
        else if (nOutBufferSize < sz) status = STATUS_BUFFER_TOO_SMALL;
3105 3106 3107
        else
        {
            TRACE("doing DVD_READ_STRUCTURE\n");
3108
            status = DVD_ReadStructure(fd, lpInBuffer, lpOutBuffer);
3109
        }
3110 3111
        break;

3112 3113
    case IOCTL_SCSI_GET_INQUIRY_DATA:
        sz = INQ_REPLY_LEN;
3114
        status = GetInquiryData(fd, lpOutBuffer, nOutBufferSize);
3115 3116
        break;

3117
    default:
3118 3119
        if (needs_close) close( fd );
        return STATUS_NOT_SUPPORTED;
3120
    }
3121
    if (needs_close) close( fd );
3122
 error:
3123 3124 3125
    piosb->u.Status = status;
    piosb->Information = sz;
    if (hEvent) NtSetEvent(hEvent, NULL);
3126
    return status;
3127
}