dmusic: Set instrument stream position where the instrument begins, not at the beginn...
[wine] / dlls / mountmgr.sys / device.c
1 /*
2  * Dynamic devices support
3  *
4  * Copyright 2006 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <sys/time.h>
29
30 #include "mountmgr.h"
31 #include "winreg.h"
32 #include "winuser.h"
33 #include "dbt.h"
34
35 #include "wine/library.h"
36 #include "wine/list.h"
37 #include "wine/unicode.h"
38 #include "wine/debug.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(mountmgr);
41
42 #define MAX_DOS_DRIVES 26
43
44 static const WCHAR drive_types[][8] =
45 {
46     { 0 },                           /* DEVICE_UNKNOWN */
47     { 0 },                           /* DEVICE_HARDDISK */
48     {'h','d',0},                     /* DEVICE_HARDDISK_VOL */
49     {'f','l','o','p','p','y',0},     /* DEVICE_FLOPPY */
50     {'c','d','r','o','m',0},         /* DEVICE_CDROM */
51     {'n','e','t','w','o','r','k',0}, /* DEVICE_NETWORK */
52     {'r','a','m','d','i','s','k',0}  /* DEVICE_RAMDISK */
53 };
54
55 static const WCHAR drives_keyW[] = {'S','o','f','t','w','a','r','e','\\',
56                                     'W','i','n','e','\\','D','r','i','v','e','s',0};
57
58 struct disk_device
59 {
60     enum device_type      type;        /* drive type */
61     DEVICE_OBJECT        *dev_obj;     /* disk device allocated for this volume */
62     UNICODE_STRING        name;        /* device name */
63     UNICODE_STRING        symlink;     /* device symlink if any */
64     STORAGE_DEVICE_NUMBER devnum;      /* device number info */
65     char                 *unix_device; /* unix device path */
66     char                 *unix_mount;  /* unix mount point path */
67 };
68
69 struct volume
70 {
71     struct list           entry;       /* entry in volumes list */
72     struct disk_device   *device;      /* disk device */
73     char                 *udi;         /* unique identifier for dynamic volumes */
74     unsigned int          ref;         /* ref count */
75     GUID                  guid;        /* volume uuid */
76     struct mount_point   *mount;       /* Volume{xxx} mount point */
77 };
78
79 struct dos_drive
80 {
81     struct list           entry;       /* entry in drives list */
82     struct volume        *volume;      /* volume for this drive */
83     int                   drive;       /* drive letter (0 = A: etc.) */
84     struct mount_point   *mount;       /* DosDevices mount point */
85 };
86
87 static struct list drives_list = LIST_INIT(drives_list);
88 static struct list volumes_list = LIST_INIT(volumes_list);
89
90 static DRIVER_OBJECT *harddisk_driver;
91
92 static CRITICAL_SECTION device_section;
93 static CRITICAL_SECTION_DEBUG critsect_debug =
94 {
95     0, 0, &device_section,
96     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
97       0, 0, { (DWORD_PTR)(__FILE__ ": device_section") }
98 };
99 static CRITICAL_SECTION device_section = { &critsect_debug, -1, 0, 0, 0, 0 };
100
101 static char *get_dosdevices_path( char **drive )
102 {
103     const char *config_dir = wine_get_config_dir();
104     size_t len = strlen(config_dir) + sizeof("/dosdevices/a::");
105     char *path = HeapAlloc( GetProcessHeap(), 0, len );
106     if (path)
107     {
108         strcpy( path, config_dir );
109         strcat( path, "/dosdevices/a::" );
110         *drive = path + len - 4;
111     }
112     return path;
113 }
114
115 static char *strdupA( const char *str )
116 {
117     char *ret;
118
119     if (!str) return NULL;
120     if ((ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
121     return ret;
122 }
123
124 static const GUID *get_default_uuid( int letter )
125 {
126     static GUID guid;
127
128     guid.Data4[7] = 'A' + letter;
129     return &guid;
130 }
131
132 /* read a Unix symlink; returned buffer must be freed by caller */
133 static char *read_symlink( const char *path )
134 {
135     char *buffer;
136     int ret, size = 128;
137
138     for (;;)
139     {
140         if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size )))
141         {
142             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
143             return 0;
144         }
145         ret = readlink( path, buffer, size );
146         if (ret == -1)
147         {
148             RtlFreeHeap( GetProcessHeap(), 0, buffer );
149             return 0;
150         }
151         if (ret != size)
152         {
153             buffer[ret] = 0;
154             return buffer;
155         }
156         RtlFreeHeap( GetProcessHeap(), 0, buffer );
157         size *= 2;
158     }
159 }
160
161 /* update a symlink if it changed; return TRUE if updated */
162 static void update_symlink( const char *path, const char *dest, const char *orig_dest )
163 {
164     if (dest && dest[0])
165     {
166         if (!orig_dest || strcmp( orig_dest, dest ))
167         {
168             unlink( path );
169             symlink( dest, path );
170         }
171     }
172     else unlink( path );
173 }
174
175 /* send notification about a change to a given drive */
176 static void send_notify( int drive, int code )
177 {
178     DEV_BROADCAST_VOLUME info;
179
180     info.dbcv_size       = sizeof(info);
181     info.dbcv_devicetype = DBT_DEVTYP_VOLUME;
182     info.dbcv_reserved   = 0;
183     info.dbcv_unitmask   = 1 << drive;
184     info.dbcv_flags      = DBTF_MEDIA;
185     BroadcastSystemMessageW( BSF_FORCEIFHUNG|BSF_QUERY, NULL,
186                              WM_DEVICECHANGE, code, (LPARAM)&info );
187 }
188
189 /* create the disk device for a given volume */
190 static NTSTATUS create_disk_device( enum device_type type, struct disk_device **device_ret )
191 {
192     static const WCHAR harddiskvolW[] = {'\\','D','e','v','i','c','e',
193                                          '\\','H','a','r','d','d','i','s','k','V','o','l','u','m','e','%','u',0};
194     static const WCHAR harddiskW[] = {'\\','D','e','v','i','c','e','\\','H','a','r','d','d','i','s','k','%','u',0};
195     static const WCHAR cdromW[] = {'\\','D','e','v','i','c','e','\\','C','d','R','o','m','%','u',0};
196     static const WCHAR floppyW[] = {'\\','D','e','v','i','c','e','\\','F','l','o','p','p','y','%','u',0};
197     static const WCHAR ramdiskW[] = {'\\','D','e','v','i','c','e','\\','R','a','m','d','i','s','k','%','u',0};
198     static const WCHAR cdromlinkW[] = {'\\','?','?','\\','C','d','R','o','m','%','u',0};
199     static const WCHAR physdriveW[] = {'\\','?','?','\\','P','h','y','s','i','c','a','l','D','r','i','v','e','%','u',0};
200
201     UINT i, first = 0;
202     NTSTATUS status = 0;
203     const WCHAR *format = NULL;
204     const WCHAR *link_format = NULL;
205     UNICODE_STRING name;
206     DEVICE_OBJECT *dev_obj;
207     struct disk_device *device;
208
209     switch(type)
210     {
211     case DEVICE_UNKNOWN:
212     case DEVICE_HARDDISK:
213     case DEVICE_NETWORK:  /* FIXME */
214         format = harddiskW;
215         link_format = physdriveW;
216         break;
217     case DEVICE_HARDDISK_VOL:
218         format = harddiskvolW;
219         first = 1;  /* harddisk volumes start counting from 1 */
220         break;
221     case DEVICE_FLOPPY:
222         format = floppyW;
223         break;
224     case DEVICE_CDROM:
225     case DEVICE_DVD:
226         format = cdromW;
227         link_format = cdromlinkW;
228         break;
229     case DEVICE_RAMDISK:
230         format = ramdiskW;
231         break;
232     }
233
234     name.MaximumLength = (strlenW(format) + 10) * sizeof(WCHAR);
235     name.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, name.MaximumLength );
236     for (i = first; i < 32; i++)
237     {
238         sprintfW( name.Buffer, format, i );
239         name.Length = strlenW(name.Buffer) * sizeof(WCHAR);
240         status = IoCreateDevice( harddisk_driver, sizeof(*device), &name, 0, 0, FALSE, &dev_obj );
241         if (status != STATUS_OBJECT_NAME_COLLISION) break;
242     }
243     if (!status)
244     {
245         device = dev_obj->DeviceExtension;
246         device->dev_obj        = dev_obj;
247         device->name           = name;
248         device->type           = type;
249         device->unix_device    = NULL;
250         device->unix_mount     = NULL;
251         device->symlink.Buffer = NULL;
252
253         if (link_format)
254         {
255             UNICODE_STRING symlink;
256
257             symlink.MaximumLength = (strlenW(link_format) + 10) * sizeof(WCHAR);
258             if ((symlink.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, symlink.MaximumLength)))
259             {
260                 sprintfW( symlink.Buffer, link_format, i );
261                 symlink.Length = strlenW(symlink.Buffer) * sizeof(WCHAR);
262                 if (!IoCreateSymbolicLink( &symlink, &name )) device->symlink = symlink;
263             }
264         }
265
266         switch (type)
267         {
268         case DEVICE_FLOPPY:
269         case DEVICE_RAMDISK:
270             device->devnum.DeviceType = FILE_DEVICE_DISK;
271             device->devnum.DeviceNumber = i;
272             device->devnum.PartitionNumber = ~0u;
273             break;
274         case DEVICE_CDROM:
275             device->devnum.DeviceType = FILE_DEVICE_CD_ROM;
276             device->devnum.DeviceNumber = i;
277             device->devnum.PartitionNumber = ~0u;
278             break;
279         case DEVICE_DVD:
280             device->devnum.DeviceType = FILE_DEVICE_DVD;
281             device->devnum.DeviceNumber = i;
282             device->devnum.PartitionNumber = ~0u;
283             break;
284         case DEVICE_UNKNOWN:
285         case DEVICE_HARDDISK:
286         case DEVICE_NETWORK:  /* FIXME */
287             device->devnum.DeviceType = FILE_DEVICE_DISK;
288             device->devnum.DeviceNumber = i;
289             device->devnum.PartitionNumber = 0;
290             break;
291         case DEVICE_HARDDISK_VOL:
292             device->devnum.DeviceType = FILE_DEVICE_DISK;
293             device->devnum.DeviceNumber = 0;
294             device->devnum.PartitionNumber = i;
295             break;
296         }
297         *device_ret = device;
298         TRACE( "created device %s\n", debugstr_w(name.Buffer) );
299     }
300     else
301     {
302         FIXME( "IoCreateDevice %s got %x\n", debugstr_w(name.Buffer), status );
303         RtlFreeUnicodeString( &name );
304     }
305     return status;
306 }
307
308 /* delete the disk device for a given drive */
309 static void delete_disk_device( struct disk_device *device )
310 {
311     TRACE( "deleting device %s\n", debugstr_w(device->name.Buffer) );
312     if (device->symlink.Buffer)
313     {
314         IoDeleteSymbolicLink( &device->symlink );
315         RtlFreeUnicodeString( &device->symlink );
316     }
317     RtlFreeHeap( GetProcessHeap(), 0, device->unix_device );
318     RtlFreeHeap( GetProcessHeap(), 0, device->unix_mount );
319     RtlFreeUnicodeString( &device->name );
320     IoDeleteDevice( device->dev_obj );
321 }
322
323 /* grab another reference to a volume */
324 static struct volume *grab_volume( struct volume *volume )
325 {
326     volume->ref++;
327     return volume;
328 }
329
330 /* release a volume and delete the corresponding disk device when refcount is 0 */
331 static unsigned int release_volume( struct volume *volume )
332 {
333     unsigned int ret = --volume->ref;
334
335     if (!ret)
336     {
337         TRACE( "%s udi %s\n", debugstr_guid(&volume->guid), debugstr_a(volume->udi) );
338         assert( !volume->udi );
339         list_remove( &volume->entry );
340         if (volume->mount) delete_mount_point( volume->mount );
341         delete_disk_device( volume->device );
342         RtlFreeHeap( GetProcessHeap(), 0, volume );
343     }
344     return ret;
345 }
346
347 /* set the volume udi */
348 static void set_volume_udi( struct volume *volume, const char *udi )
349 {
350     if (udi)
351     {
352         assert( !volume->udi );
353         /* having a udi means the HAL side holds an extra reference */
354         if ((volume->udi = strdupA( udi ))) grab_volume( volume );
355     }
356     else if (volume->udi)
357     {
358         RtlFreeHeap( GetProcessHeap(), 0, volume->udi );
359         volume->udi = NULL;
360         release_volume( volume );
361     }
362 }
363
364 /* create a disk volume */
365 static NTSTATUS create_volume( const char *udi, enum device_type type, struct volume **volume_ret )
366 {
367     struct volume *volume;
368     NTSTATUS status;
369
370     if (!(volume = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*volume) )))
371         return STATUS_NO_MEMORY;
372
373     if (!(status = create_disk_device( type, &volume->device )))
374     {
375         if (udi) set_volume_udi( volume, udi );
376         list_add_tail( &volumes_list, &volume->entry );
377         *volume_ret = grab_volume( volume );
378     }
379     else RtlFreeHeap( GetProcessHeap(), 0, volume );
380
381     return status;
382 }
383
384 /* create the disk device for a given volume */
385 static NTSTATUS create_dos_device( struct volume *volume, const char *udi, int letter,
386                                    enum device_type type, struct dos_drive **drive_ret )
387 {
388     struct dos_drive *drive;
389     NTSTATUS status;
390
391     if (!(drive = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*drive) ))) return STATUS_NO_MEMORY;
392     drive->drive = letter;
393     drive->mount = NULL;
394
395     if (volume)
396     {
397         if (udi) set_volume_udi( volume, udi );
398         drive->volume = grab_volume( volume );
399         status = STATUS_SUCCESS;
400     }
401     else status = create_volume( udi, type, &drive->volume );
402
403     if (status == STATUS_SUCCESS)
404     {
405         list_add_tail( &drives_list, &drive->entry );
406         *drive_ret = drive;
407     }
408     else RtlFreeHeap( GetProcessHeap(), 0, drive );
409
410     return status;
411 }
412
413 /* delete the disk device for a given drive */
414 static void delete_dos_device( struct dos_drive *drive )
415 {
416     list_remove( &drive->entry );
417     if (drive->mount) delete_mount_point( drive->mount );
418     release_volume( drive->volume );
419     RtlFreeHeap( GetProcessHeap(), 0, drive );
420 }
421
422 /* find a volume that matches the parameters */
423 static struct volume *find_matching_volume( const char *udi, const char *device,
424                                             const char *mount_point, enum device_type type )
425 {
426     struct volume *volume;
427     struct disk_device *disk_device;
428
429     LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
430     {
431         int match = 0;
432
433         /* when we have a udi we only match drives added manually */
434         if (udi && volume->udi) continue;
435         /* and when we don't have a udi we only match dynamic drives */
436         if (!udi && !volume->udi) continue;
437
438         disk_device = volume->device;
439         if (disk_device->type != type) continue;
440         if (device && disk_device->unix_device)
441         {
442             if (strcmp( device, disk_device->unix_device )) continue;
443             match++;
444         }
445         if (mount_point && disk_device->unix_mount)
446         {
447             if (strcmp( mount_point, disk_device->unix_mount )) continue;
448             match++;
449         }
450         if (!match) continue;
451         TRACE( "found matching volume %s for device %s mount %s type %u\n",
452                debugstr_guid(&volume->guid), debugstr_a(device), debugstr_a(mount_point), type );
453         return grab_volume( volume );
454     }
455     return NULL;
456 }
457
458 /* change the information for an existing volume */
459 static NTSTATUS set_volume_info( struct volume *volume, struct dos_drive *drive, const char *device,
460                                  const char *mount_point, enum device_type type, const GUID *guid )
461 {
462     void *id = NULL;
463     unsigned int id_len = 0;
464     struct disk_device *disk_device = volume->device;
465     NTSTATUS status;
466
467     if (type != disk_device->type)
468     {
469         if ((status = create_disk_device( type, &disk_device ))) return status;
470         if (volume->mount)
471         {
472             delete_mount_point( volume->mount );
473             volume->mount = NULL;
474         }
475         if (drive && drive->mount)
476         {
477             delete_mount_point( drive->mount );
478             drive->mount = NULL;
479         }
480         delete_disk_device( volume->device );
481         volume->device = disk_device;
482     }
483     else
484     {
485         RtlFreeHeap( GetProcessHeap(), 0, disk_device->unix_device );
486         RtlFreeHeap( GetProcessHeap(), 0, disk_device->unix_mount );
487     }
488     disk_device->unix_device = strdupA( device );
489     disk_device->unix_mount = strdupA( mount_point );
490
491     if (guid && memcmp( &volume->guid, guid, sizeof(volume->guid) ))
492     {
493         volume->guid = *guid;
494         if (volume->mount)
495         {
496             delete_mount_point( volume->mount );
497             volume->mount = NULL;
498         }
499     }
500
501     if (!volume->mount)
502         volume->mount = add_volume_mount_point( disk_device->dev_obj, &disk_device->name, &volume->guid );
503     if (drive && !drive->mount)
504         drive->mount = add_dosdev_mount_point( disk_device->dev_obj, &disk_device->name, drive->drive );
505
506     if (disk_device->unix_mount)
507     {
508         id = disk_device->unix_mount;
509         id_len = strlen( disk_device->unix_mount ) + 1;
510     }
511     if (volume->mount) set_mount_point_id( volume->mount, id, id_len );
512     if (drive && drive->mount) set_mount_point_id( drive->mount, id, id_len );
513
514     return STATUS_SUCCESS;
515 }
516
517 /* change the drive letter or volume for an existing drive */
518 static void set_drive_info( struct dos_drive *drive, int letter, struct volume *volume )
519 {
520     if (drive->drive != letter)
521     {
522         if (drive->mount) delete_mount_point( drive->mount );
523         drive->mount = NULL;
524         drive->drive = letter;
525     }
526     if (drive->volume != volume)
527     {
528         if (drive->mount) delete_mount_point( drive->mount );
529         drive->mount = NULL;
530         grab_volume( volume );
531         release_volume( drive->volume );
532         drive->volume = volume;
533     }
534 }
535
536 static inline int is_valid_device( struct stat *st )
537 {
538 #if defined(linux) || defined(__sun__)
539     return S_ISBLK( st->st_mode );
540 #else
541     /* disks are char devices on *BSD */
542     return S_ISCHR( st->st_mode );
543 #endif
544 }
545
546 /* find or create a DOS drive for the corresponding device */
547 static int add_drive( const char *device, enum device_type type )
548 {
549     char *path, *p;
550     char in_use[26];
551     struct stat dev_st, drive_st;
552     int drive, first, last, avail = 0;
553
554     if (stat( device, &dev_st ) == -1 || !is_valid_device( &dev_st )) return -1;
555
556     if (!(path = get_dosdevices_path( &p ))) return -1;
557
558     memset( in_use, 0, sizeof(in_use) );
559
560     switch (type)
561     {
562     case DEVICE_FLOPPY:
563         first = 0;
564         last = 2;
565         break;
566     case DEVICE_CDROM:
567     case DEVICE_DVD:
568         first = 3;
569         last = 26;
570         break;
571     default:
572         first = 2;
573         last = 26;
574         break;
575     }
576
577     while (avail != -1)
578     {
579         avail = -1;
580         for (drive = first; drive < last; drive++)
581         {
582             if (in_use[drive]) continue;  /* already checked */
583             *p = 'a' + drive;
584             if (stat( path, &drive_st ) == -1)
585             {
586                 if (lstat( path, &drive_st ) == -1 && errno == ENOENT)  /* this is a candidate */
587                 {
588                     if (avail == -1)
589                     {
590                         p[2] = 0;
591                         /* if mount point symlink doesn't exist either, it's available */
592                         if (lstat( path, &drive_st ) == -1 && errno == ENOENT) avail = drive;
593                         p[2] = ':';
594                     }
595                 }
596                 else in_use[drive] = 1;
597             }
598             else
599             {
600                 in_use[drive] = 1;
601                 if (!is_valid_device( &drive_st )) continue;
602                 if (dev_st.st_rdev == drive_st.st_rdev) goto done;
603             }
604         }
605         if (avail != -1)
606         {
607             /* try to use the one we found */
608             drive = avail;
609             *p = 'a' + drive;
610             if (symlink( device, path ) != -1) goto done;
611             /* failed, retry the search */
612         }
613     }
614     drive = -1;
615
616 done:
617     HeapFree( GetProcessHeap(), 0, path );
618     return drive;
619 }
620
621 /* create devices for mapped drives */
622 static void create_drive_devices(void)
623 {
624     char *path, *p, *link, *device;
625     struct dos_drive *drive;
626     struct volume *volume;
627     unsigned int i;
628     HKEY drives_key;
629     enum device_type drive_type;
630     WCHAR driveW[] = {'a',':',0};
631
632     if (!(path = get_dosdevices_path( &p ))) return;
633     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &drives_key )) drives_key = 0;
634
635     for (i = 0; i < MAX_DOS_DRIVES; i++)
636     {
637         p[0] = 'a' + i;
638         p[2] = 0;
639         if (!(link = read_symlink( path ))) continue;
640         p[2] = ':';
641         device = read_symlink( path );
642
643         drive_type = i < 2 ? DEVICE_FLOPPY : DEVICE_HARDDISK_VOL;
644         if (drives_key)
645         {
646             WCHAR buffer[32];
647             DWORD j, type, size = sizeof(buffer);
648
649             driveW[0] = 'a' + i;
650             if (!RegQueryValueExW( drives_key, driveW, NULL, &type, (BYTE *)buffer, &size ) &&
651                 type == REG_SZ)
652             {
653                 for (j = 0; j < sizeof(drive_types)/sizeof(drive_types[0]); j++)
654                     if (drive_types[j][0] && !strcmpiW( buffer, drive_types[j] ))
655                     {
656                         drive_type = j;
657                         break;
658                     }
659                 if (drive_type == DEVICE_FLOPPY && i >= 2) drive_type = DEVICE_HARDDISK;
660             }
661         }
662
663         volume = find_matching_volume( NULL, device, link, drive_type );
664         if (!create_dos_device( volume, NULL, i, drive_type, &drive ))
665         {
666             /* don't reset uuid if we used an existing volume */
667             const GUID *guid = volume ? NULL : get_default_uuid(i);
668             set_volume_info( drive->volume, drive, device, link, drive_type, guid );
669         }
670         else
671         {
672             RtlFreeHeap( GetProcessHeap(), 0, link );
673             RtlFreeHeap( GetProcessHeap(), 0, device );
674         }
675         if (volume) release_volume( volume );
676     }
677     RegCloseKey( drives_key );
678     RtlFreeHeap( GetProcessHeap(), 0, path );
679 }
680
681 /* create a new disk volume */
682 NTSTATUS add_volume( const char *udi, const char *device, const char *mount_point,
683                      enum device_type type, const GUID *guid )
684 {
685     struct volume *volume;
686     NTSTATUS status = STATUS_SUCCESS;
687
688     TRACE( "adding %s device %s mount %s type %u uuid %s\n", debugstr_a(udi),
689            debugstr_a(device), debugstr_a(mount_point), type, debugstr_guid(guid) );
690
691     EnterCriticalSection( &device_section );
692     LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
693         if (volume->udi && !strcmp( udi, volume->udi ))
694         {
695             grab_volume( volume );
696             goto found;
697         }
698
699     /* udi not found, search for a non-dynamic volume */
700     if ((volume = find_matching_volume( udi, device, mount_point, type ))) set_volume_udi( volume, udi );
701     else status = create_volume( udi, type, &volume );
702
703 found:
704     if (!status) status = set_volume_info( volume, NULL, device, mount_point, type, guid );
705     if (volume) release_volume( volume );
706     LeaveCriticalSection( &device_section );
707     return status;
708 }
709
710 /* create a new disk volume */
711 NTSTATUS remove_volume( const char *udi )
712 {
713     NTSTATUS status = STATUS_NO_SUCH_DEVICE;
714     struct volume *volume;
715
716     EnterCriticalSection( &device_section );
717     LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
718     {
719         if (!volume->udi || strcmp( udi, volume->udi )) continue;
720         set_volume_udi( volume, NULL );
721         status = STATUS_SUCCESS;
722         break;
723     }
724     LeaveCriticalSection( &device_section );
725     return status;
726 }
727
728
729 /* create a new dos drive */
730 NTSTATUS add_dos_device( int letter, const char *udi, const char *device,
731                          const char *mount_point, enum device_type type, const GUID *guid )
732 {
733     char *path, *p;
734     HKEY hkey;
735     NTSTATUS status = STATUS_SUCCESS;
736     struct dos_drive *drive, *next;
737     struct volume *volume;
738     int notify = -1;
739
740     if (!(path = get_dosdevices_path( &p ))) return STATUS_NO_MEMORY;
741
742     EnterCriticalSection( &device_section );
743     volume = find_matching_volume( udi, device, mount_point, type );
744
745     if (letter == -1)  /* auto-assign a letter */
746     {
747         letter = add_drive( device, type );
748         if (letter == -1)
749         {
750             status = STATUS_OBJECT_NAME_COLLISION;
751             goto done;
752         }
753
754         LIST_FOR_EACH_ENTRY_SAFE( drive, next, &drives_list, struct dos_drive, entry )
755         {
756             if (drive->volume->udi && !strcmp( udi, drive->volume->udi )) goto found;
757             if (drive->drive == letter) delete_dos_device( drive );
758         }
759     }
760     else  /* simply reset the device symlink */
761     {
762         LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
763             if (drive->drive == letter) break;
764
765         *p = 'a' + letter;
766         if (&drive->entry == &drives_list) update_symlink( path, device, NULL );
767         else
768         {
769             update_symlink( path, device, drive->volume->device->unix_device );
770             delete_dos_device( drive );
771         }
772     }
773
774     if ((status = create_dos_device( volume, udi, letter, type, &drive ))) goto done;
775
776 found:
777     if (!guid && !volume) guid = get_default_uuid( letter );
778     if (!volume) volume = grab_volume( drive->volume );
779     set_drive_info( drive, letter, volume );
780     p[0] = 'a' + drive->drive;
781     p[2] = 0;
782     update_symlink( path, mount_point, volume->device->unix_mount );
783     set_volume_info( volume, drive, device, mount_point, type, guid );
784
785     TRACE( "added device %c: udi %s for %s on %s type %u\n",
786            'a' + drive->drive, wine_dbgstr_a(udi), wine_dbgstr_a(device),
787            wine_dbgstr_a(mount_point), type );
788
789     /* hack: force the drive type in the registry */
790     if (!RegCreateKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
791     {
792         const WCHAR *type_name = drive_types[type];
793         WCHAR name[] = {'a',':',0};
794
795         name[0] += drive->drive;
796         if (!type_name[0] && type == DEVICE_HARDDISK) type_name = drive_types[DEVICE_FLOPPY];
797         if (type_name[0])
798             RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)type_name,
799                             (strlenW(type_name) + 1) * sizeof(WCHAR) );
800         else
801             RegDeleteValueW( hkey, name );
802         RegCloseKey( hkey );
803     }
804
805     if (udi) notify = drive->drive;
806
807 done:
808     if (volume) release_volume( volume );
809     LeaveCriticalSection( &device_section );
810     RtlFreeHeap( GetProcessHeap(), 0, path );
811     if (notify != -1) send_notify( notify, DBT_DEVICEARRIVAL );
812     return status;
813 }
814
815 /* remove an existing dos drive, by letter or udi */
816 NTSTATUS remove_dos_device( int letter, const char *udi )
817 {
818     NTSTATUS status = STATUS_NO_SUCH_DEVICE;
819     HKEY hkey;
820     struct dos_drive *drive;
821     char *path, *p;
822     int notify = -1;
823
824     EnterCriticalSection( &device_section );
825     LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
826     {
827         if (udi)
828         {
829             if (!drive->volume->udi) continue;
830             if (strcmp( udi, drive->volume->udi )) continue;
831             set_volume_udi( drive->volume, NULL );
832         }
833         else if (drive->drive != letter) continue;
834
835         if ((path = get_dosdevices_path( &p )))
836         {
837             p[0] = 'a' + drive->drive;
838             p[2] = 0;
839             unlink( path );
840             RtlFreeHeap( GetProcessHeap(), 0, path );
841         }
842
843         /* clear the registry key too */
844         if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
845         {
846             WCHAR name[] = {'a',':',0};
847             name[0] += drive->drive;
848             RegDeleteValueW( hkey, name );
849             RegCloseKey( hkey );
850         }
851
852         if (udi && drive->volume->device->unix_mount) notify = drive->drive;
853
854         delete_dos_device( drive );
855         status = STATUS_SUCCESS;
856         break;
857     }
858     LeaveCriticalSection( &device_section );
859     if (notify != -1) send_notify( notify, DBT_DEVICEREMOVECOMPLETE );
860     return status;
861 }
862
863 /* query information about an existing dos drive, by letter or udi */
864 NTSTATUS query_dos_device( int letter, enum device_type *type, char **device, char **mount_point )
865 {
866     NTSTATUS status = STATUS_NO_SUCH_DEVICE;
867     struct dos_drive *drive;
868     struct disk_device *disk_device;
869
870     EnterCriticalSection( &device_section );
871     LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
872     {
873         if (drive->drive != letter) continue;
874         disk_device = drive->volume->device;
875         if (type) *type = disk_device->type;
876         if (device) *device = strdupA( disk_device->unix_device );
877         if (mount_point) *mount_point = strdupA( disk_device->unix_mount );
878         status = STATUS_SUCCESS;
879         break;
880     }
881     LeaveCriticalSection( &device_section );
882     return status;
883 }
884
885 /* handler for ioctls on the harddisk device */
886 static NTSTATUS WINAPI harddisk_ioctl( DEVICE_OBJECT *device, IRP *irp )
887 {
888     IO_STACK_LOCATION *irpsp = IoGetCurrentIrpStackLocation( irp );
889     struct disk_device *dev = device->DeviceExtension;
890
891     TRACE( "ioctl %x insize %u outsize %u\n",
892            irpsp->Parameters.DeviceIoControl.IoControlCode,
893            irpsp->Parameters.DeviceIoControl.InputBufferLength,
894            irpsp->Parameters.DeviceIoControl.OutputBufferLength );
895
896     EnterCriticalSection( &device_section );
897
898     switch(irpsp->Parameters.DeviceIoControl.IoControlCode)
899     {
900     case IOCTL_DISK_GET_DRIVE_GEOMETRY:
901     {
902         DISK_GEOMETRY info;
903         DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
904
905         info.Cylinders.QuadPart = 10000;
906         info.MediaType = (dev->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
907         info.TracksPerCylinder = 255;
908         info.SectorsPerTrack = 63;
909         info.BytesPerSector = 512;
910         memcpy( irp->AssociatedIrp.SystemBuffer, &info, len );
911         irp->IoStatus.Information = len;
912         irp->IoStatus.u.Status = STATUS_SUCCESS;
913         break;
914     }
915     case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX:
916     {
917         DISK_GEOMETRY_EX info;
918         DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
919
920         FIXME("The DISK_PARTITION_INFO and DISK_DETECTION_INFO structures will not be filled\n");
921
922         info.Geometry.Cylinders.QuadPart = 10000;
923         info.Geometry.MediaType = (dev->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
924         info.Geometry.TracksPerCylinder = 255;
925         info.Geometry.SectorsPerTrack = 63;
926         info.Geometry.BytesPerSector = 512;
927         info.DiskSize.QuadPart = info.Geometry.Cylinders.QuadPart * info.Geometry.TracksPerCylinder *
928                                  info.Geometry.SectorsPerTrack * info.Geometry.BytesPerSector;
929         info.Data[0]  = 0;
930         memcpy( irp->AssociatedIrp.SystemBuffer, &info, len );
931         irp->IoStatus.Information = len;
932         irp->IoStatus.u.Status = STATUS_SUCCESS;
933         break;
934     }
935     case IOCTL_STORAGE_GET_DEVICE_NUMBER:
936     {
937         DWORD len = min( sizeof(dev->devnum), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
938
939         memcpy( irp->AssociatedIrp.SystemBuffer, &dev->devnum, len );
940         irp->IoStatus.Information = len;
941         irp->IoStatus.u.Status = STATUS_SUCCESS;
942         break;
943     }
944     case IOCTL_CDROM_READ_TOC:
945         irp->IoStatus.u.Status = STATUS_INVALID_DEVICE_REQUEST;
946         break;
947     case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS:
948     {
949         DWORD len = min( 32, irpsp->Parameters.DeviceIoControl.OutputBufferLength );
950
951         FIXME( "returning zero-filled buffer for IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS\n" );
952         memset( irp->AssociatedIrp.SystemBuffer, 0, len );
953         irp->IoStatus.Information = len;
954         irp->IoStatus.u.Status = STATUS_SUCCESS;
955         break;
956     }
957     default:
958     {
959         ULONG code = irpsp->Parameters.DeviceIoControl.IoControlCode;
960         FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
961               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
962         irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
963         break;
964     }
965     }
966
967     LeaveCriticalSection( &device_section );
968     IoCompleteRequest( irp, IO_NO_INCREMENT );
969     return irp->IoStatus.u.Status;
970 }
971
972 /* driver entry point for the harddisk driver */
973 NTSTATUS WINAPI harddisk_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *path )
974 {
975     struct disk_device *device;
976
977     harddisk_driver = driver;
978     driver->MajorFunction[IRP_MJ_DEVICE_CONTROL] = harddisk_ioctl;
979
980     /* create a harddisk0 device that isn't assigned to any drive */
981     create_disk_device( DEVICE_HARDDISK, &device );
982
983     create_drive_devices();
984
985     return STATUS_SUCCESS;
986 }