include: Make sure __int64 is correctly defined on PPC64.
[wine.git] / dlls / ntoskrnl.exe / pnp.c
blob713e469ee7e99dabd7609b1104d31c47f6d173c5
1 /*
2 * Plug and Play
4 * Copyright 2016 Sebastian Lackner
5 * Copyright 2016 Aric Stewart for CodeWeavers
6 * Copyright 2019 Zebediah Figura
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include <stdarg.h>
25 #define NONAMELESSUNION
27 #include "ntstatus.h"
28 #define WIN32_NO_STATUS
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winioctl.h"
32 #include "winreg.h"
33 #include "winuser.h"
34 #include "winsvc.h"
35 #include "winternl.h"
36 #include "setupapi.h"
37 #include "cfgmgr32.h"
38 #include "dbt.h"
39 #include "ddk/wdm.h"
40 #include "ddk/ntifs.h"
41 #include "wine/debug.h"
42 #include "wine/exception.h"
43 #include "wine/heap.h"
44 #include "wine/rbtree.h"
46 #include "ntoskrnl_private.h"
47 #include "plugplay.h"
49 #include "initguid.h"
50 DEFINE_GUID(GUID_NULL,0,0,0,0,0,0,0,0,0,0,0);
52 WINE_DEFAULT_DEBUG_CHANNEL(plugplay);
54 #define MAX_SERVICE_NAME 260
56 struct device_interface
58 struct wine_rb_entry entry;
60 UNICODE_STRING symbolic_link;
61 DEVICE_OBJECT *device;
62 GUID interface_class;
63 BOOL enabled;
66 static int interface_rb_compare( const void *key, const struct wine_rb_entry *entry)
68 const struct device_interface *iface = WINE_RB_ENTRY_VALUE( entry, const struct device_interface, entry );
69 const UNICODE_STRING *k = key;
71 return RtlCompareUnicodeString( k, &iface->symbolic_link, FALSE );
74 static struct wine_rb_tree device_interfaces = { interface_rb_compare };
76 static NTSTATUS WINAPI internal_complete( DEVICE_OBJECT *device, IRP *irp, void *context )
78 HANDLE event = context;
79 SetEvent( event );
80 return STATUS_MORE_PROCESSING_REQUIRED;
83 static NTSTATUS send_device_irp( DEVICE_OBJECT *device, IRP *irp, ULONG_PTR *info )
85 HANDLE event = CreateEventA( NULL, FALSE, FALSE, NULL );
86 DEVICE_OBJECT *toplevel_device;
87 NTSTATUS status;
89 irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
90 IoSetCompletionRoutine( irp, internal_complete, event, TRUE, TRUE, TRUE );
92 toplevel_device = IoGetAttachedDeviceReference( device );
93 status = IoCallDriver( toplevel_device, irp );
95 if (status == STATUS_PENDING)
96 WaitForSingleObject( event, INFINITE );
98 status = irp->IoStatus.u.Status;
99 if (info)
100 *info = irp->IoStatus.Information;
101 IoCompleteRequest( irp, IO_NO_INCREMENT );
102 ObDereferenceObject( toplevel_device );
103 CloseHandle( event );
104 return status;
107 static NTSTATUS get_device_id( DEVICE_OBJECT *device, BUS_QUERY_ID_TYPE type, WCHAR **id )
109 IO_STACK_LOCATION *irpsp;
110 IO_STATUS_BLOCK irp_status;
111 IRP *irp;
113 device = IoGetAttachedDevice( device );
115 if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_PNP, device, NULL, 0, NULL, NULL, &irp_status )))
116 return STATUS_NO_MEMORY;
118 irpsp = IoGetNextIrpStackLocation( irp );
119 irpsp->MinorFunction = IRP_MN_QUERY_ID;
120 irpsp->Parameters.QueryId.IdType = type;
122 return send_device_irp( device, irp, (ULONG_PTR *)id );
125 static NTSTATUS send_pnp_irp( DEVICE_OBJECT *device, UCHAR minor )
127 IO_STACK_LOCATION *irpsp;
128 IO_STATUS_BLOCK irp_status;
129 IRP *irp;
131 device = IoGetAttachedDevice( device );
133 if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_PNP, device, NULL, 0, NULL, NULL, &irp_status )))
134 return STATUS_NO_MEMORY;
136 irpsp = IoGetNextIrpStackLocation( irp );
137 irpsp->MinorFunction = minor;
139 irpsp->Parameters.StartDevice.AllocatedResources = NULL;
140 irpsp->Parameters.StartDevice.AllocatedResourcesTranslated = NULL;
142 return send_device_irp( device, irp, NULL );
145 static NTSTATUS get_device_instance_id( DEVICE_OBJECT *device, WCHAR *buffer )
147 static const WCHAR backslashW[] = {'\\',0};
148 NTSTATUS status;
149 WCHAR *id;
151 if ((status = get_device_id( device, BusQueryDeviceID, &id )))
153 ERR("Failed to get device ID, status %#x.\n", status);
154 return status;
157 lstrcpyW( buffer, id );
158 ExFreePool( id );
160 if ((status = get_device_id( device, BusQueryInstanceID, &id )))
162 ERR("Failed to get instance ID, status %#x.\n", status);
163 return status;
166 lstrcatW( buffer, backslashW );
167 lstrcatW( buffer, id );
168 ExFreePool( id );
170 TRACE("Returning ID %s.\n", debugstr_w(buffer));
172 return STATUS_SUCCESS;
175 static NTSTATUS send_power_irp( DEVICE_OBJECT *device, DEVICE_POWER_STATE power )
177 IO_STATUS_BLOCK irp_status;
178 IO_STACK_LOCATION *irpsp;
179 IRP *irp;
181 device = IoGetAttachedDevice( device );
183 if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_POWER, device, NULL, 0, NULL, NULL, &irp_status )))
184 return STATUS_NO_MEMORY;
186 irpsp = IoGetNextIrpStackLocation( irp );
187 irpsp->MinorFunction = IRP_MN_SET_POWER;
189 irpsp->Parameters.Power.Type = DevicePowerState;
190 irpsp->Parameters.Power.State.DeviceState = power;
192 return send_device_irp( device, irp, NULL );
195 static void load_function_driver( DEVICE_OBJECT *device, HDEVINFO set, SP_DEVINFO_DATA *sp_device )
197 static const WCHAR driverW[] = {'\\','D','r','i','v','e','r','\\',0};
198 WCHAR buffer[MAX_SERVICE_NAME + ARRAY_SIZE(servicesW)];
199 WCHAR driver[MAX_SERVICE_NAME] = {0};
200 DRIVER_OBJECT *driver_obj;
201 UNICODE_STRING string;
202 NTSTATUS status;
204 if (!SetupDiGetDeviceRegistryPropertyW( set, sp_device, SPDRP_SERVICE,
205 NULL, (BYTE *)driver, sizeof(driver), NULL ))
207 WARN("No driver registered for device %p.\n", device);
208 return;
211 lstrcpyW( buffer, servicesW );
212 lstrcatW( buffer, driver );
213 RtlInitUnicodeString( &string, buffer );
214 status = ZwLoadDriver( &string );
215 if (status != STATUS_SUCCESS && status != STATUS_IMAGE_ALREADY_LOADED)
217 ERR("Failed to load driver %s, status %#x.\n", debugstr_w(driver), status);
218 return;
221 lstrcpyW( buffer, driverW );
222 lstrcatW( buffer, driver );
223 RtlInitUnicodeString( &string, buffer );
224 if (ObReferenceObjectByName( &string, OBJ_CASE_INSENSITIVE, NULL,
225 0, NULL, KernelMode, NULL, (void **)&driver_obj ) != STATUS_SUCCESS)
227 ERR("Failed to locate loaded driver %s.\n", debugstr_w(driver));
228 return;
231 TRACE("Calling AddDevice routine %p.\n", driver_obj->DriverExtension->AddDevice);
232 if (driver_obj->DriverExtension->AddDevice)
233 status = driver_obj->DriverExtension->AddDevice( driver_obj, device );
234 else
235 status = STATUS_NOT_IMPLEMENTED;
236 TRACE("AddDevice routine %p returned %#x.\n", driver_obj->DriverExtension->AddDevice, status);
238 ObDereferenceObject( driver_obj );
240 if (status != STATUS_SUCCESS)
241 ERR("AddDevice failed for driver %s, status %#x.\n", debugstr_w(driver), status);
244 /* Return the total number of characters in a REG_MULTI_SZ string, including
245 * the final terminating null. */
246 static size_t sizeof_multiszW( const WCHAR *str )
248 const WCHAR *p;
249 for (p = str; *p; p += lstrlenW(p) + 1);
250 return p + 1 - str;
253 /* This does almost the same thing as UpdateDriverForPlugAndPlayDevices(),
254 * except that we don't know the INF path beforehand. */
255 static BOOL install_device_driver( DEVICE_OBJECT *device, HDEVINFO set, SP_DEVINFO_DATA *sp_device )
257 static const DWORD dif_list[] =
259 DIF_REGISTERDEVICE,
260 DIF_SELECTBESTCOMPATDRV,
261 DIF_ALLOW_INSTALL,
262 DIF_INSTALLDEVICEFILES,
263 DIF_REGISTER_COINSTALLERS,
264 DIF_INSTALLINTERFACES,
265 DIF_INSTALLDEVICE,
266 DIF_NEWDEVICEWIZARD_FINISHINSTALL,
269 NTSTATUS status;
270 unsigned int i;
271 WCHAR *ids;
273 if ((status = get_device_id( device, BusQueryHardwareIDs, &ids )) || !ids)
275 ERR("Failed to get hardware IDs, status %#x.\n", status);
276 return FALSE;
279 SetupDiSetDeviceRegistryPropertyW( set, sp_device, SPDRP_HARDWAREID, (BYTE *)ids,
280 sizeof_multiszW( ids ) * sizeof(WCHAR) );
281 ExFreePool( ids );
283 if ((status = get_device_id( device, BusQueryCompatibleIDs, &ids )) || !ids)
285 ERR("Failed to get compatible IDs, status %#x.\n", status);
286 return FALSE;
289 SetupDiSetDeviceRegistryPropertyW( set, sp_device, SPDRP_COMPATIBLEIDS, (BYTE *)ids,
290 sizeof_multiszW( ids ) * sizeof(WCHAR) );
291 ExFreePool( ids );
293 if (!SetupDiBuildDriverInfoList( set, sp_device, SPDIT_COMPATDRIVER ))
295 ERR("Failed to build compatible driver list, error %#x.\n", GetLastError());
296 return FALSE;
299 for (i = 0; i < ARRAY_SIZE(dif_list); ++i)
301 if (!SetupDiCallClassInstaller(dif_list[i], set, sp_device) && GetLastError() != ERROR_DI_DO_DEFAULT)
303 WARN("Install function %#x failed, error %#x.\n", dif_list[i], GetLastError());
304 return FALSE;
308 return TRUE;
311 /* Load the function driver for a newly created PDO, if one is present, and
312 * send IRPs to start the device. */
313 static void start_device( DEVICE_OBJECT *device, HDEVINFO set, SP_DEVINFO_DATA *sp_device )
315 load_function_driver( device, set, sp_device );
316 if (device->DriverObject)
318 send_pnp_irp( device, IRP_MN_START_DEVICE );
319 send_power_irp( device, PowerDeviceD0 );
323 static void enumerate_new_device( DEVICE_OBJECT *device, HDEVINFO set )
325 static const WCHAR infpathW[] = {'I','n','f','P','a','t','h',0};
327 SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
328 WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
329 BOOL need_driver = TRUE;
330 HKEY key;
332 if (get_device_instance_id( device, device_instance_id ))
333 return;
335 if (!SetupDiCreateDeviceInfoW( set, device_instance_id, &GUID_NULL, NULL, NULL, 0, &sp_device )
336 && !SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device ))
338 ERR("Failed to create or open device %s, error %#x.\n", debugstr_w(device_instance_id), GetLastError());
339 return;
342 TRACE("Creating new device %s.\n", debugstr_w(device_instance_id));
344 /* Check if the device already has a driver registered; if not, find one
345 * and install it. */
346 key = SetupDiOpenDevRegKey( set, &sp_device, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_READ );
347 if (key != INVALID_HANDLE_VALUE)
349 if (!RegQueryValueExW( key, infpathW, NULL, NULL, NULL, NULL ))
350 need_driver = FALSE;
351 RegCloseKey( key );
354 if (need_driver && !install_device_driver( device, set, &sp_device ))
355 return;
357 start_device( device, set, &sp_device );
360 static void remove_device( DEVICE_OBJECT *device )
362 struct wine_device *wine_device = CONTAINING_RECORD(device, struct wine_device, device_obj);
364 TRACE("Removing device %p.\n", device);
366 if (wine_device->children)
368 ULONG i;
369 for (i = 0; i < wine_device->children->Count; ++i)
370 remove_device( wine_device->children->Objects[i] );
373 send_power_irp( device, PowerDeviceD3 );
374 send_pnp_irp( device, IRP_MN_SURPRISE_REMOVAL );
375 send_pnp_irp( device, IRP_MN_REMOVE_DEVICE );
378 static BOOL device_in_list( const DEVICE_RELATIONS *list, const DEVICE_OBJECT *device )
380 ULONG i;
381 for (i = 0; i < list->Count; ++i)
383 if (list->Objects[i] == device)
384 return TRUE;
386 return FALSE;
389 static void handle_bus_relations( DEVICE_OBJECT *parent )
391 struct wine_device *wine_parent = CONTAINING_RECORD(parent, struct wine_device, device_obj);
392 SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
393 DEVICE_RELATIONS *relations;
394 IO_STATUS_BLOCK irp_status;
395 IO_STACK_LOCATION *irpsp;
396 NTSTATUS status;
397 HDEVINFO set;
398 IRP *irp;
399 ULONG i;
401 TRACE( "(%p)\n", parent );
403 set = SetupDiCreateDeviceInfoList( NULL, NULL );
405 parent = IoGetAttachedDevice( parent );
407 if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_PNP, parent, NULL, 0, NULL, NULL, &irp_status )))
409 SetupDiDestroyDeviceInfoList( set );
410 return;
413 irpsp = IoGetNextIrpStackLocation( irp );
414 irpsp->MinorFunction = IRP_MN_QUERY_DEVICE_RELATIONS;
415 irpsp->Parameters.QueryDeviceRelations.Type = BusRelations;
416 if ((status = send_device_irp( parent, irp, (ULONG_PTR *)&relations )))
418 ERR("Failed to enumerate child devices, status %#x.\n", status);
419 SetupDiDestroyDeviceInfoList( set );
420 return;
423 TRACE("Got %u devices.\n", relations->Count);
425 for (i = 0; i < relations->Count; ++i)
427 DEVICE_OBJECT *child = relations->Objects[i];
429 if (!wine_parent->children || !device_in_list( wine_parent->children, child ))
431 TRACE("Adding new device %p.\n", child);
432 enumerate_new_device( child, set );
436 if (wine_parent->children)
438 for (i = 0; i < wine_parent->children->Count; ++i)
440 DEVICE_OBJECT *child = wine_parent->children->Objects[i];
442 if (!device_in_list( relations, child ))
444 TRACE("Removing device %p.\n", child);
445 remove_device( child );
447 ObDereferenceObject( child );
451 ExFreePool( wine_parent->children );
452 wine_parent->children = relations;
454 SetupDiDestroyDeviceInfoList( set );
457 /***********************************************************************
458 * IoInvalidateDeviceRelations (NTOSKRNL.EXE.@)
460 void WINAPI IoInvalidateDeviceRelations( DEVICE_OBJECT *device_object, DEVICE_RELATION_TYPE type )
462 TRACE("device %p, type %#x.\n", device_object, type);
464 switch (type)
466 case BusRelations:
467 handle_bus_relations( device_object );
468 break;
469 default:
470 FIXME("Unhandled relation %#x.\n", type);
471 break;
475 /***********************************************************************
476 * IoGetDeviceProperty (NTOSKRNL.EXE.@)
478 NTSTATUS WINAPI IoGetDeviceProperty( DEVICE_OBJECT *device, DEVICE_REGISTRY_PROPERTY property,
479 ULONG length, void *buffer, ULONG *needed )
481 SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
482 WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
483 DWORD sp_property = -1;
484 NTSTATUS status;
485 HDEVINFO set;
487 TRACE("device %p, property %u, length %u, buffer %p, needed %p.\n",
488 device, property, length, buffer, needed);
490 switch (property)
492 case DevicePropertyEnumeratorName:
494 WCHAR *id, *ptr;
496 status = get_device_id( device, BusQueryInstanceID, &id );
497 if (status != STATUS_SUCCESS)
499 ERR("Failed to get instance ID, status %#x.\n", status);
500 break;
503 wcsupr( id );
504 ptr = wcschr( id, '\\' );
505 if (ptr) *ptr = 0;
507 *needed = sizeof(WCHAR) * (lstrlenW(id) + 1);
508 if (length >= *needed)
509 memcpy( buffer, id, *needed );
510 else
511 status = STATUS_BUFFER_TOO_SMALL;
513 ExFreePool( id );
514 return status;
516 case DevicePropertyPhysicalDeviceObjectName:
518 ULONG used_len, len = length + sizeof(OBJECT_NAME_INFORMATION);
519 OBJECT_NAME_INFORMATION *name = HeapAlloc(GetProcessHeap(), 0, len);
520 HANDLE handle;
522 status = ObOpenObjectByPointer( device, OBJ_KERNEL_HANDLE, NULL, 0, NULL, KernelMode, &handle );
523 if (!status)
525 status = NtQueryObject( handle, ObjectNameInformation, name, len, &used_len );
526 NtClose( handle );
528 if (status == STATUS_SUCCESS)
530 /* Ensure room for NULL termination */
531 if (length >= name->Name.MaximumLength)
532 memcpy(buffer, name->Name.Buffer, name->Name.MaximumLength);
533 else
534 status = STATUS_BUFFER_TOO_SMALL;
535 *needed = name->Name.MaximumLength;
537 else
539 if (status == STATUS_INFO_LENGTH_MISMATCH ||
540 status == STATUS_BUFFER_OVERFLOW)
542 status = STATUS_BUFFER_TOO_SMALL;
543 *needed = used_len - sizeof(OBJECT_NAME_INFORMATION);
545 else
546 *needed = 0;
548 HeapFree(GetProcessHeap(), 0, name);
549 return status;
551 case DevicePropertyDeviceDescription:
552 sp_property = SPDRP_DEVICEDESC;
553 break;
554 case DevicePropertyHardwareID:
555 sp_property = SPDRP_HARDWAREID;
556 break;
557 case DevicePropertyCompatibleIDs:
558 sp_property = SPDRP_COMPATIBLEIDS;
559 break;
560 case DevicePropertyClassName:
561 sp_property = SPDRP_CLASS;
562 break;
563 case DevicePropertyClassGuid:
564 sp_property = SPDRP_CLASSGUID;
565 break;
566 case DevicePropertyManufacturer:
567 sp_property = SPDRP_MFG;
568 break;
569 case DevicePropertyFriendlyName:
570 sp_property = SPDRP_FRIENDLYNAME;
571 break;
572 case DevicePropertyLocationInformation:
573 sp_property = SPDRP_LOCATION_INFORMATION;
574 break;
575 case DevicePropertyBusTypeGuid:
576 sp_property = SPDRP_BUSTYPEGUID;
577 break;
578 case DevicePropertyLegacyBusType:
579 sp_property = SPDRP_LEGACYBUSTYPE;
580 break;
581 case DevicePropertyBusNumber:
582 sp_property = SPDRP_BUSNUMBER;
583 break;
584 case DevicePropertyAddress:
585 sp_property = SPDRP_ADDRESS;
586 break;
587 case DevicePropertyUINumber:
588 sp_property = SPDRP_UI_NUMBER;
589 break;
590 case DevicePropertyInstallState:
591 sp_property = SPDRP_INSTALL_STATE;
592 break;
593 case DevicePropertyRemovalPolicy:
594 sp_property = SPDRP_REMOVAL_POLICY;
595 break;
596 default:
597 FIXME("Unhandled property %u.\n", property);
598 return STATUS_NOT_IMPLEMENTED;
601 if ((status = get_device_instance_id( device, device_instance_id )))
602 return status;
604 if ((set = SetupDiCreateDeviceInfoList( &GUID_NULL, NULL )) == INVALID_HANDLE_VALUE)
606 ERR("Failed to create device list, error %#x.\n", GetLastError());
607 return GetLastError();
610 if (!SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device))
612 ERR("Failed to open device, error %#x.\n", GetLastError());
613 SetupDiDestroyDeviceInfoList( set );
614 return GetLastError();
617 if (SetupDiGetDeviceRegistryPropertyW( set, &sp_device, sp_property, NULL, buffer, length, needed ))
618 status = STATUS_SUCCESS;
619 else
620 status = GetLastError();
622 SetupDiDestroyDeviceInfoList( set );
624 return status;
627 static NTSTATUS create_device_symlink( DEVICE_OBJECT *device, UNICODE_STRING *symlink_name )
629 UNICODE_STRING device_nameU;
630 WCHAR *device_name;
631 ULONG len = 0;
632 NTSTATUS ret;
634 ret = IoGetDeviceProperty( device, DevicePropertyPhysicalDeviceObjectName, 0, NULL, &len );
635 if (ret != STATUS_BUFFER_TOO_SMALL)
636 return ret;
638 device_name = heap_alloc( len );
639 ret = IoGetDeviceProperty( device, DevicePropertyPhysicalDeviceObjectName, len, device_name, &len );
640 if (ret)
642 heap_free( device_name );
643 return ret;
646 RtlInitUnicodeString( &device_nameU, device_name );
647 ret = IoCreateSymbolicLink( symlink_name, &device_nameU );
648 heap_free( device_name );
649 return ret;
652 void __RPC_FAR * __RPC_USER MIDL_user_allocate( SIZE_T len )
654 return heap_alloc( len );
657 void __RPC_USER MIDL_user_free( void __RPC_FAR *ptr )
659 heap_free( ptr );
662 static LONG WINAPI rpc_filter( EXCEPTION_POINTERS *eptr )
664 return I_RpcExceptionFilter( eptr->ExceptionRecord->ExceptionCode );
667 static void send_devicechange( DWORD code, void *data, unsigned int size )
669 __TRY
671 plugplay_send_event( code, data, size );
673 __EXCEPT(rpc_filter)
675 WARN("Failed to send event, exception %#x.\n", GetExceptionCode());
677 __ENDTRY
680 /***********************************************************************
681 * IoSetDeviceInterfaceState (NTOSKRNL.EXE.@)
683 NTSTATUS WINAPI IoSetDeviceInterfaceState( UNICODE_STRING *name, BOOLEAN enable )
685 static const WCHAR DeviceClassesW[] = {'\\','R','E','G','I','S','T','R','Y','\\',
686 'M','a','c','h','i','n','e','\\','S','y','s','t','e','m','\\',
687 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
688 'C','o','n','t','r','o','l','\\',
689 'D','e','v','i','c','e','C','l','a','s','s','e','s','\\',0};
690 static const WCHAR controlW[] = {'C','o','n','t','r','o','l',0};
691 static const WCHAR linkedW[] = {'L','i','n','k','e','d',0};
692 static const WCHAR slashW[] = {'\\',0};
693 static const WCHAR hashW[] = {'#',0};
695 size_t namelen = name->Length / sizeof(WCHAR);
696 DEV_BROADCAST_DEVICEINTERFACE_W *broadcast;
697 struct device_interface *iface;
698 HANDLE iface_key, control_key;
699 OBJECT_ATTRIBUTES attr = {0};
700 struct wine_rb_entry *entry;
701 WCHAR *path, *refstr, *p;
702 UNICODE_STRING string;
703 DWORD data = enable;
704 NTSTATUS ret;
705 ULONG len;
707 TRACE("device %s, enable %u.\n", debugstr_us(name), enable);
709 entry = wine_rb_get( &device_interfaces, name );
710 if (!entry)
711 return STATUS_OBJECT_NAME_NOT_FOUND;
713 iface = WINE_RB_ENTRY_VALUE( entry, struct device_interface, entry );
715 if (!enable && !iface->enabled)
716 return STATUS_OBJECT_NAME_NOT_FOUND;
718 if (enable && iface->enabled)
719 return STATUS_OBJECT_NAME_EXISTS;
721 for (p = name->Buffer + 4, refstr = NULL; p < name->Buffer + namelen; p++)
722 if (*p == '\\') refstr = p;
723 if (!refstr) refstr = p;
725 len = lstrlenW(DeviceClassesW) + 38 + 1 + namelen + 2 + 1;
727 if (!(path = heap_alloc( len * sizeof(WCHAR) )))
728 return STATUS_NO_MEMORY;
730 lstrcpyW( path, DeviceClassesW );
731 lstrcpynW( path + lstrlenW( path ), refstr - 38, 39 );
732 lstrcatW( path, slashW );
733 p = path + lstrlenW( path );
734 lstrcpynW( path + lstrlenW( path ), name->Buffer, (refstr - name->Buffer) + 1 );
735 p[0] = p[1] = p[3] = '#';
736 lstrcatW( path, slashW );
737 lstrcatW( path, hashW );
738 if (refstr < name->Buffer + namelen)
739 lstrcpynW( path + lstrlenW( path ), refstr, name->Buffer + namelen - refstr + 1 );
741 attr.Length = sizeof(attr);
742 attr.ObjectName = &string;
743 RtlInitUnicodeString( &string, path );
744 ret = NtOpenKey( &iface_key, KEY_CREATE_SUB_KEY, &attr );
745 heap_free(path);
746 if (ret)
747 return ret;
749 attr.RootDirectory = iface_key;
750 RtlInitUnicodeString( &string, controlW );
751 ret = NtCreateKey( &control_key, KEY_SET_VALUE, &attr, 0, NULL, REG_OPTION_VOLATILE, NULL );
752 NtClose( iface_key );
753 if (ret)
754 return ret;
756 RtlInitUnicodeString( &string, linkedW );
757 ret = NtSetValueKey( control_key, &string, 0, REG_DWORD, &data, sizeof(data) );
758 if (ret)
760 NtClose( control_key );
761 return ret;
764 if (enable)
765 ret = create_device_symlink( iface->device, name );
766 else
767 ret = IoDeleteSymbolicLink( name );
768 if (ret)
770 NtDeleteValueKey( control_key, &string );
771 NtClose( control_key );
772 return ret;
775 iface->enabled = enable;
777 len = offsetof(DEV_BROADCAST_DEVICEINTERFACE_W, dbcc_name[namelen + 1]);
779 if ((broadcast = heap_alloc( len )))
781 broadcast->dbcc_size = len;
782 broadcast->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
783 broadcast->dbcc_reserved = 0;
784 broadcast->dbcc_classguid = iface->interface_class;
785 lstrcpynW( broadcast->dbcc_name, name->Buffer, namelen + 1 );
786 send_devicechange( enable ? DBT_DEVICEARRIVAL : DBT_DEVICEREMOVECOMPLETE, broadcast, len );
787 heap_free( broadcast );
789 return ret;
792 /***********************************************************************
793 * IoRegisterDeviceInterface (NTOSKRNL.EXE.@)
795 NTSTATUS WINAPI IoRegisterDeviceInterface(DEVICE_OBJECT *device, const GUID *class_guid,
796 UNICODE_STRING *refstr, UNICODE_STRING *symbolic_link)
798 SP_DEVICE_INTERFACE_DATA sp_iface = {sizeof(sp_iface)};
799 SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
800 WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
801 SP_DEVICE_INTERFACE_DETAIL_DATA_W *data;
802 NTSTATUS status = STATUS_SUCCESS;
803 UNICODE_STRING device_path;
804 struct device_interface *iface;
805 struct wine_rb_entry *entry;
806 DWORD required;
807 HDEVINFO set;
809 TRACE("device %p, class_guid %s, refstr %s, symbolic_link %p.\n",
810 device, debugstr_guid(class_guid), debugstr_us(refstr), symbolic_link);
812 if ((status = get_device_instance_id( device, device_instance_id )))
813 return status;
815 set = SetupDiGetClassDevsW( class_guid, NULL, NULL, DIGCF_DEVICEINTERFACE );
816 if (set == INVALID_HANDLE_VALUE) return STATUS_UNSUCCESSFUL;
818 if (!SetupDiCreateDeviceInfoW( set, device_instance_id, class_guid, NULL, NULL, 0, &sp_device )
819 && !SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device ))
821 ERR("Failed to create device %s, error %#x.\n", debugstr_w(device_instance_id), GetLastError());
822 return GetLastError();
825 if (!SetupDiCreateDeviceInterfaceW( set, &sp_device, class_guid, refstr ? refstr->Buffer : NULL, 0, &sp_iface ))
826 return STATUS_UNSUCCESSFUL;
828 required = 0;
829 SetupDiGetDeviceInterfaceDetailW( set, &sp_iface, NULL, 0, &required, NULL );
830 if (required == 0) return STATUS_UNSUCCESSFUL;
832 data = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, required );
833 data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
835 if (!SetupDiGetDeviceInterfaceDetailW( set, &sp_iface, data, required, NULL, NULL ))
837 HeapFree( GetProcessHeap(), 0, data );
838 return STATUS_UNSUCCESSFUL;
841 data->DevicePath[1] = '?';
842 TRACE("Returning path %s.\n", debugstr_w(data->DevicePath));
843 RtlCreateUnicodeString( &device_path, data->DevicePath);
845 entry = wine_rb_get( &device_interfaces, &device_path );
846 if (entry)
848 iface = WINE_RB_ENTRY_VALUE( entry, struct device_interface, entry );
849 if (iface->enabled)
850 ERR("Device interface %s is still enabled.\n", debugstr_us(&iface->symbolic_link));
852 else
854 iface = heap_alloc_zero( sizeof(struct device_interface) );
855 RtlCreateUnicodeString(&iface->symbolic_link, data->DevicePath);
856 if (wine_rb_put( &device_interfaces, &iface->symbolic_link, &iface->entry ))
857 ERR("Failed to insert interface %s into tree.\n", debugstr_us(&iface->symbolic_link));
860 iface->device = device;
861 iface->interface_class = *class_guid;
862 if (symbolic_link)
863 RtlCreateUnicodeString( symbolic_link, data->DevicePath);
865 HeapFree( GetProcessHeap(), 0, data );
867 RtlFreeUnicodeString( &device_path );
869 return status;
872 /***********************************************************************
873 * IoOpenDeviceRegistryKey (NTOSKRNL.EXE.@)
875 NTSTATUS WINAPI IoOpenDeviceRegistryKey( DEVICE_OBJECT *device, ULONG type, ACCESS_MASK access, HANDLE *key )
877 SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
878 WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
879 NTSTATUS status;
880 HDEVINFO set;
882 TRACE("device %p, type %#x, access %#x, key %p.\n", device, type, access, key);
884 if ((status = get_device_instance_id( device, device_instance_id )))
886 ERR("Failed to get device instance ID, error %#x.\n", status);
887 return status;
890 set = SetupDiCreateDeviceInfoList( &GUID_NULL, NULL );
892 SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device );
894 *key = SetupDiOpenDevRegKey( set, &sp_device, DICS_FLAG_GLOBAL, 0, type, access );
895 SetupDiDestroyDeviceInfoList( set );
896 if (*key == INVALID_HANDLE_VALUE)
897 return GetLastError();
898 return STATUS_SUCCESS;
901 /***********************************************************************
902 * PoSetPowerState (NTOSKRNL.EXE.@)
904 POWER_STATE WINAPI PoSetPowerState( DEVICE_OBJECT *device, POWER_STATE_TYPE type, POWER_STATE state)
906 FIXME("device %p, type %u, state %u, stub!\n", device, type, state.DeviceState);
907 return state;
910 /*****************************************************
911 * PoStartNextPowerIrp (NTOSKRNL.EXE.@)
913 void WINAPI PoStartNextPowerIrp( IRP *irp )
915 FIXME("irp %p, stub!\n", irp);
918 /*****************************************************
919 * PoCallDriver (NTOSKRNL.EXE.@)
921 NTSTATUS WINAPI PoCallDriver( DEVICE_OBJECT *device, IRP *irp )
923 TRACE("device %p, irp %p.\n", device, irp);
924 return IoCallDriver( device, irp );
927 static DRIVER_OBJECT *pnp_manager;
929 struct root_pnp_device
931 WCHAR id[MAX_DEVICE_ID_LEN];
932 struct wine_rb_entry entry;
933 DEVICE_OBJECT *device;
936 static int root_pnp_devices_rb_compare( const void *key, const struct wine_rb_entry *entry )
938 const struct root_pnp_device *device = WINE_RB_ENTRY_VALUE( entry, const struct root_pnp_device, entry );
939 const WCHAR *k = key;
941 return wcsicmp( k, device->id );
944 static struct wine_rb_tree root_pnp_devices = { root_pnp_devices_rb_compare };
946 static NTSTATUS WINAPI pnp_manager_device_pnp( DEVICE_OBJECT *device, IRP *irp )
948 IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation( irp );
949 struct root_pnp_device *root_device = device->DeviceExtension;
950 NTSTATUS status;
952 TRACE("device %p, irp %p, minor function %#x.\n", device, irp, stack->MinorFunction);
954 switch (stack->MinorFunction)
956 case IRP_MN_QUERY_DEVICE_RELATIONS:
957 /* The FDO above already handled this, so return the same status. */
958 break;
959 case IRP_MN_START_DEVICE:
960 case IRP_MN_SURPRISE_REMOVAL:
961 case IRP_MN_REMOVE_DEVICE:
962 /* Nothing to do. */
963 irp->IoStatus.u.Status = STATUS_SUCCESS;
964 break;
965 case IRP_MN_QUERY_CAPABILITIES:
966 irp->IoStatus.u.Status = STATUS_SUCCESS;
967 break;
968 case IRP_MN_QUERY_ID:
970 BUS_QUERY_ID_TYPE type = stack->Parameters.QueryId.IdType;
971 WCHAR *id, *p;
973 TRACE("Received IRP_MN_QUERY_ID, type %#x.\n", type);
975 switch (type)
977 case BusQueryDeviceID:
978 p = wcsrchr( root_device->id, '\\' );
979 if ((id = ExAllocatePool( NonPagedPool, (p - root_device->id + 1) * sizeof(WCHAR) )))
981 memcpy( id, root_device->id, (p - root_device->id) * sizeof(WCHAR) );
982 id[p - root_device->id] = 0;
983 irp->IoStatus.Information = (ULONG_PTR)id;
984 irp->IoStatus.u.Status = STATUS_SUCCESS;
986 else
988 irp->IoStatus.Information = 0;
989 irp->IoStatus.u.Status = STATUS_NO_MEMORY;
991 break;
992 case BusQueryInstanceID:
993 p = wcsrchr( root_device->id, '\\' );
994 if ((id = ExAllocatePool( NonPagedPool, (wcslen( p + 1 ) + 1) * sizeof(WCHAR) )))
996 wcscpy( id, p + 1 );
997 irp->IoStatus.Information = (ULONG_PTR)id;
998 irp->IoStatus.u.Status = STATUS_SUCCESS;
1000 else
1002 irp->IoStatus.Information = 0;
1003 irp->IoStatus.u.Status = STATUS_NO_MEMORY;
1005 break;
1006 default:
1007 FIXME("Unhandled IRP_MN_QUERY_ID type %#x.\n", type);
1009 break;
1011 default:
1012 FIXME("Unhandled PnP request %#x.\n", stack->MinorFunction);
1015 status = irp->IoStatus.u.Status;
1016 IoCompleteRequest( irp, IO_NO_INCREMENT );
1017 return status;
1020 static NTSTATUS WINAPI pnp_manager_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *keypath )
1022 pnp_manager = driver;
1023 driver->MajorFunction[IRP_MJ_PNP] = pnp_manager_device_pnp;
1024 return STATUS_SUCCESS;
1027 void pnp_manager_start(void)
1029 static const WCHAR driver_nameW[] = {'\\','D','r','i','v','e','r','\\','P','n','p','M','a','n','a','g','e','r',0};
1030 WCHAR endpoint[] = L"\\pipe\\wine_plugplay";
1031 WCHAR protseq[] = L"ncalrpc";
1032 UNICODE_STRING driver_nameU;
1033 RPC_WSTR binding_str;
1034 NTSTATUS status;
1035 RPC_STATUS err;
1037 RtlInitUnicodeString( &driver_nameU, driver_nameW );
1038 if ((status = IoCreateDriver( &driver_nameU, pnp_manager_driver_entry )))
1039 ERR("Failed to create PnP manager driver, status %#x.\n", status);
1041 if ((err = RpcStringBindingComposeW( NULL, protseq, NULL, endpoint, NULL, &binding_str )))
1043 ERR("RpcStringBindingCompose() failed, error %#x\n", err);
1044 return;
1046 err = RpcBindingFromStringBindingW( binding_str, &plugplay_binding_handle );
1047 RpcStringFreeW( &binding_str );
1048 if (err)
1049 ERR("RpcBindingFromStringBinding() failed, error %#x\n", err);
1052 static void destroy_root_pnp_device( struct wine_rb_entry *entry, void *context )
1054 struct root_pnp_device *device = WINE_RB_ENTRY_VALUE(entry, struct root_pnp_device, entry);
1055 remove_device( device->device );
1058 void pnp_manager_stop(void)
1060 wine_rb_destroy( &root_pnp_devices, destroy_root_pnp_device, NULL );
1061 IoDeleteDriver( pnp_manager );
1062 RpcBindingFree( &plugplay_binding_handle );
1065 void pnp_manager_enumerate_root_devices( const WCHAR *driver_name )
1067 static const WCHAR driverW[] = {'\\','D','r','i','v','e','r','\\',0};
1068 static const WCHAR rootW[] = {'R','O','O','T',0};
1069 WCHAR buffer[MAX_SERVICE_NAME + ARRAY_SIZE(driverW)], id[MAX_DEVICE_ID_LEN];
1070 SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
1071 struct root_pnp_device *pnp_device;
1072 DEVICE_OBJECT *device;
1073 NTSTATUS status;
1074 unsigned int i;
1075 HDEVINFO set;
1077 TRACE("Searching for new root-enumerated devices for driver %s.\n", debugstr_w(driver_name));
1079 set = SetupDiGetClassDevsW( NULL, rootW, NULL, DIGCF_ALLCLASSES );
1080 if (set == INVALID_HANDLE_VALUE)
1082 ERR("Failed to build device set, error %#x.\n", GetLastError());
1083 return;
1086 for (i = 0; SetupDiEnumDeviceInfo( set, i, &sp_device ); ++i)
1088 if (!SetupDiGetDeviceRegistryPropertyW( set, &sp_device, SPDRP_SERVICE,
1089 NULL, (BYTE *)buffer, sizeof(buffer), NULL )
1090 || lstrcmpiW( buffer, driver_name ))
1092 continue;
1095 SetupDiGetDeviceInstanceIdW( set, &sp_device, id, ARRAY_SIZE(id), NULL );
1097 if (wine_rb_get( &root_pnp_devices, id ))
1098 continue;
1100 TRACE("Adding new root-enumerated device %s.\n", debugstr_w(id));
1102 if ((status = IoCreateDevice( pnp_manager, sizeof(struct root_pnp_device), NULL,
1103 FILE_DEVICE_CONTROLLER, FILE_AUTOGENERATED_DEVICE_NAME, FALSE, &device )))
1105 ERR("Failed to create root-enumerated PnP device %s, status %#x.\n", debugstr_w(id), status);
1106 continue;
1109 pnp_device = device->DeviceExtension;
1110 wcscpy( pnp_device->id, id );
1111 pnp_device->device = device;
1112 if (wine_rb_put( &root_pnp_devices, id, &pnp_device->entry ))
1114 ERR("Failed to insert device %s into tree.\n", debugstr_w(id));
1115 IoDeleteDevice( device );
1116 continue;
1119 start_device( device, set, &sp_device );
1122 SetupDiDestroyDeviceInfoList(set);