device.c 71.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * Dynamic devices support
 *
 * Copyright 2006 Alexandre Julliard
 *
 * 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
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"
#include "wine/port.h"

#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
28
#include <fcntl.h>
29
#include <sys/time.h>
30 31 32
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
33

34 35
#define NONAMELESSUNION

36
#include "mountmgr.h"
37 38 39 40 41
#include "winreg.h"
#include "winuser.h"
#include "dbt.h"

#include "wine/list.h"
42
#include "wine/unicode.h"
43 44
#include "wine/debug.h"

45
WINE_DEFAULT_DEBUG_CHANNEL(mountmgr);
46

47
#define MAX_DOS_DRIVES 26
48
#define MAX_PORTS 256
49

50 51
static const WCHAR drive_types[][8] =
{
52 53 54 55 56
    { 0 },                           /* DEVICE_UNKNOWN */
    { 0 },                           /* DEVICE_HARDDISK */
    {'h','d',0},                     /* DEVICE_HARDDISK_VOL */
    {'f','l','o','p','p','y',0},     /* DEVICE_FLOPPY */
    {'c','d','r','o','m',0},         /* DEVICE_CDROM */
57
    {'c','d','r','o','m',0},         /* DEVICE_DVD */
58 59
    {'n','e','t','w','o','r','k',0}, /* DEVICE_NETWORK */
    {'r','a','m','d','i','s','k',0}  /* DEVICE_RAMDISK */
60 61
};

62 63
static const WCHAR drives_keyW[] = {'S','o','f','t','w','a','r','e','\\',
                                    'W','i','n','e','\\','D','r','i','v','e','s',0};
64 65
static const WCHAR ports_keyW[] = {'S','o','f','t','w','a','r','e','\\',
                                   'W','i','n','e','\\','P','o','r','t','s',0};
66 67 68 69 70 71
static const WCHAR scsi_keyW[] = {'H','A','R','D','W','A','R','E','\\','D','E','V','I','C','E','M','A','P','\\','S','c','s','i',0};
static const WCHAR scsi_port_keyW[] = {'S','c','s','i',' ','P','o','r','t',' ','%','d',0};
static const WCHAR scsi_bus_keyW[] = {'S','c','s','i',' ','B','u','s',' ','%','d',0};
static const WCHAR target_id_keyW[] = {'T','a','r','g','e','t',' ','I','d',' ','%','d',0};
static const WCHAR lun_keyW[] = {'L','o','g','i','c','a','l',' ','U','n','i','t',' ','I','d',' ','%','d',0};
static const WCHAR devnameW[] = {'D','e','v','i','c','e','N','a','m','e',0};
72

73 74 75 76 77 78 79 80 81 82
enum fs_type
{
    FS_ERROR,    /* error accessing the device */
    FS_UNKNOWN,  /* unknown file system */
    FS_FAT1216,
    FS_FAT32,
    FS_ISO9660,
    FS_UDF       /* For reference [E] = Ecma-167.pdf, [U] = udf260.pdf */
};

83
struct disk_device
84
{
85
    enum device_type      type;        /* drive type */
86
    DEVICE_OBJECT        *dev_obj;     /* disk device allocated for this volume */
87
    UNICODE_STRING        name;        /* device name */
88
    UNICODE_STRING        symlink;     /* device symlink if any */
89
    STORAGE_DEVICE_NUMBER devnum;      /* device number info */
90
    char                 *unix_device; /* unix device path */
91
    char                 *unix_mount;  /* unix mount point path */
92
    char                 *serial;      /* disk serial number */
93 94
};

95 96 97 98 99
struct volume
{
    struct list           entry;       /* entry in volumes list */
    struct disk_device   *device;      /* disk device */
    char                 *udi;         /* unique identifier for dynamic volumes */
100
    unsigned int          ref;         /* ref count */
101
    GUID                  guid;        /* volume uuid */
102
    struct mount_point   *mount;       /* Volume{xxx} mount point */
103 104 105
    WCHAR                 label[256];  /* volume label */
    DWORD                 serial;      /* volume serial number */
    enum fs_type          fs_type;     /* file system type */
106 107
};

108 109 110
struct dos_drive
{
    struct list           entry;       /* entry in drives list */
111
    struct volume        *volume;      /* volume for this drive */
112
    int                   drive;       /* drive letter (0 = A: etc.) */
113
    struct mount_point   *mount;       /* DosDevices mount point */
114 115
};

116
static struct list drives_list = LIST_INIT(drives_list);
117
static struct list volumes_list = LIST_INIT(volumes_list);
118

119
static DRIVER_OBJECT *harddisk_driver;
120
static DRIVER_OBJECT *serial_driver;
121
static DRIVER_OBJECT *parallel_driver;
122

123 124 125 126 127 128 129 130 131
static CRITICAL_SECTION device_section;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &device_section,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": device_section") }
};
static CRITICAL_SECTION device_section = { &critsect_debug, -1, 0, 0, 0, 0 };

132
static char *get_dosdevices_path( char **device )
133
{
134 135 136
    const char *home = getenv( "HOME" );
    const char *prefix = getenv( "WINEPREFIX" );
    size_t len = (prefix ? strlen(prefix) : strlen(home) + strlen("/.wine")) + sizeof("/dosdevices/com256");
137
    char *path = HeapAlloc( GetProcessHeap(), 0, len );
138

139 140
    if (path)
    {
141 142 143 144 145 146
        if (prefix) strcpy( path, prefix );
        else
        {
            strcpy( path, home );
            strcat( path, "/.wine" );
        }
147
        strcat( path, "/dosdevices/a::" );
148
        *device = path + len - sizeof("com256");
149 150 151 152
    }
    return path;
}

153 154 155 156 157 158 159 160 161
static char *strdupA( const char *str )
{
    char *ret;

    if (!str) return NULL;
    if ((ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
    return ret;
}

162
WCHAR *strdupW( const WCHAR *str )
163 164 165 166 167 168 169 170
{
    WCHAR *ret;

    if (!str) return NULL;
    if ((ret = RtlAllocateHeap( GetProcessHeap(), 0, (strlenW(str) + 1) * sizeof(WCHAR) ))) strcpyW( ret, str );
    return ret;
}

171 172 173 174 175 176 177 178
static const GUID *get_default_uuid( int letter )
{
    static GUID guid;

    guid.Data4[7] = 'A' + letter;
    return &guid;
}

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
/* read a Unix symlink; returned buffer must be freed by caller */
static char *read_symlink( const char *path )
{
    char *buffer;
    int ret, size = 128;

    for (;;)
    {
        if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size )))
        {
            SetLastError( ERROR_NOT_ENOUGH_MEMORY );
            return 0;
        }
        ret = readlink( path, buffer, size );
        if (ret == -1)
        {
            RtlFreeHeap( GetProcessHeap(), 0, buffer );
            return 0;
        }
        if (ret != size)
        {
            buffer[ret] = 0;
            return buffer;
        }
        RtlFreeHeap( GetProcessHeap(), 0, buffer );
        size *= 2;
    }
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221
/* update a symlink if it changed; return TRUE if updated */
static void update_symlink( const char *path, const char *dest, const char *orig_dest )
{
    if (dest && dest[0])
    {
        if (!orig_dest || strcmp( orig_dest, dest ))
        {
            unlink( path );
            symlink( dest, path );
        }
    }
    else unlink( path );
}

222 223 224 225 226 227 228 229 230 231
/* send notification about a change to a given drive */
static void send_notify( int drive, int code )
{
    DEV_BROADCAST_VOLUME info;

    info.dbcv_size       = sizeof(info);
    info.dbcv_devicetype = DBT_DEVTYP_VOLUME;
    info.dbcv_reserved   = 0;
    info.dbcv_unitmask   = 1 << drive;
    info.dbcv_flags      = DBTF_MEDIA;
232 233
    BroadcastSystemMessageW( BSF_FORCEIFHUNG|BSF_QUERY, NULL,
                             WM_DEVICECHANGE, code, (LPARAM)&info );
234 235
}

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
#define BLOCK_SIZE 2048
#define SUPERBLOCK_SIZE BLOCK_SIZE

#define CDFRAMES_PERSEC         75
#define CDFRAMES_PERMIN         (CDFRAMES_PERSEC * 60)
#define FRAME_OF_ADDR(a)        ((a)[1] * CDFRAMES_PERMIN + (a)[2] * CDFRAMES_PERSEC + (a)[3])
#define FRAME_OF_TOC(toc, idx)  FRAME_OF_ADDR((toc)->TrackData[(idx) - (toc)->FirstTrack].Address)

#define GETWORD(buf,off)  MAKEWORD(buf[(off)],buf[(off+1)])
#define GETLONG(buf,off)  MAKELONG(GETWORD(buf,off),GETWORD(buf,off+2))

static int open_volume_file( const struct volume *volume, const char *file )
{
    const char *unix_mount = volume->device->unix_mount;
    char *path;
    int fd;

    if (!unix_mount) return -1;

    if (unix_mount[0] == '/')
    {
        if (!(path = HeapAlloc( GetProcessHeap(), 0, strlen( unix_mount ) + 1 + strlen( file ) + 1 )))
            return -1;

        strcpy( path, unix_mount );
    }
    else
    {
264 265 266
        const char *home = getenv( "HOME" );
        const char *prefix = getenv( "WINEPREFIX" );
        size_t len = prefix ? strlen(prefix) : strlen(home) + strlen("/.wine");
267

268 269
        if (!(path = HeapAlloc( GetProcessHeap(), 0, len + strlen("/dosdevices/") +
                                strlen(unix_mount) + 1 + strlen( file ) + 1 )))
270 271
            return -1;

272 273 274 275 276 277
        if (prefix) strcpy( path, prefix );
        else
        {
            strcpy( path, home );
            strcat( path, "/.wine" );
        }
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 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 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
        strcat( path, "/dosdevices/" );
        strcat( path, unix_mount );
    }
    strcat( path, "/" );
    strcat( path, file );

    fd = open( path, O_RDONLY );
    HeapFree( GetProcessHeap(), 0, path );
    return fd;
}

/* get the label by reading it from a file at the root of the filesystem */
static void get_filesystem_label( struct volume *volume )
{
    int fd;
    ssize_t size;
    char buffer[256], *p;

    volume->label[0] = 0;

    if ((fd = open_volume_file( volume, ".windows-label" )) == -1)
        return;
    size = read( fd, buffer, sizeof(buffer) );
    close( fd );

    p = buffer + size;
    while (p > buffer && (p[-1] == ' ' || p[-1] == '\r' || p[-1] == '\n')) p--;
    *p = 0;
    if (!MultiByteToWideChar( CP_UNIXCP, 0, buffer, -1, volume->label, ARRAY_SIZE(volume->label) ))
        volume->label[ARRAY_SIZE(volume->label) - 1] = 0;
}

