winealsa: Fix AudioRenderClient Get/ReleaseBuffer protocol.
[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 physdriveW[] = {'\\','?','?','\\','P','h','y','s','i','c','a','l','D','r','i','v','e','%','u',0};
199
200     UINT i, first = 0;
201     NTSTATUS status = 0;
202     const WCHAR *format = NULL;
203     UNICODE_STRING name;
204     DEVICE_OBJECT *dev_obj;
205     struct disk_device *device;
206
207     switch(type)
208     {
209     case DEVICE_UNKNOWN:
210     case DEVICE_HARDDISK:
211     case DEVICE_NETWORK:  /* FIXME */
212         format = harddiskW;
213         break;
214     case DEVICE_HARDDISK_VOL:
215         format = harddiskvolW;
216         first = 1;  /* harddisk volumes start counting from 1 */
217         break;
218     case DEVICE_FLOPPY:
219         format = floppyW;
220         break;
221     case DEVICE_CDROM:
222     case DEVICE_DVD:
223         format = cdromW;
224         break;
225     case DEVICE_RAMDISK:
226         format = ramdiskW;
227         break;
228     }
229
230     name.MaximumLength = (strlenW(format) + 10) * sizeof(WCHAR);
231     name.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, name.MaximumLength );
232     for (i = first; i < 32; i++)
233     {
234         sprintfW( name.Buffer, format, i );
235         name.Length = strlenW(name.Buffer) * sizeof(WCHAR);
236         status = IoCreateDevice( harddisk_driver, sizeof(*device), &name, 0, 0, FALSE, &dev_obj );
237         if (status != STATUS_OBJECT_NAME_COLLISION) break;
238     }
239     if (!status)
240     {
241         device = dev_obj->DeviceExtension;
242         device->dev_obj        = dev_obj;
243         device->name           = name;
244         device->type           = type;
245         device->unix_device    = NULL;
246         device->unix_mount     = NULL;
247         device->symlink.Buffer = NULL;
248
249         switch (type)
250         {
251         case DEVICE_FLOPPY:
252         case DEVICE_RAMDISK:
253             device->devnum.DeviceType = FILE_DEVICE_DISK;
254             device->devnum.DeviceNumber = i;
255             device->devnum.PartitionNumber = ~0u;
256             break;
257         case DEVICE_CDROM:
258             device->devnum.DeviceType = FILE_DEVICE_CD_ROM;
259             device->devnum.DeviceNumber = i;
260             device->devnum.PartitionNumber = ~0u;
261             break;
262         case DEVICE_DVD:
263             device->devnum.DeviceType = FILE_DEVICE_DVD;
264             device->devnum.DeviceNumber = i;
265             device->devnum.PartitionNumber = ~0u;
266             break;
267         case DEVICE_UNKNOWN:
268         case DEVICE_HARDDISK:
269         case DEVICE_NETWORK:  /* FIXME */
270             {
271                 UNICODE_STRING symlink;
272
273                 symlink.MaximumLength = sizeof(physdriveW) + 10 * sizeof(WCHAR);
274                 if ((symlink.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, symlink.MaximumLength)))
275                 {
276                     sprintfW( symlink.Buffer, physdriveW, i );
277                     symlink.Length = strlenW(symlink.Buffer) * sizeof(WCHAR);
278                     if (!IoCreateSymbolicLink( &symlink, &name )) device->symlink = symlink;
279                 }
280                 device->devnum.DeviceType = FILE_DEVICE_DISK;
281                 device->devnum.DeviceNumber = i;
282                 device->devnum.PartitionNumber = 0;
283             }
284             break;
285         case DEVICE_HARDDISK_VOL:
286             device->devnum.DeviceType = FILE_DEVICE_DISK;
287             device->devnum.DeviceNumber = 0;
288             device->devnum.PartitionNumber = i;
289             break;
290         }
291         *device_ret = device;
292         TRACE( "created device %s\n", debugstr_w(name.Buffer) );
293     }
294     else
295     {
296         FIXME( "IoCreateDevice %s got %x\n", debugstr_w(name.Buffer), status );
297         RtlFreeUnicodeString( &name );
298     }
299     return status;
300 }
301
302 /* delete the disk device for a given drive */
303 static void delete_disk_device( struct disk_device *device )
304 {
305     TRACE( "deleting device %s\n", debugstr_w(device->name.Buffer) );
306     if (device->symlink.Buffer)
307     {
308         IoDeleteSymbolicLink( &device->symlink );
309         RtlFreeUnicodeString( &device->symlink );
310     }
311     RtlFreeHeap( GetProcessHeap(), 0, device->unix_device );
312     RtlFreeHeap( GetProcessHeap(), 0, device->unix_mount );
313     RtlFreeUnicodeString( &device->name );
314     IoDeleteDevice( device->dev_obj );
315 }
316
317 /* grab another reference to a volume */
318 static struct volume *grab_volume( struct volume *volume )
319 {
320     volume->ref++;
321     return volume;
322 }
323
324 /* release a volume and delete the corresponding disk device when refcount is 0 */
325 static unsigned int release_volume( struct volume *volume )
326 {
327     unsigned int ret = --volume->ref;
328
329     if (!ret)
330     {
331         TRACE( "%s udi %s\n", debugstr_guid(&volume->guid), debugstr_a(volume->udi) );
332         assert( !volume->udi );
333         list_remove( &volume->entry );
334         if (volume->mount) delete_mount_point( volume->mount );
335         delete_disk_device( volume->device );
336         RtlFreeHeap( GetProcessHeap(), 0, volume );
337     }
338     return ret;
339 }
340
341 /* set the volume udi */
342 static void set_volume_udi( struct volume *volume, const char *udi )
343 {
344     if (udi)
345     {
346         assert( !volume->udi );
347         /* having a udi means the HAL side holds an extra reference */
348         if ((volume->udi = strdupA( udi ))) grab_volume( volume );
349     }
350     else if (volume->udi)
351     {
352         RtlFreeHeap( GetProcessHeap(), 0, volume->udi );
353         volume->udi = NULL;
354         release_volume( volume );
355     }
356 }
357
358 /* create a disk volume */
359 static NTSTATUS create_volume( const char *udi, enum device_type type, struct volume **volume_ret )
360 {
361     struct volume *volume;
362     NTSTATUS status;
363
364     if (!(volume = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*volume) )))
365         return STATUS_NO_MEMORY;
366
367     if (!(status = create_disk_device( type, &volume->device )))
368     {
369         if (udi) set_volume_udi( volume, udi );
370         list_add_tail( &volumes_list, &volume->entry );
371         *volume_ret = grab_volume( volume );
372     }
373     else RtlFreeHeap( GetProcessHeap(), 0, volume );
374
375     return status;
376 }
377
378 /* create the disk device for a given volume */
379 static NTSTATUS create_dos_device( struct volume *volume, const char *udi, int letter,
380                                    enum device_type type, struct dos_drive **drive_ret )
381 {
382     struct dos_drive *drive;
383     NTSTATUS status;
384
385     if (!(drive = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*drive) ))) return STATUS_NO_MEMORY;
386     drive->drive = letter;
387     drive->mount = NULL;
388
389     if (volume)
390     {
391         if (udi) set_volume_udi( volume, udi );
392         drive->volume = grab_volume( volume );
393         status = STATUS_SUCCESS;
394     }
395     else status = create_volume( udi, type, &drive->volume );
396
397     if (status == STATUS_SUCCESS)
398     {
399         list_add_tail( &drives_list, &drive->entry );
400         *drive_ret = drive;
401     }
402     else RtlFreeHeap( GetProcessHeap(), 0, drive );
403
404     return status;
405 }
406
407 /* delete the disk device for a given drive */
408 static void delete_dos_device( struct dos_drive *drive )
409 {
410     list_remove( &drive->entry );
411     if (drive->mount) delete_mount_point( drive->mount );
412     release_volume( drive->volume );
413     RtlFreeHeap( GetProcessHeap(), 0, drive );
414 }
415
416 /* find a volume that matches the parameters */
417 static struct volume *find_matching_volume( const char *udi, const char *device,
418                                             const char *mount_point, enum device_type type )
419 {
420     struct volume *volume;
421     struct disk_device *disk_device;
422
423     LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
424     {
425         int match = 0;
426
427         /* when we have a udi we only match drives added manually */
428         if (udi && volume->udi) continue;
429         /* and when we don't have a udi we only match dynamic drives */
430         if (!udi && !volume->udi) continue;
431
432         disk_device = volume->device;
433         if (disk_device->type != type) continue;
434         if (device && disk_device->unix_device)
435         {
436             if (strcmp( device, disk_device->unix_device )) continue;
437             match++;
438         }
439         if (mount_point && disk_device->unix_mount)
440         {
441             if (strcmp( mount_point, disk_device->unix_mount )) continue;
442             match++;
443         }
444         if (!match) continue;
445         TRACE( "found matching volume %s for device %s mount %s type %u\n",
446                debugstr_guid(&volume->guid), debugstr_a(device), debugstr_a(mount_point), type );
447         return grab_volume( volume );
448     }
449     return NULL;
450 }
451
452 /* change the information for an existing volume */
453 static NTSTATUS set_volume_info( struct volume *volume, struct dos_drive *drive, const char *device,
454                                  const char *mount_point, enum device_type type, const GUID *guid )
455 {
456     void *id = NULL;
457     unsigned int id_len = 0;
458     struct disk_device *disk_device = volume->device;
459     NTSTATUS status;
460
461     if (type != disk_device->type)
462     {
463         if ((status = create_disk_device( type, &disk_device ))) return status;
464         if (volume->mount)
465         {
466             delete_mount_point( volume->mount );
467             volume->mount = NULL;
468         }
469         if (drive && drive->mount)
470         {
471             delete_mount_point( drive->mount );
472             drive->mount = NULL;
473         }
474         delete_disk_device( volume->device );
475         volume->device = disk_device;
476     }
477     else
478     {
479         RtlFreeHeap( GetProcessHeap(), 0, disk_device->unix_device );
480         RtlFreeHeap( GetProcessHeap(), 0, disk_device->unix_mount );
481     }
482     disk_device->unix_device = strdupA( device );
483     disk_device->unix_mount = strdupA( mount_point );
484
485     if (guid && memcmp( &volume->guid, guid, sizeof(volume->guid) ))
486     {
487         volume->guid = *guid;
488         if (volume->mount)
489         {
490             delete_mount_point( volume->mount );
491             volume->mount = NULL;
492         }
493     }
494
495     if (!volume->mount)
496         volume->mount = add_volume_mount_point( disk_device->dev_obj, &disk_device->name, &volume->guid );
497     if (drive && !drive->mount)
498         drive->mount = add_dosdev_mount_point( disk_device->dev_obj, &disk_device->name, drive->drive );
499
500     if (disk_device->unix_mount)
501     {
502         id = disk_device->unix_mount;
503         id_len = strlen( disk_device->unix_mount ) + 1;
504     }
505     if (volume->mount) set_mount_point_id( volume->mount, id, id_len );
506     if (drive && drive->mount) set_mount_point_id( drive->mount, id, id_len );
507
508     return STATUS_SUCCESS;
509 }
510
511 /* change the drive letter or volume for an existing drive */
512 static void set_drive_info( struct dos_drive *drive, int letter, struct volume *volume )
513 {
514     if (drive->drive != letter)
515     {
516         if (drive->mount) delete_mount_point( drive->mount );
517         drive->mount = NULL;
518         drive->drive = letter;
519     }
520     if (drive->volume != volume)
521     {
522         if (drive->mount) delete_mount_point( drive->mount );
523         drive->mount = NULL;
524         grab_volume( volume );
525         release_volume( drive->volume );
526         drive->volume = volume;
527     }
528 }
529
530 static inline int is_valid_device( struct stat *st )
531 {
532 #if defined(linux) || defined(__sun__)
533     return S_ISBLK( st->st_mode );
534 #else
535     /* disks are char devices on *BSD */
536     return S_ISCHR( st->st_mode );
537 #endif
538 }
539
540 /* find or create a DOS drive for the corresponding device */
541 static int add_drive( const char *device, enum device_type type )
542 {
543     char *path, *p;
544     char in_use[26];
545     struct stat dev_st, drive_st;
546     int drive, first, last, avail = 0;
547
548     if (stat( device, &dev_st ) == -1 || !is_valid_device( &dev_st )) return -1;
549
550     if (!(path = get_dosdevices_path( &p ))) return -1;
551
552     memset( in_use, 0, sizeof(in_use) );
553
554     switch (type)
555     {
556     case DEVICE_FLOPPY:
557         first = 0;
558         last = 2;
559         break;
560     case DEVICE_CDROM:
561     case DEVICE_DVD:
562         first = 3;
563         last = 26;
564         break;
565     default:
566         first = 2;
567         last = 26;
568         break;
569     }
570
571     while (avail != -1)
572     {
573         avail = -1;
574         for (drive = first; drive < last; drive++)
575         {
576             if (in_use[drive]) continue;  /* already checked */
577             *p = 'a' + drive;
578             if (stat( path, &drive_st ) == -1)
579             {
580                 if (lstat( path, &drive_st ) == -1 && errno == ENOENT)  /* this is a candidate */
581                 {
582                     if (avail == -1)
583                     {
584                         p[2] = 0;
585                         /* if mount point symlink doesn't exist either, it's available */
586                         if (lstat( path, &drive_st ) == -1 && errno == ENOENT) avail = drive;
587                         p[2] = ':';
588                     }
589                 }
590                 else in_use[drive] = 1;
591             }
592             else
593             {
594                 in_use[drive] = 1;
595                 if (!is_valid_device( &drive_st )) continue;
596                 if (dev_st.st_rdev == drive_st.st_rdev) goto done;
597             }
598         }
599         if (avail != -1)
600         {
601             /* try to use the one we found */
602             drive = avail;
603             *p = 'a' + drive;
604             if (symlink( device, path ) != -1) goto done;
605             /* failed, retry the search */
606         }
607     }
608     drive = -1;
609
610 done:
611     HeapFree( GetProcessHeap(), 0, path );
612     return drive;
613 }
614
615 /* create devices for mapped drives */
616 static void create_drive_devices(void)
617 {
618     char *path, *p, *link, *device;
619     struct dos_drive *drive;
620     struct volume *volume;
621     unsigned int i;
622     HKEY drives_key;
623     enum device_type drive_type;
624     WCHAR driveW[] = {'a',':',0};
625
626     if (!(path = get_dosdevices_path( &p ))) return;
627     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &drives_key )) drives_key = 0;
628
629     for (i = 0; i < MAX_DOS_DRIVES; i++)
630     {
631         p[0] = 'a' + i;
632         p[2] = 0;
633         if (!(link = read_symlink( path ))) continue;
634         p[2] = ':';
635         device = read_symlink( path );
636
637         drive_type = i < 2 ? DEVICE_FLOPPY : DEVICE_HARDDISK_VOL;
638         if (drives_key)
639         {
640             WCHAR buffer[32];
641             DWORD j, type, size = sizeof(buffer);
642
643             driveW[0] = 'a' + i;
644             if (!RegQueryValueExW( drives_key, driveW, NULL, &type, (BYTE *)buffer, &size ) &&
645                 type == REG_SZ)
646             {
647                 for (j = 0; j < sizeof(drive_types)/sizeof(drive_types[0]); j++)
648                     if (drive_types[j][0] && !strcmpiW( buffer, drive_types[j] ))
649                     {
650                         drive_type = j;
651                         break;
652                     }
653                 if (drive_type == DEVICE_FLOPPY && i >= 2) drive_type = DEVICE_HARDDISK;
654             }
655         }
656
657         volume = find_matching_volume( NULL, device, link, drive_type );
658         if (!create_dos_device( volume, NULL, i, drive_type, &drive ))
659         {
660             /* don't reset uuid if we used an existing volume */
661             const GUID *guid = volume ? NULL : get_default_uuid(i);
662             set_volume_info( drive->volume, drive, device, link, drive_type, guid );
663         }
664         else
665         {
666             RtlFreeHeap( GetProcessHeap(), 0, link );
667             RtlFreeHeap( GetProcessHeap(), 0, device );
668         }
669         if (volume) release_volume( volume );
670     }
671     RegCloseKey( drives_key );
672     RtlFreeHeap( GetProcessHeap(), 0, path );
673 }
674
675 /* create a new disk volume */
676 NTSTATUS add_volume( const char *udi, const char *device, const char *mount_point,
677                      enum device_type type, const GUID *guid )
678 {
679     struct volume *volume;
680     NTSTATUS status = STATUS_SUCCESS;
681
682     TRACE( "adding %s device %s mount %s type %u uuid %s\n", debugstr_a(udi),
683            debugstr_a(device), debugstr_a(mount_point), type, debugstr_guid(guid) );
684
685     EnterCriticalSection( &device_section );
686     LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
687         if (volume->udi && !strcmp( udi, volume->udi ))
688         {
689             grab_volume( volume );
690             goto found;
691         }
692
693     /* udi not found, search for a non-dynamic volume */
694     if ((volume = find_matching_volume( udi, device, mount_point, type ))) set_volume_udi( volume, udi );
695     else status = create_volume( udi, type, &volume );
696
697 found:
698     if (!status) status = set_volume_info( volume, NULL, device, mount_point, type, guid );
699     if (volume) release_volume( volume );
700     LeaveCriticalSection( &device_section );
701     return status;
702 }
703
704 /* create a new disk volume */
705 NTSTATUS remove_volume( const char *udi )
706 {
707     NTSTATUS status = STATUS_NO_SUCH_DEVICE;
708     struct volume *volume;
709
710     EnterCriticalSection( &device_section );
711     LIST_FOR_EACH_ENTRY( volume, &volumes_list, struct volume, entry )
712     {
713         if (!volume->udi || strcmp( udi, volume->udi )) continue;
714         set_volume_udi( volume, NULL );
715         status = STATUS_SUCCESS;
716         break;
717     }
718     LeaveCriticalSection( &device_section );
719     return status;
720 }
721
722
723 /* create a new dos drive */
724 NTSTATUS add_dos_device( int letter, const char *udi, const char *device,
725                          const char *mount_point, enum device_type type, const GUID *guid )
726 {
727     char *path, *p;
728     HKEY hkey;
729     NTSTATUS status = STATUS_SUCCESS;
730     struct dos_drive *drive, *next;
731     struct volume *volume;
732     int notify = -1;
733
734     if (!(path = get_dosdevices_path( &p ))) return STATUS_NO_MEMORY;
735
736     EnterCriticalSection( &device_section );
737     volume = find_matching_volume( udi, device, mount_point, type );
738
739     if (letter == -1)  /* auto-assign a letter */
740     {
741         letter = add_drive( device, type );
742         if (letter == -1)
743         {
744             status = STATUS_OBJECT_NAME_COLLISION;
745             goto done;
746         }
747
748         LIST_FOR_EACH_ENTRY_SAFE( drive, next, &drives_list, struct dos_drive, entry )
749         {
750             if (drive->volume->udi && !strcmp( udi, drive->volume->udi )) goto found;
751             if (drive->drive == letter) delete_dos_device( drive );
752         }
753     }
754     else  /* simply reset the device symlink */
755     {
756         LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
757             if (drive->drive == letter) break;
758
759         *p = 'a' + letter;
760         if (&drive->entry == &drives_list) update_symlink( path, device, NULL );
761         else
762         {
763             update_symlink( path, device, drive->volume->device->unix_device );
764             delete_dos_device( drive );
765         }
766     }
767
768     if ((status = create_dos_device( volume, udi, letter, type, &drive ))) goto done;
769
770 found:
771     if (!guid && !volume) guid = get_default_uuid( letter );
772     if (!volume) volume = grab_volume( drive->volume );
773     set_drive_info( drive, letter, volume );
774     p[0] = 'a' + drive->drive;
775     p[2] = 0;
776     update_symlink( path, mount_point, volume->device->unix_mount );
777     set_volume_info( volume, drive, device, mount_point, type, guid );
778
779     TRACE( "added device %c: udi %s for %s on %s type %u\n",
780            'a' + drive->drive, wine_dbgstr_a(udi), wine_dbgstr_a(device),
781            wine_dbgstr_a(mount_point), type );
782
783     /* hack: force the drive type in the registry */
784     if (!RegCreateKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
785     {
786         const WCHAR *type_name = drive_types[type];
787         WCHAR name[] = {'a',':',0};
788
789         name[0] += drive->drive;
790         if (!type_name[0] && type == DEVICE_HARDDISK) type_name = drive_types[DEVICE_FLOPPY];
791         if (type_name[0])
792             RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)type_name,
793                             (strlenW(type_name) + 1) * sizeof(WCHAR) );
794         else
795             RegDeleteValueW( hkey, name );
796         RegCloseKey( hkey );
797     }
798
799     if (udi) notify = drive->drive;
800
801 done:
802     if (volume) release_volume( volume );
803     LeaveCriticalSection( &device_section );
804     RtlFreeHeap( GetProcessHeap(), 0, path );
805     if (notify != -1) send_notify( notify, DBT_DEVICEARRIVAL );
806     return status;
807 }
808
809 /* remove an existing dos drive, by letter or udi */
810 NTSTATUS remove_dos_device( int letter, const char *udi )
811 {
812     NTSTATUS status = STATUS_NO_SUCH_DEVICE;
813     HKEY hkey;
814     struct dos_drive *drive;
815     char *path, *p;
816     int notify = -1;
817
818     EnterCriticalSection( &device_section );
819     LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
820     {
821         if (udi)
822         {
823             if (!drive->volume->udi) continue;
824             if (strcmp( udi, drive->volume->udi )) continue;
825             set_volume_udi( drive->volume, NULL );
826         }
827         else if (drive->drive != letter) continue;
828
829         if ((path = get_dosdevices_path( &p )))
830         {
831             p[0] = 'a' + drive->drive;
832             p[2] = 0;
833             unlink( path );
834             RtlFreeHeap( GetProcessHeap(), 0, path );
835         }
836
837         /* clear the registry key too */
838         if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
839         {
840             WCHAR name[] = {'a',':',0};
841             name[0] += drive->drive;
842             RegDeleteValueW( hkey, name );
843             RegCloseKey( hkey );
844         }
845
846         if (udi && drive->volume->device->unix_mount) notify = drive->drive;
847
848         delete_dos_device( drive );
849         status = STATUS_SUCCESS;
850         break;
851     }
852     LeaveCriticalSection( &device_section );
853     if (notify != -1) send_notify( notify, DBT_DEVICEREMOVECOMPLETE );
854     return status;
855 }
856
857 /* query information about an existing dos drive, by letter or udi */
858 NTSTATUS query_dos_device( int letter, enum device_type *type, char **device, char **mount_point )
859 {
860     NTSTATUS status = STATUS_NO_SUCH_DEVICE;
861     struct dos_drive *drive;
862     struct disk_device *disk_device;
863
864     EnterCriticalSection( &device_section );
865     LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
866     {
867         if (drive->drive != letter) continue;
868         disk_device = drive->volume->device;
869         if (type) *type = disk_device->type;
870         if (device) *device = strdupA( disk_device->unix_device );
871         if (mount_point) *mount_point = strdupA( disk_device->unix_mount );
872         status = STATUS_SUCCESS;
873         break;
874     }
875     LeaveCriticalSection( &device_section );
876     return status;
877 }
878
879 /* handler for ioctls on the harddisk device */
880 static NTSTATUS WINAPI harddisk_ioctl( DEVICE_OBJECT *device, IRP *irp )
881 {
882     IO_STACK_LOCATION *irpsp = IoGetCurrentIrpStackLocation( irp );
883     struct disk_device *dev = device->DeviceExtension;
884
885     TRACE( "ioctl %x insize %u outsize %u\n",
886            irpsp->Parameters.DeviceIoControl.IoControlCode,
887            irpsp->Parameters.DeviceIoControl.InputBufferLength,
888            irpsp->Parameters.DeviceIoControl.OutputBufferLength );
889
890     EnterCriticalSection( &device_section );
891
892     switch(irpsp->Parameters.DeviceIoControl.IoControlCode)
893     {
894     case IOCTL_DISK_GET_DRIVE_GEOMETRY:
895     {
896         DISK_GEOMETRY info;
897         DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
898
899         info.Cylinders.QuadPart = 10000;
900         info.MediaType = (dev->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
901         info.TracksPerCylinder = 255;
902         info.SectorsPerTrack = 63;
903         info.BytesPerSector = 512;
904         memcpy( irp->AssociatedIrp.SystemBuffer, &info, len );
905         irp->IoStatus.Information = len;
906         irp->IoStatus.u.Status = STATUS_SUCCESS;
907         break;
908     }
909     case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX:
910     {
911         DISK_GEOMETRY_EX info;
912         DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
913
914         FIXME("The DISK_PARTITION_INFO and DISK_DETECTION_INFO structures will not be filled\n");
915
916         info.Geometry.Cylinders.QuadPart = 10000;
917         info.Geometry.MediaType = (dev->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
918         info.Geometry.TracksPerCylinder = 255;
919         info.Geometry.SectorsPerTrack = 63;
920         info.Geometry.BytesPerSector = 512;
921         info.DiskSize.QuadPart = info.Geometry.Cylinders.QuadPart * info.Geometry.TracksPerCylinder *
922                                  info.Geometry.SectorsPerTrack * info.Geometry.BytesPerSector;
923         info.Data[0]  = 0;
924         memcpy( irp->AssociatedIrp.SystemBuffer, &info, len );
925         irp->IoStatus.Information = len;
926         irp->IoStatus.u.Status = STATUS_SUCCESS;
927         break;
928     }
929     case IOCTL_STORAGE_GET_DEVICE_NUMBER:
930     {
931         DWORD len = min( sizeof(dev->devnum), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
932
933         memcpy( irp->AssociatedIrp.SystemBuffer, &dev->devnum, len );
934         irp->IoStatus.Information = len;
935         irp->IoStatus.u.Status = STATUS_SUCCESS;
936         break;
937     }
938     case IOCTL_CDROM_READ_TOC:
939         irp->IoStatus.u.Status = STATUS_INVALID_DEVICE_REQUEST;
940         break;
941     case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS:
942     {
943         DWORD len = min( 32, irpsp->Parameters.DeviceIoControl.OutputBufferLength );
944
945         FIXME( "returning zero-filled buffer for IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS\n" );
946         memset( irp->AssociatedIrp.SystemBuffer, 0, len );
947         irp->IoStatus.Information = len;
948         irp->IoStatus.u.Status = STATUS_SUCCESS;
949         break;
950     }
951     default:
952     {
953         ULONG code = irpsp->Parameters.DeviceIoControl.IoControlCode;
954         FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
955               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
956         irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
957         break;
958     }
959     }
960
961     LeaveCriticalSection( &device_section );
962     IoCompleteRequest( irp, IO_NO_INCREMENT );
963     return irp->IoStatus.u.Status;
964 }
965
966 /* driver entry point for the harddisk driver */
967 NTSTATUS WINAPI harddisk_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *path )
968 {
969     struct disk_device *device;
970
971     harddisk_driver = driver;
972     driver->MajorFunction[IRP_MJ_DEVICE_CONTROL] = harddisk_ioctl;
973
974     /* create a harddisk0 device that isn't assigned to any drive */
975     create_disk_device( DEVICE_HARDDISK, &device );
976
977     create_drive_devices();
978
979     return STATUS_SUCCESS;
980 }