/* get the serial number by reading it from a file at the root of the filesystem */
static void get_filesystem_serial( struct volume *volume )
{
    int fd;
    ssize_t size;
    char buffer[32];

    volume->serial = 0;

    if ((fd = open_volume_file( volume, ".windows-serial" )) == -1)
        return;
    size = read( fd, buffer, sizeof(buffer) );
    close( fd );

    if (size < 0) return;
    buffer[size] = 0;
    volume->serial = strtoul( buffer, NULL, 16 );
}


/******************************************************************
 *		VOLUME_FindCdRomDataBestVoldesc
 */
static DWORD VOLUME_FindCdRomDataBestVoldesc( HANDLE handle )
{
    BYTE cur_vd_type, max_vd_type = 0;
    BYTE buffer[0x800];
    DWORD size, offs, best_offs = 0, extra_offs = 0;

    for (offs = 0x8000; offs <= 0x9800; offs += 0x800)
    {
        /* if 'CDROM' occurs at position 8, this is a pre-iso9660 cd, and
         * the volume label is displaced forward by 8
         */
        if (SetFilePointer( handle, offs, NULL, FILE_BEGIN ) != offs) break;
        if (!ReadFile( handle, buffer, sizeof(buffer), &size, NULL )) break;
        if (size != sizeof(buffer)) break;
        /* check for non-ISO9660 signature */
        if (!memcmp( buffer + 11, "ROM", 3 )) extra_offs = 8;
        cur_vd_type = buffer[extra_offs];
        if (cur_vd_type == 0xff) /* voldesc set terminator */
            break;
        if (cur_vd_type > max_vd_type)
        {
            max_vd_type = cur_vd_type;
            best_offs = offs + extra_offs;
        }
    }
    return best_offs;
}


/***********************************************************************
 *           VOLUME_ReadFATSuperblock
 */
static enum fs_type VOLUME_ReadFATSuperblock( HANDLE handle, BYTE *buff )
{
    DWORD size;

    /* try a fixed disk, with a FAT partition */
    if (SetFilePointer( handle, 0, NULL, FILE_BEGIN ) != 0 ||
        !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ))
    {
        if (GetLastError() == ERROR_BAD_DEV_TYPE) return FS_UNKNOWN;  /* not a real device */
        return FS_ERROR;
    }

    if (size < SUPERBLOCK_SIZE) return FS_UNKNOWN;

    /* FIXME: do really all FAT have their name beginning with
     * "FAT" ? (At least FAT12, FAT16 and FAT32 have :)
     */
    if (!memcmp(buff+0x36, "FAT", 3) || !memcmp(buff+0x52, "FAT", 3))
    {
        /* guess which type of FAT we have */
        int reasonable;
        unsigned int sectors,
                     sect_per_fat,
                     total_sectors,
                     num_boot_sectors,
                     num_fats,
                     num_root_dir_ents,
                     bytes_per_sector,
                     sectors_per_cluster,
                     nclust;
        sect_per_fat = GETWORD(buff, 0x16);
        if (!sect_per_fat) sect_per_fat = GETLONG(buff, 0x24);
        total_sectors = GETWORD(buff, 0x13);
        if (!total_sectors)
            total_sectors = GETLONG(buff, 0x20);
        num_boot_sectors = GETWORD(buff, 0x0e);
        num_fats =  buff[0x10];
        num_root_dir_ents = GETWORD(buff, 0x11);
        bytes_per_sector = GETWORD(buff, 0x0b);
        sectors_per_cluster = buff[0x0d];
        /* check if the parameters are reasonable and will not cause
         * arithmetic errors in the calculation */
        reasonable = num_boot_sectors < total_sectors &&
                     num_fats < 16 &&
                     bytes_per_sector >= 512 && bytes_per_sector % 512 == 0 &&
                     sectors_per_cluster >= 1;
        if (!reasonable) return FS_UNKNOWN;
        sectors =  total_sectors - num_boot_sectors - num_fats * sect_per_fat -
            (num_root_dir_ents * 32 + bytes_per_sector - 1) / bytes_per_sector;
        nclust = sectors / sectors_per_cluster;
        if ((buff[0x42] == 0x28 || buff[0x42] == 0x29) &&
                !memcmp(buff+0x52, "FAT", 3)) return FS_FAT32;
        if (nclust < 65525)
        {
            if ((buff[0x26] == 0x28 || buff[0x26] == 0x29) &&
                    !memcmp(buff+0x36, "FAT", 3))
                return FS_FAT1216;
        }
    }
    return FS_UNKNOWN;
}


/***********************************************************************
 *           VOLUME_ReadCDBlock
 */
static BOOL VOLUME_ReadCDBlock( HANDLE handle, BYTE *buff, INT offs )
{
    DWORD size, whence = offs >= 0 ? FILE_BEGIN : FILE_END;

    if (SetFilePointer( handle, offs, NULL, whence ) != offs ||
        !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ) ||
        size != SUPERBLOCK_SIZE)
        return FALSE;

    return TRUE;
}


/***********************************************************************
 *           VOLUME_ReadCDSuperblock
 */
static enum fs_type VOLUME_ReadCDSuperblock( HANDLE handle, BYTE *buff )
{
    int i;
    DWORD offs;

    /* Check UDF first as UDF and ISO9660 structures can coexist on the same medium
     *  Starting from sector 16, we may find :
     *  - a CD-ROM Volume Descriptor Set (ISO9660) containing one or more Volume Descriptors
     *  - an Extended Area (UDF) -- [E] 2/8.3.1 and [U] 2.1.7
     *  There is no explicit end so read 16 sectors and then give up */
    for( i=16; i<16+16; i++)
    {
        if (!VOLUME_ReadCDBlock(handle, buff, i*BLOCK_SIZE))
            continue;

        /* We are supposed to check "BEA01", "NSR0x" and "TEA01" IDs + verify tag checksum
         *  but we assume the volume is well-formatted */
        if (!memcmp(&buff[1], "BEA01", 5)) return FS_UDF;
    }

    offs = VOLUME_FindCdRomDataBestVoldesc( handle );
    if (!offs) return FS_UNKNOWN;

    if (!VOLUME_ReadCDBlock(handle, buff, offs))
        return FS_ERROR;

    /* check for the iso9660 identifier */
    if (!memcmp(&buff[1], "CD001", 5)) return FS_ISO9660;
    return FS_UNKNOWN;
}


/**************************************************************************
 *                        UDF_Find_PVD
 * Find the Primary Volume Descriptor
 */
static BOOL UDF_Find_PVD( HANDLE handle, BYTE pvd[] )
{
    unsigned int i;
    DWORD offset;
    INT locations[] = { 256, -1, -257, 512 };

    for(i=0; i<ARRAY_SIZE(locations); i++)
    {
        if (!VOLUME_ReadCDBlock(handle, pvd, locations[i]*BLOCK_SIZE))
            return FALSE;

        /* Tag Identifier of Anchor Volume Descriptor Pointer is 2 -- [E] 3/10.2.1 */
        if (pvd[0]==2 && pvd[1]==0)
        {
            /* Tag location (Uint32) at offset 12, little-endian */
            offset  = pvd[20 + 0];
            offset |= pvd[20 + 1] << 8;
            offset |= pvd[20 + 2] << 16;
            offset |= pvd[20 + 3] << 24;
            offset *= BLOCK_SIZE;

            if (!VOLUME_ReadCDBlock(handle, pvd, offset))
                return FALSE;

            /* Check for the Primary Volume Descriptor Tag Id -- [E] 3/10.1.1 */
            if (pvd[0]!=1 || pvd[1]!=0)
                return FALSE;

            /* 8 or 16 bits per character -- [U] 2.1.1 */
            if (!(pvd[24]==8 || pvd[24]==16))
                return FALSE;

            return TRUE;
        }
    }

    return FALSE;
}


/**************************************************************************
 *                              VOLUME_GetSuperblockLabel
 */
static void VOLUME_GetSuperblockLabel( struct volume *volume, HANDLE handle, const BYTE *superblock )
{
    const BYTE *label_ptr = NULL;
    DWORD label_len;

    switch (volume->fs_type)
    {
    case FS_ERROR:
        label_len = 0;
        break;
    case FS_UNKNOWN:
        get_filesystem_label( volume );
        return;
    case FS_FAT1216:
        label_ptr = superblock + 0x2b;
        label_len = 11;
        break;
    case FS_FAT32:
        label_ptr = superblock + 0x47;
        label_len = 11;
        break;
    case FS_ISO9660:
        {
            BYTE ver = superblock[0x5a];

            if (superblock[0x58] == 0x25 && superblock[0x59] == 0x2f &&  /* Unicode ID */
                ((ver == 0x40) || (ver == 0x43) || (ver == 0x45)))
            { /* yippee, unicode */
                unsigned int i;

                for (i = 0; i < 16; i++)
                    volume->label[i] = (superblock[40+2*i] << 8) | superblock[41+2*i];
                volume->label[i] = 0;
                while (i && volume->label[i-1] == ' ') volume->label[--i] = 0;
                return;
            }
            label_ptr = superblock + 40;
            label_len = 32;
            break;
        }
    case FS_UDF:
        {
            BYTE pvd[BLOCK_SIZE];

            if(!UDF_Find_PVD(handle, pvd))
            {
                label_len = 0;
                break;
            }

            /* [E] 3/10.1.4 and [U] 2.1.1 */
            if(pvd[24]==8)
            {
                label_ptr = pvd + 24 + 1;
                label_len = pvd[24+32-1];
                break;
            }
            else
            {
                unsigned int i;

                label_len = 1 + pvd[24+32-1];
                for (i = 0; i < label_len; i += 2)
                    volume->label[i/2] = (pvd[24+1+i] << 8) | pvd[24+1+i+1];
                volume->label[label_len] = 0;
                return;
            }
        }
    }
    if (label_len) RtlMultiByteToUnicodeN( volume->label, sizeof(volume->label) - sizeof(WCHAR),
                                           &label_len, (const char *)label_ptr, label_len );
    label_len /= sizeof(WCHAR);
    volume->label[label_len] = 0;
    while (label_len && volume->label[label_len-1] == ' ') volume->label[--label_len] = 0;
}


/**************************************************************************
 *                              UDF_Find_FSD_Sector
 * Find the File Set Descriptor used to compute the serial of a UDF volume
 */
static int UDF_Find_FSD_Sector( HANDLE handle, BYTE block[] )
{
    int i, PVD_sector, PD_sector, PD_length;

    if(!UDF_Find_PVD(handle,block))
        goto default_sector;

    /* Retrieve the tag location of the PVD -- [E] 3/7.2 */
    PVD_sector  = block[12 + 0];
    PVD_sector |= block[12 + 1] << 8;
    PVD_sector |= block[12 + 2] << 16;
    PVD_sector |= block[12 + 3] << 24;

    /* Find the Partition Descriptor */
    for(i=PVD_sector+1; ; i++)
    {
        if(!VOLUME_ReadCDBlock(handle, block, i*BLOCK_SIZE))
            goto default_sector;

        /* Partition Descriptor Tag Id -- [E] 3/10.5.1 */
        if(block[0]==5 && block[1]==0)
            break;

        /* Terminating Descriptor Tag Id -- [E] 3/10.9.1 */
        if(block[0]==8 && block[1]==0)
            goto default_sector;
    }

    /* Find the partition starting location -- [E] 3/10.5.8 */
    PD_sector  = block[188 + 0];
    PD_sector |= block[188 + 1] << 8;
    PD_sector |= block[188 + 2] << 16;
    PD_sector |= block[188 + 3] << 24;

    /* Find the partition length -- [E] 3/10.5.9 */
    PD_length  = block[192 + 0];
    PD_length |= block[192 + 1] << 8;
    PD_length |= block[192 + 2] << 16;
    PD_length |= block[192 + 3] << 24;

    for(i=PD_sector; i<PD_sector+PD_length; i++)
    {
        if(!VOLUME_ReadCDBlock(handle, block, i*BLOCK_SIZE))
            goto default_sector;

        /* File Set Descriptor Tag Id -- [E] 3/14.1.1 */
        if(block[0]==0 && block[1]==1)
            return i;
    }

default_sector:
    WARN("FSD sector not found, serial may be incorrect\n");
    return 257;
}


/**************************************************************************
 *                              VOLUME_GetSuperblockSerial
 */
static void VOLUME_GetSuperblockSerial( struct volume *volume, HANDLE handle, const BYTE *superblock )
{
    int FSD_sector;
    BYTE block[BLOCK_SIZE];

    switch (volume->fs_type)
    {
    case FS_ERROR:
        break;
    case FS_UNKNOWN:
        get_filesystem_serial( volume );
        break;
    case FS_FAT1216:
        volume->serial = GETLONG( superblock, 0x27 );
        break;
    case FS_FAT32:
        volume->serial = GETLONG( superblock, 0x43 );
        break;
    case FS_UDF:
        FSD_sector = UDF_Find_FSD_Sector(handle, block);
        if (!VOLUME_ReadCDBlock(handle, block, FSD_sector*BLOCK_SIZE))
            break;
        superblock = block;
        /* fallthrough */
    case FS_ISO9660:
        {
            BYTE sum[4];
            int i;

            sum[0] = sum[1] = sum[2] = sum[3] = 0;
            for (i = 0; i < 2048; i += 4)
            {
                /* DON'T optimize this into DWORD !! (breaks overflow) */
                sum[0] += superblock[i+0];
                sum[1] += superblock[i+1];
                sum[2] += superblock[i+2];
                sum[3] += superblock[i+3];
            }
            /*
             * OK, another braindead one... argh. Just believe it.
             * Me$$ysoft chose to reverse the serial number in NT4/W2K.
             * It's true and nobody will ever be able to change it.
             */
            if ((GetVersion() & 0x80000000) || volume->fs_type == FS_UDF)
                volume->serial = (sum[3] << 24) | (sum[2] << 16) | (sum[1] << 8) | sum[0];
            else
                volume->serial = (sum[0] << 24) | (sum[1] << 16) | (sum[2] << 8) | sum[3];
        }
    }
}


/**************************************************************************
 *                              VOLUME_GetAudioCDSerial
 */
static DWORD VOLUME_GetAudioCDSerial( const CDROM_TOC *toc )
{
    DWORD serial = 0;
    int i;

    for (i = 0; i <= toc->LastTrack - toc->FirstTrack; i++)
        serial += ((toc->TrackData[i].Address[1] << 16) |
                   (toc->TrackData[i].Address[2] << 8) |
                   toc->TrackData[i].Address[3]);

    /*
     * dwStart, dwEnd collect the beginning and end of the disc respectively, in
     * frames.
     * There it is collected for correcting the serial when there are less than
     * 3 tracks.
     */
    if (toc->LastTrack - toc->FirstTrack + 1 < 3)
    {
        DWORD dwStart = FRAME_OF_TOC(toc, toc->FirstTrack);
        DWORD dwEnd = FRAME_OF_TOC(toc, toc->LastTrack + 1);
        serial += dwEnd - dwStart;
    }
    return serial;
}


747 748
/* create the disk device for a given volume */
static NTSTATUS create_disk_device( enum device_type type, struct disk_device **device_ret )
749
{
750 751 752
    static const WCHAR harddiskvolW[] = {'\\','D','e','v','i','c','e',
                                         '\\','H','a','r','d','d','i','s','k','V','o','l','u','m','e','%','u',0};
    static const WCHAR harddiskW[] = {'\\','D','e','v','i','c','e','\\','H','a','r','d','d','i','s','k','%','u',0};
753 754
    static const WCHAR cdromW[] = {'\\','D','e','v','i','c','e','\\','C','d','R','o','m','%','u',0};
    static const WCHAR floppyW[] = {'\\','D','e','v','i','c','e','\\','F','l','o','p','p','y','%','u',0};
755
    static const WCHAR ramdiskW[] = {'\\','D','e','v','i','c','e','\\','R','a','m','d','i','s','k','%','u',0};
756
    static const WCHAR cdromlinkW[] = {'\\','?','?','\\','C','d','R','o','m','%','u',0};
757
    static const WCHAR physdriveW[] = {'\\','?','?','\\','P','h','y','s','i','c','a','l','D','r','i','v','e','%','u',0};
758 759 760

    UINT i, first = 0;
    NTSTATUS status = 0;
761
    const WCHAR *format = NULL;
762
    const WCHAR *link_format = NULL;
763
    UNICODE_STRING name;
764
    DEVICE_OBJECT *dev_obj;
765
    struct disk_device *device;
766 767 768

    switch(type)
    {
769 770 771 772
    case DEVICE_UNKNOWN:
    case DEVICE_HARDDISK:
    case DEVICE_NETWORK:  /* FIXME */
        format = harddiskW;
773
        link_format = physdriveW;
774 775 776 777 778 779
        break;
    case DEVICE_HARDDISK_VOL:
        format = harddiskvolW;
        first = 1;  /* harddisk volumes start counting from 1 */
        break;
    case DEVICE_FLOPPY:
780 781
        format = floppyW;
        break;
782
    case DEVICE_CDROM:
783
    case DEVICE_DVD:
784
        format = cdromW;
785
        link_format = cdromlinkW;
786
        break;
787 788
    case DEVICE_RAMDISK:
        format = ramdiskW;
789 790 791 792 793 794 795 796 797
        break;
    }

    name.MaximumLength = (strlenW(format) + 10) * sizeof(WCHAR);
    name.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, name.MaximumLength );
    for (i = first; i < 32; i++)
    {
        sprintfW( name.Buffer, format, i );
        name.Length = strlenW(name.Buffer) * sizeof(WCHAR);
798
        status = IoCreateDevice( harddisk_driver, sizeof(*device), &name, 0, 0, FALSE, &dev_obj );
799 800 801 802
        if (status != STATUS_OBJECT_NAME_COLLISION) break;
    }
    if (!status)
    {
803 804 805 806 807 808 809 810
        device = dev_obj->DeviceExtension;
        device->dev_obj        = dev_obj;
        device->name           = name;
        device->type           = type;
        device->unix_device    = NULL;
        device->unix_mount     = NULL;
        device->symlink.Buffer = NULL;

811 812 813 814 815 816 817 818 819 820 821 822 823
        if (link_format)
        {
            UNICODE_STRING symlink;

            symlink.MaximumLength = (strlenW(link_format) + 10) * sizeof(WCHAR);
            if ((symlink.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, symlink.MaximumLength)))
            {
                sprintfW( symlink.Buffer, link_format, i );
                symlink.Length = strlenW(symlink.Buffer) * sizeof(WCHAR);
                if (!IoCreateSymbolicLink( &symlink, &name )) device->symlink = symlink;
            }
        }

824
        switch (type)
825
        {
826 827
        case DEVICE_FLOPPY:
        case DEVICE_RAMDISK:
828 829 830
            device->devnum.DeviceType = FILE_DEVICE_DISK;
            device->devnum.DeviceNumber = i;
            device->devnum.PartitionNumber = ~0u;
831
            break;
832
        case DEVICE_CDROM:
833 834 835
            device->devnum.DeviceType = FILE_DEVICE_CD_ROM;
            device->devnum.DeviceNumber = i;
            device->devnum.PartitionNumber = ~0u;
836
            break;
837 838 839 840 841
        case DEVICE_DVD:
            device->devnum.DeviceType = FILE_DEVICE_DVD;
            device->devnum.DeviceNumber = i;
            device->devnum.PartitionNumber = ~0u;
            break;
842 843 844
        case DEVICE_UNKNOWN:
        case DEVICE_HARDDISK:
        case DEVICE_NETWORK:  /* FIXME */
845 846 847
            device->devnum.DeviceType = FILE_DEVICE_DISK;
            device->devnum.DeviceNumber = i;
            device->devnum.PartitionNumber = 0;
848 849
            break;
        case DEVICE_HARDDISK_VOL:
850 851 852
            device->devnum.DeviceType = FILE_DEVICE_DISK;
            device->devnum.DeviceNumber = 0;
            device->devnum.PartitionNumber = i;
853 854
            break;
        }
855
        *device_ret = device;
856
        TRACE( "created device %s\n", debugstr_w(name.Buffer) );
857 858 859 860 861 862 863 864 865
    }
    else
    {
        FIXME( "IoCreateDevice %s got %x\n", debugstr_w(name.Buffer), status );
        RtlFreeUnicodeString( &name );
    }
    return status;
}

866
/* delete the disk device for a given drive */
867 868 869 870 871 872 873 874 875 876
static void delete_disk_device( struct disk_device *device )
{
    TRACE( "deleting device %s\n", debugstr_w(device->name.Buffer) );
    if (device->symlink.Buffer)
    {
        IoDeleteSymbolicLink( &device->symlink );
        RtlFreeUnicodeString( &device->symlink );
    }
    RtlFreeHeap( GetProcessHeap(), 0, device->unix_device );
    RtlFreeHeap( GetProcessHeap(), 0, device->unix_mount );
877
    RtlFreeHeap( GetProcessHeap(), 0, device->serial );
878 879 880 881
    RtlFreeUnicodeString( &device->name );
    IoDeleteDevice( device->dev_obj );
}

882
/* grab another reference to a volume */
883
static struct volume *grab_volume( struct volume *volume )
884
{
885 886
    volume->ref++;
    return volume;
887 888 889 890 891 892 893 894 895
}

/* release a volume and delete the corresponding disk device when refcount is 0 */
static unsigned int release_volume( struct volume *volume )
{
    unsigned int ret = --volume->ref;

    if (!ret)
    {
896
        TRACE( "%s udi %s\n", debugstr_guid(&volume->guid), debugstr_a(volume->udi) );
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
        assert( !volume->udi );
        list_remove( &volume->entry );
        if (volume->mount) delete_mount_point( volume->mount );
        delete_disk_device( volume->device );
        RtlFreeHeap( GetProcessHeap(), 0, volume );
    }
    return ret;
}

/* set the volume udi */
static void set_volume_udi( struct volume *volume, const char *udi )
{
    if (udi)
    {
        assert( !volume->udi );
        /* having a udi means the HAL side holds an extra reference */
        if ((volume->udi = strdupA( udi ))) grab_volume( volume );
    }
    else if (volume->udi)
    {
        RtlFreeHeap( GetProcessHeap(), 0, volume->udi );
        volume->udi = NULL;
        release_volume( volume );
    }
}

923 924 925 926 927 928 929 930 931 932 933
/* create a disk volume */
static NTSTATUS create_volume( const char *udi, enum device_type type, struct volume **volume_ret )
{
    struct volume *volume;
    NTSTATUS status;

    if (!(volume = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*volume) )))
        return STATUS_NO_MEMORY;

    if (!(status = create_disk_device( type, &volume->device )))
    {
934
        if (udi) set_volume_udi( volume, udi );
935
        list_add_tail( &volumes_list, &volume->entry );
936
        *volume_ret = grab_volume( volume );
937
    }
938
    else RtlFreeHeap( GetProcessHeap(), 0, volume );
939

940
    return status;
941 942
}

943
/* create the disk device for a given volume */
944 945
static NTSTATUS create_dos_device( struct volume *volume, const char *udi, int letter,
                                   enum device_type type, struct dos_drive **drive_ret )
946 947 948 949 950
{
    struct dos_drive *drive;
    NTSTATUS status;

    if (!(drive = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*drive) ))) return STATUS_NO_MEMORY;
951
    drive->drive = letter;
952
    drive->mount = NULL;
953

954 955 956
    if (volume)
    {
        if (udi) set_volume_udi( volume, udi );
957
        drive->volume = grab_volume( volume );
958 959 960 961 962
        status = STATUS_SUCCESS;
    }
    else status = create_volume( udi, type, &drive->volume );

    if (status == STATUS_SUCCESS)
963 964 965 966
    {
        list_add_tail( &drives_list, &drive->entry );
        *drive_ret = drive;
    }
967 968
    else RtlFreeHeap( GetProcessHeap(), 0, drive );

969 970 971 972 973
    return status;
}

/* delete the disk device for a given drive */
static void delete_dos_device( struct dos_drive *drive )
974 975
{
    list_remove( &drive->entry );
976
    if (drive->mount) delete_mount_point( drive->mount );
977
    release_volume( drive->volume );
978
    RtlFreeHeap( GetProcessHeap(), 0, drive );
979 980
}

981 982 983 984 985 986 987 988 989
/* find a volume that matches the parameters */
static struct volume *find_matching_volume( const char *udi, const char *device,
                                            const char *mount_point, enum device_type type )
{
    struct volume *volume;
    struct disk_device *disk_device;

    LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
    {
990 991
        int match = 0;

992 993 994 995 996 997 998
        /* when we have a udi we only match drives added manually */
        if (udi && volume->udi) continue;
        /* and when we don't have a udi we only match dynamic drives */
        if (!udi && !volume->udi) continue;

        disk_device = volume->device;
        if (disk_device->type != type) continue;
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
        if (device && disk_device->unix_device)
        {
            if (strcmp( device, disk_device->unix_device )) continue;
            match++;
        }
        if (mount_point && disk_device->unix_mount)
        {
            if (strcmp( mount_point, disk_device->unix_mount )) continue;
            match++;
        }
        if (!match) continue;
1010 1011
        TRACE( "found matching volume %s for device %s mount %s type %u\n",
               debugstr_guid(&volume->guid), debugstr_a(device), debugstr_a(mount_point), type );
1012
        return grab_volume( volume );
1013 1014 1015 1016
    }
    return NULL;
}

1017 1018 1019
static BOOL get_volume_device_info( struct volume *volume )
{
    const char *unix_device = volume->device->unix_device;
1020
    WCHAR *name;
1021 1022 1023 1024 1025 1026 1027 1028
    HANDLE handle;
    CDROM_TOC toc;
    DWORD size;
    BYTE superblock[SUPERBLOCK_SIZE];

    if (!unix_device)
        return FALSE;

1029
    if (!(name = wine_get_dos_file_name( unix_device )))
1030
    {
1031
        ERR("Failed to convert %s to NT, err %u\n", debugstr_a(unix_device), GetLastError());
1032 1033
        return FALSE;
    }
1034 1035 1036 1037
    handle = CreateFileW( name, GENERIC_READ | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL, OPEN_EXISTING, 0, 0 );
    RtlFreeHeap( GetProcessHeap(), 0, name );
    if (handle == INVALID_HANDLE_VALUE)
1038
    {
1039
        WARN("Failed to open %s, err %u\n", debugstr_a(unix_device), GetLastError());
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
        return FALSE;
    }

    if (DeviceIoControl( handle, IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc), &size, 0 ))
    {
        if (!(toc.TrackData[0].Control & 0x04))  /* audio track */
        {
            static const WCHAR audiocdW[] = {'A','u','d','i','o',' ','C','D',0};
            TRACE( "%s: found audio CD\n", debugstr_a(unix_device) );
            lstrcpynW( volume->label, audiocdW, ARRAY_SIZE(volume->label) );
            volume->serial = VOLUME_GetAudioCDSerial( &toc );
            volume->fs_type = FS_ISO9660;
            CloseHandle( handle );
            return TRUE;
        }
        volume->fs_type = VOLUME_ReadCDSuperblock( handle, superblock );
    }
    else
    {
        volume->fs_type = VOLUME_ReadFATSuperblock( handle, superblock );
        if (volume->fs_type == FS_UNKNOWN) volume->fs_type = VOLUME_ReadCDSuperblock( handle, superblock );
    }

    TRACE( "%s: found fs type %d\n", debugstr_a(unix_device), volume->fs_type );
    if (volume->fs_type == FS_ERROR)
    {
        CloseHandle( handle );
        return FALSE;
    }

    VOLUME_GetSuperblockLabel( volume, handle, superblock );
    VOLUME_GetSuperblockSerial( volume, handle, superblock );

    CloseHandle( handle );
    return TRUE;
}

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
/* set disk serial for dos devices that reside on a given Unix device */
static void set_dos_devices_disk_serial( struct disk_device *device )
{
    struct dos_drive *drive;
    struct stat dev_st, drive_st;
    char *path, *p;

    if (!device->serial || !device->unix_mount || stat( device->unix_mount, &dev_st ) == -1) return;

    if (!(path = get_dosdevices_path( &p ))) return;
    p[2] = 0;

    LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
    {
        /* drives mapped to Unix devices already have serial set, if available */
        if (drive->volume->device->unix_device) continue;

        p[0] = 'a' + drive->drive;

        /* copy serial if drive resides on this Unix device */
        if (stat( path, &drive_st ) != -1 && drive_st.st_rdev == dev_st.st_rdev)
        {
            HeapFree( GetProcessHeap(), 0, drive->volume->device->serial );
            drive->volume->device->serial = strdupA( device->serial );
        }
    }

    HeapFree( GetProcessHeap(), 0, path );
}

1107
/* change the information for an existing volume */
1108
static NTSTATUS set_volume_info( struct volume *volume, struct dos_drive *drive, const char *device,
1109 1110
                                 const char *mount_point, enum device_type type, const GUID *guid,
                                 const char *disk_serial )
1111
{
1112 1113
    void *id = NULL;
    unsigned int id_len = 0;
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    struct disk_device *disk_device = volume->device;
    NTSTATUS status;

    if (type != disk_device->type)
    {
        if ((status = create_disk_device( type, &disk_device ))) return status;
        if (volume->mount)
        {
            delete_mount_point( volume->mount );
            volume->mount = NULL;
        }
1125 1126 1127 1128 1129
        if (drive && drive->mount)
        {
            delete_mount_point( drive->mount );
            drive->mount = NULL;
        }
1130 1131 1132 1133 1134 1135 1136
        delete_disk_device( volume->device );
        volume->device = disk_device;
    }
    else
    {
        RtlFreeHeap( GetProcessHeap(), 0, disk_device->unix_device );
        RtlFreeHeap( GetProcessHeap(), 0, disk_device->unix_mount );
1137
        RtlFreeHeap( GetProcessHeap(), 0, disk_device->serial );
1138 1139 1140
    }
    disk_device->unix_device = strdupA( device );
    disk_device->unix_mount = strdupA( mount_point );
1141 1142
    disk_device->serial = strdupA( disk_serial );
    set_dos_devices_disk_serial( disk_device );
1143

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    if (!get_volume_device_info( volume ))
    {
        if (volume->device->type == DEVICE_CDROM)
            volume->fs_type = FS_ISO9660;
        else if (volume->device->type == DEVICE_DVD)
            volume->fs_type = FS_UDF;
        else
            volume->fs_type = FS_UNKNOWN;

        get_filesystem_label( volume );
        get_filesystem_serial( volume );
    }

    TRACE("fs_type %#x, label %s, serial %08x\n", volume->fs_type, debugstr_w(volume->label), volume->serial);

1159
    if (guid && memcmp( &volume->guid, guid, sizeof(volume->guid) ))
1160 1161 1162 1163 1164 1165 1166 1167 1168
    {
        volume->guid = *guid;
        if (volume->mount)
        {
            delete_mount_point( volume->mount );
            volume->mount = NULL;
        }
    }

1169 1170 1171
    if (!volume->serial)
        memcpy(&volume->serial, &volume->guid.Data4[4], sizeof(DWORD));

1172 1173
    if (!volume->mount)
        volume->mount = add_volume_mount_point( disk_device->dev_obj, &disk_device->name, &volume->guid );
1174 1175
    if (drive && !drive->mount)
        drive->mount = add_dosdev_mount_point( disk_device->dev_obj, &disk_device->name, drive->drive );
1176

1177
    if (disk_device->unix_mount)
1178
    {
1179 1180
        id = disk_device->unix_mount;
        id_len = strlen( disk_device->unix_mount ) + 1;
1181
    }
1182 1183 1184
    if (volume->mount) set_mount_point_id( volume->mount, id, id_len );
    if (drive && drive->mount) set_mount_point_id( drive->mount, id, id_len );

1185 1186 1187
    return STATUS_SUCCESS;
}

1188 1189
/* change the drive letter or volume for an existing drive */
static void set_drive_info( struct dos_drive *drive, int letter, struct volume *volume )
1190
{
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    if (drive->drive != letter)
    {
        if (drive->mount) delete_mount_point( drive->mount );
        drive->mount = NULL;
        drive->drive = letter;
    }
    if (drive->volume != volume)
    {
        if (drive->mount) delete_mount_point( drive->mount );
        drive->mount = NULL;
        grab_volume( volume );
        release_volume( drive->volume );
        drive->volume = volume;
    }
1205
}
1206

1207
static inline BOOL is_valid_device( struct stat *st )
1208 1209 1210 1211 1212 1213 1214 1215 1216
{
#if defined(linux) || defined(__sun__)
    return S_ISBLK( st->st_mode );
#else
    /* disks are char devices on *BSD */
    return S_ISCHR( st->st_mode );
#endif
}

1217
/* find or create a DOS drive for the corresponding device */
1218
static int add_drive( const char *device, enum device_type type )
1219 1220 1221 1222 1223 1224
{
    char *path, *p;
    char in_use[26];
    struct stat dev_st, drive_st;
    int drive, first, last, avail = 0;

1225
    if (stat( device, &dev_st ) == -1 || !is_valid_device( &dev_st )) return -1;
1226

1227
    if (!(path = get_dosdevices_path( &p ))) return -1;
1228 1229 1230

    memset( in_use, 0, sizeof(in_use) );

1231
    switch (type)
1232
    {
1233
    case DEVICE_FLOPPY:
1234 1235
        first = 0;
        last = 2;
1236 1237
        break;
    case DEVICE_CDROM:
1238
    case DEVICE_DVD:
1239 1240 1241 1242 1243 1244 1245
        first = 3;
        last = 26;
        break;
    default:
        first = 2;
        last = 26;
        break;
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
    }

    while (avail != -1)
    {
        avail = -1;
        for (drive = first; drive < last; drive++)
        {
            if (in_use[drive]) continue;  /* already checked */
            *p = 'a' + drive;
            if (stat( path, &drive_st ) == -1)
            {
                if (lstat( path, &drive_st ) == -1 && errno == ENOENT)  /* this is a candidate */
                {
                    if (avail == -1)
                    {
                        p[2] = 0;
                        /* if mount point symlink doesn't exist either, it's available */
                        if (lstat( path, &drive_st ) == -1 && errno == ENOENT) avail = drive;
                        p[2] = ':';
                    }
                }
                else in_use[drive] = 1;
            }
            else
            {
                in_use[drive] = 1;
1272
                if (!is_valid_device( &drive_st )) continue;
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
                if (dev_st.st_rdev == drive_st.st_rdev) goto done;
            }
        }
        if (avail != -1)
        {
            /* try to use the one we found */
            drive = avail;
            *p = 'a' + drive;
            if (symlink( device, path ) != -1) goto done;
            /* failed, retry the search */
        }
    }
    drive = -1;

done:
    HeapFree( GetProcessHeap(), 0, path );
    return drive;
}

1292 1293
/* create devices for mapped drives */
static void create_drive_devices(void)
1294
{
1295
    char *path, *p, *link, *device;
1296
    struct dos_drive *drive;
1297
    struct volume *volume;
1298
    unsigned int i;
1299
    HKEY drives_key;
1300
    enum device_type drive_type;
1301
    WCHAR driveW[] = {'a',':',0};
1302

1303
    if (!(path = get_dosdevices_path( &p ))) return;
1304
    if (RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &drives_key )) drives_key = 0;
1305

1306 1307 1308 1309 1310
    for (i = 0; i < MAX_DOS_DRIVES; i++)
    {
        p[0] = 'a' + i;
        p[2] = 0;
        if (!(link = read_symlink( path ))) continue;
1311 1312
        p[2] = ':';
        device = read_symlink( path );
1313

1314
        drive_type = i < 2 ? DEVICE_FLOPPY : DEVICE_HARDDISK_VOL;
1315 1316 1317 1318 1319 1320 1321 1322 1323
        if (drives_key)
        {
            WCHAR buffer[32];
            DWORD j, type, size = sizeof(buffer);

            driveW[0] = 'a' + i;
            if (!RegQueryValueExW( drives_key, driveW, NULL, &type, (BYTE *)buffer, &size ) &&
                type == REG_SZ)
            {
1324
                for (j = 0; j < ARRAY_SIZE(drive_types); j++)
1325 1326 1327 1328 1329
                    if (drive_types[j][0] && !strcmpiW( buffer, drive_types[j] ))
                    {
                        drive_type = j;
                        break;
                    }
1330
                if (drive_type == DEVICE_FLOPPY && i >= 2) drive_type = DEVICE_HARDDISK;
1331 1332 1333
            }
        }

1334 1335
        volume = find_matching_volume( NULL, device, link, drive_type );
        if (!create_dos_device( volume, NULL, i, drive_type, &drive ))
1336
        {
1337 1338
            /* don't reset uuid if we used an existing volume */
            const GUID *guid = volume ? NULL : get_default_uuid(i);
1339
            set_volume_info( drive->volume, drive, device, link, drive_type, guid, NULL );
1340
        }
1341 1342 1343 1344 1345
        else
        {
            RtlFreeHeap( GetProcessHeap(), 0, link );
            RtlFreeHeap( GetProcessHeap(), 0, device );
        }
1346
        if (volume) release_volume( volume );
1347
    }
1348
    RegCloseKey( drives_key );
1349
    RtlFreeHeap( GetProcessHeap(), 0, path );
1350 1351
}

1352 1353 1354 1355 1356 1357 1358 1359
/* open the "Logical Unit" key for a given SCSI address */
static HKEY get_scsi_device_lun_key( SCSI_ADDRESS *scsi_addr )
{
    WCHAR dataW[50];
    HKEY scsi_key, port_key, bus_key, target_key, lun_key;

    if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, scsi_keyW, 0, KEY_READ|KEY_WRITE, &scsi_key )) return NULL;

1360
    snprintfW( dataW, ARRAY_SIZE( dataW ), scsi_port_keyW, scsi_addr->PortNumber );
1361 1362 1363
    if (RegCreateKeyExW( scsi_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &port_key, NULL )) return NULL;
    RegCloseKey( scsi_key );

1364
    snprintfW( dataW, ARRAY_SIZE( dataW ), scsi_bus_keyW, scsi_addr->PathId );
1365 1366 1367
    if (RegCreateKeyExW( port_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &bus_key, NULL )) return NULL;
    RegCloseKey( port_key );

1368
    snprintfW( dataW, ARRAY_SIZE( dataW ), target_id_keyW, scsi_addr->TargetId );
1369 1370 1371
    if (RegCreateKeyExW( bus_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &target_key, NULL )) return NULL;
    RegCloseKey( bus_key );

1372
    snprintfW( dataW, ARRAY_SIZE( dataW ), lun_keyW, scsi_addr->Lun );
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    if (RegCreateKeyExW( target_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &lun_key, NULL )) return NULL;
    RegCloseKey( target_key );

    return lun_key;
}

/* fill in the "Logical Unit" key for a given SCSI address */
void create_scsi_entry( SCSI_ADDRESS *scsi_addr, UINT init_id, const char *driver, UINT type, const char *model, const UNICODE_STRING *dev )
{
    static UCHAR tape_no = 0;
    static const WCHAR tapeW[] = {'T','a','p','e','%','d',0};
    static const WCHAR init_id_keyW[] = {'I','n','i','t','i','a','t','o','r',' ','I','d',' ','%','d',0};
    static const WCHAR driverW[] = {'D','r','i','v','e','r',0};
    static const WCHAR bus_time_scanW[] = {'F','i','r','s','t','B','u','s','T','i','m','e','S','c','a','n','I','n','M','s',0};
    static const WCHAR typeW[] = {'T','y','p','e',0};
    static const WCHAR identW[] = {'I','d','e','n','t','i','f','i','e','r',0};

    WCHAR dataW[50];
    DWORD sizeW;
    DWORD value;
    const char *data;
    HKEY scsi_key;
    HKEY port_key;
    HKEY bus_key;
    HKEY target_key;
    HKEY lun_key;

    if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, scsi_keyW, 0, KEY_READ|KEY_WRITE, &scsi_key )) return;

1402
    snprintfW( dataW, ARRAY_SIZE( dataW ), scsi_port_keyW, scsi_addr->PortNumber );
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
    if (RegCreateKeyExW( scsi_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &port_key, NULL )) return;
    RegCloseKey( scsi_key );

    RtlMultiByteToUnicodeN( dataW, sizeof(dataW), &sizeW, driver, strlen(driver)+1);
    RegSetValueExW( port_key, driverW, 0, REG_SZ, (const BYTE *)dataW, sizeW );
    value = 10;
    RegSetValueExW( port_key, bus_time_scanW, 0, REG_DWORD, (const BYTE *)&value, sizeof(value));

    value = 0;

1413
    snprintfW( dataW, ARRAY_SIZE( dataW ), scsi_bus_keyW, scsi_addr->PathId );
1414 1415 1416
    if (RegCreateKeyExW( port_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &bus_key, NULL )) return;
    RegCloseKey( port_key );

1417
    snprintfW( dataW, ARRAY_SIZE( dataW ), init_id_keyW, init_id );
1418 1419 1420
    if (RegCreateKeyExW( bus_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &target_key, NULL )) return;
    RegCloseKey( target_key );

1421
    snprintfW( dataW, ARRAY_SIZE( dataW ), target_id_keyW, scsi_addr->TargetId );
1422 1423 1424
    if (RegCreateKeyExW( bus_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &target_key, NULL )) return;
    RegCloseKey( bus_key );

1425
    snprintfW( dataW, ARRAY_SIZE( dataW ), lun_keyW, scsi_addr->Lun );
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    if (RegCreateKeyExW( target_key, dataW, 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &lun_key, NULL )) return;
    RegCloseKey( target_key );

    switch (type)
    {
    case SCSI_DISK_PERIPHERAL:              data = "DiskPeripheral"; break;
    case SCSI_TAPE_PERIPHERAL:              data = "TapePeripheral"; break;
    case SCSI_PRINTER_PERIPHERAL:           data = "PrinterPeripheral"; break;
    case SCSI_WORM_PERIPHERAL:              data = "WormPeripheral"; break;
    case SCSI_CDROM_PERIPHERAL:             data = "CdRomPeripheral"; break;
    case SCSI_SCANNER_PERIPHERAL:           data = "ScannerPeripheral"; break;
    case SCSI_OPTICAL_DISK_PERIPHERAL:      data = "OpticalDiskPeripheral"; break;
    case SCSI_MEDIUM_CHANGER_PERIPHERAL:    data = "MediumChangerPeripheral"; break;
    case SCSI_COMMS_PERIPHERAL:             data = "CommunicationsPeripheral"; break;
    case SCSI_ASC_GRAPHICS_PERIPHERAL:
    case SCSI_ASC_GRAPHICS2_PERIPHERAL:     data = "ASCPrePressGraphicsPeripheral"; break;
    case SCSI_ARRAY_PERIPHERAL:             data = "ArrayPeripheral"; break;
    case SCSI_ENCLOSURE_PERIPHERAL:         data = "EnclosurePeripheral"; break;
    case SCSI_REDUCED_DISK_PERIPHERAL:      data = "RBCPeripheral"; break;
    case SCSI_CARD_READER_PERIPHERAL:       data = "CardReaderPeripheral"; break;
    case SCSI_BRIDGE_PERIPHERAL:            data = "BridgePeripheral"; break;
    case SCSI_OBJECT_STORAGE_PERIPHERAL:    /* Object-based storage devices */
    case SCSI_DRIVE_CONTROLLER_PERIPHERAL:  /* Automation/drive controllers */
    case SCSI_REDUCED_CDROM_PERIPHERAL:     /* Reduced-commands MM devices */
    case SCSI_PROCESSOR_PERIPHERAL:         /* Processor devices (considered to be "Other" by Windows) */
    default:                                data = "OtherPeripheral"; break;
    }
    RtlMultiByteToUnicodeN( dataW, sizeof(dataW), &sizeW, data, strlen(data)+1);
    RegSetValueExW( lun_key, typeW, 0, REG_SZ, (const BYTE *)dataW, sizeW );

    RtlMultiByteToUnicodeN( dataW, sizeof(dataW), &sizeW, model, strlen(model)+1);
    RegSetValueExW( lun_key, identW, 0, REG_SZ, (const BYTE *)dataW, sizeW );

    if (dev)
    {
        WCHAR *buffer = memchrW( dev->Buffer+1, '\\', dev->Length )+1;
        ULONG length = dev->Length - (buffer - dev->Buffer)*sizeof(WCHAR);
        RegSetValueExW( lun_key, devnameW, 0, REG_SZ, (const BYTE *)buffer, length );
    }
    else if (type == SCSI_TAPE_PERIPHERAL)
    {
1467
        snprintfW( dataW, ARRAY_SIZE( dataW ), tapeW, tape_no++ );
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        RegSetValueExW( lun_key, devnameW, 0, REG_SZ, (const BYTE *)dataW, strlenW( dataW ) );
    }

    RegCloseKey( lun_key );
}

/* set the "DeviceName" for a given SCSI address */
void set_scsi_device_name( SCSI_ADDRESS *scsi_addr, const UNICODE_STRING *dev )
{
    HKEY lun_key;
    WCHAR *buffer;
    ULONG length;

    lun_key = get_scsi_device_lun_key( scsi_addr );
    buffer = memchrW( dev->Buffer+1, '\\', dev->Length )+1;
    length = dev->Length - (buffer - dev->Buffer)*sizeof(WCHAR);
    RegSetValueExW( lun_key, devnameW, 0, REG_SZ, (const BYTE *)buffer, length );

    RegCloseKey( lun_key );
}


1490 1491
/* create a new disk volume */
NTSTATUS add_volume( const char *udi, const char *device, const char *mount_point,
1492
                     enum device_type type, const GUID *guid, const char *disk_serial )
1493 1494
{
    struct volume *volume;
1495
    NTSTATUS status = STATUS_SUCCESS;
1496 1497 1498 1499

    TRACE( "adding %s device %s mount %s type %u uuid %s\n", debugstr_a(udi),
           debugstr_a(device), debugstr_a(mount_point), type, debugstr_guid(guid) );

1500
    EnterCriticalSection( &device_section );
1501
    LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
1502 1503 1504 1505 1506
        if (volume->udi && !strcmp( udi, volume->udi ))
        {
            grab_volume( volume );
            goto found;
        }
1507

1508
    /* udi not found, search for a non-dynamic volume */
1509 1510
    if ((volume = find_matching_volume( udi, device, mount_point, type ))) set_volume_udi( volume, udi );
    else status = create_volume( udi, type, &volume );
1511 1512

found:
1513
    if (!status) status = set_volume_info( volume, NULL, device, mount_point, type, guid, disk_serial );
1514
    if (volume) release_volume( volume );
1515 1516
    LeaveCriticalSection( &device_section );
    return status;
1517 1518
}

1519
/* remove a disk volume */
1520 1521
NTSTATUS remove_volume( const char *udi )
{
1522
    NTSTATUS status = STATUS_NO_SUCH_DEVICE;
1523 1524
    struct volume *volume;

1525
    EnterCriticalSection( &device_section );
1526 1527 1528
    LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
    {
        if (!volume->udi || strcmp( udi, volume->udi )) continue;
1529
        set_volume_udi( volume, NULL );
1530 1531
        status = STATUS_SUCCESS;
        break;
1532
    }
1533 1534
    LeaveCriticalSection( &device_section );
    return status;
1535 1536 1537
}


1538 1539
/* create a new dos drive */
NTSTATUS add_dos_device( int letter, const char *udi, const char *device,
1540 1541
                         const char *mount_point, enum device_type type, const GUID *guid,
                         UNICODE_STRING *devname )
1542
{
1543
    char *path, *p;
1544
    HKEY hkey;
1545
    NTSTATUS status = STATUS_SUCCESS;
1546
    struct dos_drive *drive, *next;
1547 1548
    struct volume *volume;
    int notify = -1;
1549

1550 1551
    if (!(path = get_dosdevices_path( &p ))) return STATUS_NO_MEMORY;

1552 1553 1554
    EnterCriticalSection( &device_section );
    volume = find_matching_volume( udi, device, mount_point, type );

1555 1556 1557
    if (letter == -1)  /* auto-assign a letter */
    {
        letter = add_drive( device, type );
1558 1559 1560 1561 1562
        if (letter == -1)
        {
            status = STATUS_OBJECT_NAME_COLLISION;
            goto done;
        }
1563 1564 1565 1566 1567 1568

        LIST_FOR_EACH_ENTRY_SAFE( drive, next, &drives_list, struct dos_drive, entry )
        {
            if (drive->volume->udi && !strcmp( udi, drive->volume->udi )) goto found;
            if (drive->drive == letter) delete_dos_device( drive );
        }
1569 1570 1571
    }
    else  /* simply reset the device symlink */
    {
1572
        LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
1573 1574 1575 1576 1577
            if (drive->drive == letter) break;

        *p = 'a' + letter;
        if (&drive->entry == &drives_list) update_symlink( path, device, NULL );
        else
1578
        {
1579
            update_symlink( path, device, drive->volume->device->unix_device );
1580
            delete_dos_device( drive );
1581
        }
1582
    }
1583

1584
    if ((status = create_dos_device( volume, udi, letter, type, &drive ))) goto done;
1585 1586

found:
1587
    if (!guid && !volume) guid = get_default_uuid( letter );
1588
    if (!volume) volume = grab_volume( drive->volume );
1589
    set_drive_info( drive, letter, volume );
1590 1591
    p[0] = 'a' + drive->drive;
    p[2] = 0;
1592
    update_symlink( path, mount_point, volume->device->unix_mount );
1593
    set_volume_info( volume, drive, device, mount_point, type, guid, NULL );
1594

1595 1596 1597 1598 1599 1600
    TRACE( "added device %c: udi %s for %s on %s type %u\n",
           'a' + drive->drive, wine_dbgstr_a(udi), wine_dbgstr_a(device),
           wine_dbgstr_a(mount_point), type );

    /* hack: force the drive type in the registry */
    if (!RegCreateKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
1601
    {
1602
        const WCHAR *type_name = drive_types[type];
1603
        WCHAR name[] = {'a',':',0};
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613

        name[0] += drive->drive;
        if (!type_name[0] && type == DEVICE_HARDDISK) type_name = drive_types[DEVICE_FLOPPY];
        if (type_name[0])
            RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)type_name,
                            (strlenW(type_name) + 1) * sizeof(WCHAR) );
        else
            RegDeleteValueW( hkey, name );
        RegCloseKey( hkey );
    }
1614

1615
    if (udi) notify = drive->drive;
1616

1617 1618
    if (devname) *devname = volume->device->name;

1619
done:
1620
    if (volume) release_volume( volume );
1621
    LeaveCriticalSection( &device_section );
1622
    RtlFreeHeap( GetProcessHeap(), 0, path );
1623
    if (notify != -1) send_notify( notify, DBT_DEVICEARRIVAL );
1624
    return status;
1625 1626
}

1627 1628
/* remove an existing dos drive, by letter or udi */
NTSTATUS remove_dos_device( int letter, const char *udi )
1629
{
1630
    NTSTATUS status = STATUS_NO_SUCH_DEVICE;
1631 1632
    HKEY hkey;
    struct dos_drive *drive;
1633
    char *path, *p;
1634
    int notify = -1;
1635

1636
    EnterCriticalSection( &device_section );
1637 1638
    LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
    {
1639 1640
        if (udi)
        {
1641 1642
            if (!drive->volume->udi) continue;
            if (strcmp( udi, drive->volume->udi )) continue;
1643
            set_volume_udi( drive->volume, NULL );
1644
        }
1645
        else if (drive->drive != letter) continue;
1646

1647
        if ((path = get_dosdevices_path( &p )))
1648
        {
1649 1650 1651 1652 1653
            p[0] = 'a' + drive->drive;
            p[2] = 0;
            unlink( path );
            RtlFreeHeap( GetProcessHeap(), 0, path );
        }
1654

1655 1656 1657
        /* clear the registry key too */
        if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
        {
1658
            WCHAR name[] = {'a',':',0};
1659 1660 1661
            name[0] += drive->drive;
            RegDeleteValueW( hkey, name );
            RegCloseKey( hkey );
1662
        }
1663

1664
        if (udi && drive->volume->device->unix_mount) notify = drive->drive;
1665

1666
        delete_dos_device( drive );
1667 1668
        status = STATUS_SUCCESS;
        break;
1669
    }
1670 1671 1672
    LeaveCriticalSection( &device_section );
    if (notify != -1) send_notify( notify, DBT_DEVICEREMOVECOMPLETE );
    return status;
1673
}
1674

1675
static enum mountmgr_fs_type get_mountmgr_fs_type(enum fs_type fs_type)
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
{
    switch (fs_type)
    {
    case FS_ISO9660: return MOUNTMGR_FS_TYPE_ISO9660;
    case FS_UDF:     return MOUNTMGR_FS_TYPE_UDF;
    case FS_FAT1216: return MOUNTMGR_FS_TYPE_FAT;
    case FS_FAT32:   return MOUNTMGR_FS_TYPE_FAT32;
    default:         return MOUNTMGR_FS_TYPE_NTFS;
    }
}

1687
/* query information about an existing dos drive, by letter or udi */
1688
NTSTATUS query_dos_device( int letter, enum device_type *type, enum mountmgr_fs_type *fs_type,
1689
                           DWORD *serial, char **device, char **mount_point, WCHAR **label )
1690
{
1691
    NTSTATUS status = STATUS_NO_SUCH_DEVICE;
1692
    struct dos_drive *drive;
1693
    struct disk_device *disk_device;
1694

1695
    EnterCriticalSection( &device_section );
1696 1697 1698
    LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
    {
        if (drive->drive != letter) continue;
1699
        disk_device = drive->volume->device;
1700
        if (type) *type = disk_device->type;
1701
        if (fs_type) *fs_type = get_mountmgr_fs_type( drive->volume->fs_type );
1702
        if (serial) *serial = drive->volume->serial;
1703 1704
        if (device) *device = strdupA( disk_device->unix_device );
        if (mount_point) *mount_point = strdupA( disk_device->unix_mount );
1705
        if (label) *label = strdupW( drive->volume->label );
1706 1707 1708 1709 1710 1711 1712 1713 1714
        status = STATUS_SUCCESS;
        break;
    }
    LeaveCriticalSection( &device_section );
    return status;
}

/* query information about an existing unix device, by dev_t */
NTSTATUS query_unix_device( ULONGLONG unix_dev, enum device_type *type,
1715 1716
                            enum mountmgr_fs_type *fs_type, DWORD *serial, char **device,
                            char **mount_point, WCHAR **label )
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
{
    NTSTATUS status = STATUS_NO_SUCH_DEVICE;
    struct volume *volume;
    struct disk_device *disk_device;
    struct stat st;

    EnterCriticalSection( &device_section );
    LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
    {
        disk_device = volume->device;

        if (!disk_device->unix_device
            || stat( disk_device->unix_device, &st ) < 0
            || st.st_rdev != unix_dev)
            continue;

        if (type) *type = disk_device->type;
        if (fs_type) *fs_type = get_mountmgr_fs_type( volume->fs_type );
1735
        if (serial) *serial = volume->serial;
1736 1737
        if (device) *device = strdupA( disk_device->unix_device );
        if (mount_point) *mount_point = strdupA( disk_device->unix_mount );
1738
        if (label) *label = strdupW( volume->label );
1739 1740
        status = STATUS_SUCCESS;
        break;
1741
    }
1742 1743
    LeaveCriticalSection( &device_section );
    return status;
1744 1745
}

1746
static void query_property( struct disk_device *device, IRP *irp )
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
{
    IO_STACK_LOCATION *irpsp = IoGetCurrentIrpStackLocation( irp );
    STORAGE_PROPERTY_QUERY *query = irp->AssociatedIrp.SystemBuffer;

    if (!irp->AssociatedIrp.SystemBuffer
        || irpsp->Parameters.DeviceIoControl.InputBufferLength < sizeof(STORAGE_PROPERTY_QUERY))
    {
        irp->IoStatus.u.Status = STATUS_INVALID_PARAMETER;
        return;
    }

    /* Try to persuade application not to check property */
    if (query->QueryType == PropertyExistsQuery)
    {
        irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
        return;
    }

    switch (query->PropertyId)
    {
    case StorageDeviceProperty:
    {
        STORAGE_DEVICE_DESCRIPTOR *descriptor;
1770 1771 1772
        DWORD len = sizeof(*descriptor);

        if (device->serial) len += strlen( device->serial ) + 1;
1773

1774
        if (irpsp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(STORAGE_DESCRIPTOR_HEADER))
1775
            irp->IoStatus.u.Status = STATUS_INVALID_PARAMETER;
1776
        else if (irpsp->Parameters.DeviceIoControl.OutputBufferLength < len)
1777
        {
1778
            descriptor = irp->AssociatedIrp.SystemBuffer;
1779
            descriptor->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR);
1780
            descriptor->Size = len;
1781 1782 1783 1784 1785 1786 1787
            irp->IoStatus.Information = sizeof(STORAGE_DESCRIPTOR_HEADER);
            irp->IoStatus.u.Status = STATUS_SUCCESS;
        }
        else
        {
            FIXME( "Faking StorageDeviceProperty data\n" );

1788 1789
            memset( irp->AssociatedIrp.SystemBuffer, 0, irpsp->Parameters.DeviceIoControl.OutputBufferLength );
            descriptor = irp->AssociatedIrp.SystemBuffer;
1790
            descriptor->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR);
1791
            descriptor->Size = len;
1792 1793 1794 1795 1796 1797 1798 1799 1800
            descriptor->DeviceType = FILE_DEVICE_DISK;
            descriptor->DeviceTypeModifier = 0;
            descriptor->RemovableMedia = FALSE;
            descriptor->CommandQueueing = FALSE;
            descriptor->VendorIdOffset = 0;
            descriptor->ProductIdOffset = 0;
            descriptor->ProductRevisionOffset = 0;
            descriptor->BusType = BusTypeScsi;
            descriptor->RawPropertiesLength = 0;
1801 1802 1803 1804 1805 1806 1807
            if (!device->serial) descriptor->SerialNumberOffset = 0;
            else
            {
                descriptor->SerialNumberOffset = sizeof(*descriptor);
                strcpy( (char *)descriptor + descriptor->SerialNumberOffset, device->serial );
            }
            irp->IoStatus.Information = len;
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
            irp->IoStatus.u.Status = STATUS_SUCCESS;
        }

        break;
    }
    default:
        FIXME( "Unsupported property %#x\n", query->PropertyId );
        irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
        break;
    }
}

1820 1821 1822
/* handler for ioctls on the harddisk device */
static NTSTATUS WINAPI harddisk_ioctl( DEVICE_OBJECT *device, IRP *irp )
{
1823
    IO_STACK_LOCATION *irpsp = IoGetCurrentIrpStackLocation( irp );
1824
    struct disk_device *dev = device->DeviceExtension;
1825 1826 1827 1828 1829 1830

    TRACE( "ioctl %x insize %u outsize %u\n",
           irpsp->Parameters.DeviceIoControl.IoControlCode,
           irpsp->Parameters.DeviceIoControl.InputBufferLength,
           irpsp->Parameters.DeviceIoControl.OutputBufferLength );

1831 1832
    EnterCriticalSection( &device_section );

1833 1834 1835 1836 1837 1838 1839 1840
    switch(irpsp->Parameters.DeviceIoControl.IoControlCode)
    {
    case IOCTL_DISK_GET_DRIVE_GEOMETRY:
    {
        DISK_GEOMETRY info;
        DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );

        info.Cylinders.QuadPart = 10000;
1841
        info.MediaType = (dev->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
1842 1843 1844
        info.TracksPerCylinder = 255;
        info.SectorsPerTrack = 63;
        info.BytesPerSector = 512;
1845
        memcpy( irp->AssociatedIrp.SystemBuffer, &info, len );
1846 1847 1848 1849
        irp->IoStatus.Information = len;
        irp->IoStatus.u.Status = STATUS_SUCCESS;
        break;
    }
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
    case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX:
    {
        DISK_GEOMETRY_EX info;
        DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );

        FIXME("The DISK_PARTITION_INFO and DISK_DETECTION_INFO structures will not be filled\n");

        info.Geometry.Cylinders.QuadPart = 10000;
        info.Geometry.MediaType = (dev->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
        info.Geometry.TracksPerCylinder = 255;
        info.Geometry.SectorsPerTrack = 63;
        info.Geometry.BytesPerSector = 512;
        info.DiskSize.QuadPart = info.Geometry.Cylinders.QuadPart * info.Geometry.TracksPerCylinder *
                                 info.Geometry.SectorsPerTrack * info.Geometry.BytesPerSector;
        info.Data[0]  = 0;
1865
        memcpy( irp->AssociatedIrp.SystemBuffer, &info, len );
1866 1867 1868 1869
        irp->IoStatus.Information = len;
        irp->IoStatus.u.Status = STATUS_SUCCESS;
        break;
    }
1870 1871
    case IOCTL_STORAGE_GET_DEVICE_NUMBER:
    {
1872
        DWORD len = min( sizeof(dev->devnum), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
1873

1874
        memcpy( irp->AssociatedIrp.SystemBuffer, &dev->devnum, len );
1875 1876 1877 1878 1879 1880 1881
        irp->IoStatus.Information = len;
        irp->IoStatus.u.Status = STATUS_SUCCESS;
        break;
    }
    case IOCTL_CDROM_READ_TOC:
        irp->IoStatus.u.Status = STATUS_INVALID_DEVICE_REQUEST;
        break;
1882
    case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS:
1883 1884 1885
    {
        DWORD len = min( 32, irpsp->Parameters.DeviceIoControl.OutputBufferLength );

1886
        FIXME( "returning zero-filled buffer for IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS\n" );
1887
        memset( irp->AssociatedIrp.SystemBuffer, 0, len );
1888 1889 1890 1891
        irp->IoStatus.Information = len;
        irp->IoStatus.u.Status = STATUS_SUCCESS;
        break;
    }
1892
    case IOCTL_STORAGE_QUERY_PROPERTY:
1893
        query_property( dev, irp );
1894
        break;
1895
    default:
1896 1897 1898 1899
    {
        ULONG code = irpsp->Parameters.DeviceIoControl.IoControlCode;
        FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
              code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1900 1901 1902
        irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
        break;
    }
1903
    }
1904 1905

    LeaveCriticalSection( &device_section );
1906
    IoCompleteRequest( irp, IO_NO_INCREMENT );
1907
    return STATUS_SUCCESS;
1908 1909 1910 1911 1912
}

/* driver entry point for the harddisk driver */
NTSTATUS WINAPI harddisk_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *path )
{
1913
    struct disk_device *device;
1914

1915
    harddisk_driver = driver;
1916 1917
    driver->MajorFunction[IRP_MJ_DEVICE_CONTROL] = harddisk_ioctl;

1918
    /* create a harddisk0 device that isn't assigned to any drive */
1919
    create_disk_device( DEVICE_HARDDISK, &device );
1920 1921

    create_drive_devices();
1922

1923
    return STATUS_SUCCESS;
1924
}
1925 1926 1927


/* create a serial or parallel port */
1928 1929
static BOOL create_port_device( DRIVER_OBJECT *driver, int n, const char *unix_path,
                                const char *dosdevices_path, HKEY windows_ports_key )
1930 1931
{
    static const WCHAR comW[] = {'C','O','M','%','u',0};
1932
    static const WCHAR lptW[] = {'L','P','T','%','u',0};
1933
    static const WCHAR device_serialW[] = {'\\','D','e','v','i','c','e','\\','S','e','r','i','a','l','%','u',0};
1934
    static const WCHAR device_parallelW[] = {'\\','D','e','v','i','c','e','\\','P','a','r','a','l','l','e','l','%','u',0};
1935
    static const WCHAR dosdevices_comW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','C','O','M','%','u',0};
1936
    static const WCHAR dosdevices_auxW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','A','U','X',0};
1937
    static const WCHAR dosdevices_lptW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','L','P','T','%','u',0};
1938
    static const WCHAR dosdevices_prnW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','P','R','N',0};
1939 1940 1941
    const WCHAR *dos_name_format, *nt_name_format, *reg_value_format, *symlink_format, *default_device;
    WCHAR dos_name[7], reg_value[256], nt_buffer[32], symlink_buffer[32];
    UNICODE_STRING nt_name, symlink_name, default_name;
1942 1943 1944
    DEVICE_OBJECT *dev_obj;
    NTSTATUS status;

1945 1946 1947 1948 1949
    if (driver == serial_driver)
    {
        dos_name_format = comW;
        nt_name_format = device_serialW;
        reg_value_format = comW;
1950
        symlink_format = dosdevices_comW;
1951
        default_device = dosdevices_auxW;
1952 1953 1954 1955 1956 1957
    }
    else
    {
        dos_name_format = lptW;
        nt_name_format = device_parallelW;
        reg_value_format = dosdevices_lptW;
1958
        symlink_format = dosdevices_lptW;
1959
        default_device = dosdevices_prnW;
1960
    }
1961 1962 1963 1964

    sprintfW( dos_name, dos_name_format, n );

    /* create DOS device */
1965
    unlink( dosdevices_path );
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    if (symlink( unix_path, dosdevices_path ) != 0)
        return FALSE;

    /* create NT device */
    sprintfW( nt_buffer, nt_name_format, n - 1 );
    RtlInitUnicodeString( &nt_name, nt_buffer );
    status = IoCreateDevice( driver, 0, &nt_name, 0, 0, FALSE, &dev_obj );
    if (status != STATUS_SUCCESS)
    {
        FIXME( "IoCreateDevice %s got %x\n", debugstr_w(nt_name.Buffer), status );
        return FALSE;
    }
1978 1979 1980 1981 1982 1983 1984 1985 1986
    sprintfW( symlink_buffer, symlink_format, n );
    RtlInitUnicodeString( &symlink_name, symlink_buffer );
    IoCreateSymbolicLink( &symlink_name, &nt_name );
    if (n == 1)
    {
        RtlInitUnicodeString( &default_name, default_device );
        IoCreateSymbolicLink( &default_name, &symlink_name );
    }

1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
    /* TODO: store information about the Unix device in the NT device */

    /* create registry entry */
    sprintfW( reg_value, reg_value_format, n );
    RegSetValueExW( windows_ports_key, nt_name.Buffer, 0, REG_SZ,
                    (BYTE *)reg_value, (strlenW( reg_value ) + 1) * sizeof(WCHAR) );

    return TRUE;
}

/* find and create serial or parallel ports */
static void create_port_devices( DRIVER_OBJECT *driver )
{
    static const char *serial_search_paths[] = {
#ifdef linux
        "/dev/ttyS%u",
        "/dev/ttyUSB%u",
2004
        "/dev/ttyACM%u",
2005 2006 2007 2008
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
        "/dev/cuau%u",
#elif defined(__DragonFly__)
        "/dev/cuaa%u",
2009
#endif
2010
        NULL
2011 2012 2013 2014
    };
    static const char *parallel_search_paths[] = {
#ifdef linux
        "/dev/lp%u",
2015
#endif
2016
        NULL
2017 2018 2019 2020
    };
    static const WCHAR serialcomm_keyW[] = {'H','A','R','D','W','A','R','E','\\',
                                            'D','E','V','I','C','E','M','A','P','\\',
                                            'S','E','R','I','A','L','C','O','M','M',0};
2021 2022 2023
    static const WCHAR parallel_ports_keyW[] = {'H','A','R','D','W','A','R','E','\\',
                                                'D','E','V','I','C','E','M','A','P','\\',
                                                'P','A','R','A','L','L','E','L',' ','P','O','R','T','S',0};
2024 2025
    static const WCHAR comW[] = {'C','O','M'};
    static const WCHAR lptW[] = {'L','P','T'};
2026 2027 2028 2029 2030
    const char **search_paths;
    const WCHAR *windows_ports_key_name;
    char *dosdevices_path, *p;
    HKEY wine_ports_key = NULL, windows_ports_key = NULL;
    char unix_path[256];
2031 2032 2033 2034 2035
    const WCHAR *port_prefix;
    WCHAR reg_value[256];
    BOOL used[MAX_PORTS];
    WCHAR port[7];
    DWORD port_len, type, size;
2036
    int i, j, n;
2037 2038 2039 2040

    if (!(dosdevices_path = get_dosdevices_path( &p )))
        return;

2041 2042 2043 2044 2045 2046 2047
    if (driver == serial_driver)
    {
        p[0] = 'c';
        p[1] = 'o';
        p[2] = 'm';
        search_paths = serial_search_paths;
        windows_ports_key_name = serialcomm_keyW;
2048
        port_prefix = comW;
2049 2050 2051 2052 2053 2054 2055 2056
    }
    else
    {
        p[0] = 'l';
        p[1] = 'p';
        p[2] = 't';
        search_paths = parallel_search_paths;
        windows_ports_key_name = parallel_ports_keyW;
2057
        port_prefix = lptW;
2058
    }
2059 2060
    p += 3;

2061 2062
    RegCreateKeyExW( HKEY_LOCAL_MACHINE, ports_keyW, 0, NULL, 0,
                     KEY_QUERY_VALUE, NULL, &wine_ports_key, NULL );
2063 2064
    RegCreateKeyExW( HKEY_LOCAL_MACHINE, windows_ports_key_name, 0, NULL, REG_OPTION_VOLATILE,
                     KEY_ALL_ACCESS, NULL, &windows_ports_key, NULL );
2065

2066 2067 2068
    /* add user-defined serial ports */
    memset(used, 0, sizeof(used));
    for (i = 0; ; i++)
2069
    {
2070 2071 2072 2073
        port_len = ARRAY_SIZE(port);
        size = sizeof(reg_value);
        if (RegEnumValueW( wine_ports_key, i, port, &port_len, NULL,
                    &type, (BYTE*)reg_value, &size ) != ERROR_SUCCESS)
2074
            break;
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
        if (type != REG_SZ || strncmpiW( port, port_prefix, 3 ))
            continue;

        n = atolW( port  + 3 );
        if (n < 1 || n >= MAX_PORTS)
            continue;

        if (!WideCharToMultiByte( CP_UNIXCP, WC_ERR_INVALID_CHARS, reg_value, size/sizeof(WCHAR),
                    unix_path, sizeof(unix_path), NULL, NULL))
            continue;

        used[n - 1] = TRUE;
        sprintf( p, "%u", n );
        create_port_device( driver, n, unix_path, dosdevices_path, windows_ports_key );
2089 2090 2091 2092
    }

    /* look for ports in the usual places */
    n = 1;
2093
    while (n <= MAX_PORTS && used[n - 1]) n++;
2094
    for (i = 0; search_paths[i]; i++)
2095 2096 2097 2098 2099 2100 2101
    {
        for (j = 0; n <= MAX_PORTS; j++)
        {
            sprintf( unix_path, search_paths[i], j );
            if (access( unix_path, F_OK ) != 0)
                break;

2102 2103
            sprintf( p, "%u", n );
            create_port_device( driver, n, unix_path, dosdevices_path, windows_ports_key );
2104
            n++;
2105
            while (n <= MAX_PORTS && used[n - 1]) n++;
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
        }
    }

    RegCloseKey( wine_ports_key );
    RegCloseKey( windows_ports_key );
    HeapFree( GetProcessHeap(), 0, dosdevices_path );
}

/* driver entry point for the serial port driver */
NTSTATUS WINAPI serial_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *path )
{
    serial_driver = driver;
    /* TODO: fill in driver->MajorFunction */

    create_port_devices( driver );

    return STATUS_SUCCESS;
}
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134

/* driver entry point for the parallel port driver */
NTSTATUS WINAPI parallel_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *path )
{
    parallel_driver = driver;
    /* TODO: fill in driver->MajorFunction */

    create_port_devices( driver );

    return STATUS_SUCCESS;
}