pnp.c 35.4 KB
Newer Older
1 2 3 4 5
/*
 * Plug and Play
 *
 * Copyright 2016 Sebastian Lackner
 * Copyright 2016 Aric Stewart for CodeWeavers
6
 * Copyright 2019 Zebediah Figura
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include <stdarg.h>

#define NONAMELESSUNION

#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winbase.h"
#include "winioctl.h"
#include "winreg.h"
#include "winuser.h"
#include "winsvc.h"
#include "winternl.h"
#include "setupapi.h"
#include "cfgmgr32.h"
#include "dbt.h"
#include "ddk/wdm.h"
#include "ddk/ntifs.h"
#include "wine/debug.h"
42
#include "wine/exception.h"
43 44 45 46
#include "wine/heap.h"
#include "wine/rbtree.h"

#include "ntoskrnl_private.h"
47
#include "plugplay.h"
48

49 50 51
#include "initguid.h"
DEFINE_GUID(GUID_NULL,0,0,0,0,0,0,0,0,0,0,0);

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
WINE_DEFAULT_DEBUG_CHANNEL(plugplay);

#define MAX_SERVICE_NAME 260

struct device_interface
{
    struct wine_rb_entry entry;

    UNICODE_STRING symbolic_link;
    DEVICE_OBJECT *device;
    GUID interface_class;
    BOOL enabled;
};

static int interface_rb_compare( const void *key, const struct wine_rb_entry *entry)
{
    const struct device_interface *iface = WINE_RB_ENTRY_VALUE( entry, const struct device_interface, entry );
    const UNICODE_STRING *k = key;

    return RtlCompareUnicodeString( k, &iface->symbolic_link, FALSE );
}

static struct wine_rb_tree device_interfaces = { interface_rb_compare };

static NTSTATUS get_device_id( DEVICE_OBJECT *device, BUS_QUERY_ID_TYPE type, WCHAR **id )
{
    IO_STACK_LOCATION *irpsp;
    IO_STATUS_BLOCK irp_status;
80
    KEVENT event;
81 82
    IRP *irp;

83 84
    device = IoGetAttachedDevice( device );

85 86
    KeInitializeEvent( &event, NotificationEvent, FALSE );
    if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_PNP, device, NULL, 0, NULL, &event, &irp_status )))
87 88 89 90 91 92
        return STATUS_NO_MEMORY;

    irpsp = IoGetNextIrpStackLocation( irp );
    irpsp->MinorFunction = IRP_MN_QUERY_ID;
    irpsp->Parameters.QueryId.IdType = type;

93 94 95 96
    irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
    if (IoCallDriver( device, irp ) == STATUS_PENDING)
        KeWaitForSingleObject( &event, Executive, KernelMode, FALSE, NULL );

97 98
    *id = (WCHAR *)irp_status.Information;
    return irp_status.u.Status;
99 100 101 102 103 104
}

static NTSTATUS send_pnp_irp( DEVICE_OBJECT *device, UCHAR minor )
{
    IO_STACK_LOCATION *irpsp;
    IO_STATUS_BLOCK irp_status;
105
    KEVENT event;
106 107
    IRP *irp;

108 109
    device = IoGetAttachedDevice( device );

110
    KeInitializeEvent( &event, NotificationEvent, FALSE );
111 112 113 114 115 116 117 118 119
    if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_PNP, device, NULL, 0, NULL, NULL, &irp_status )))
        return STATUS_NO_MEMORY;

    irpsp = IoGetNextIrpStackLocation( irp );
    irpsp->MinorFunction = minor;

    irpsp->Parameters.StartDevice.AllocatedResources = NULL;
    irpsp->Parameters.StartDevice.AllocatedResourcesTranslated = NULL;

120 121 122 123
    irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
    if (IoCallDriver( device, irp ) == STATUS_PENDING)
        KeWaitForSingleObject( &event, Executive, KernelMode, FALSE, NULL );

124
    return irp_status.u.Status;
125 126
}

127 128 129 130 131 132 133 134 135 136 137 138
static NTSTATUS get_device_instance_id( DEVICE_OBJECT *device, WCHAR *buffer )
{
    static const WCHAR backslashW[] = {'\\',0};
    NTSTATUS status;
    WCHAR *id;

    if ((status = get_device_id( device, BusQueryDeviceID, &id )))
    {
        ERR("Failed to get device ID, status %#x.\n", status);
        return status;
    }

139
    lstrcpyW( buffer, id );
140 141 142 143 144 145 146 147
    ExFreePool( id );

    if ((status = get_device_id( device, BusQueryInstanceID, &id )))
    {
        ERR("Failed to get instance ID, status %#x.\n", status);
        return status;
    }

148 149
    lstrcatW( buffer, backslashW );
    lstrcatW( buffer, id );
150 151 152 153 154 155 156
    ExFreePool( id );

    TRACE("Returning ID %s.\n", debugstr_w(buffer));

    return STATUS_SUCCESS;
}

157
static void send_power_irp( DEVICE_OBJECT *device, DEVICE_POWER_STATE power )
158 159 160
{
    IO_STATUS_BLOCK irp_status;
    IO_STACK_LOCATION *irpsp;
161
    KEVENT event;
162 163
    IRP *irp;

164 165
    device = IoGetAttachedDevice( device );

166 167 168
    KeInitializeEvent( &event, NotificationEvent, FALSE );
    if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_POWER, device, NULL, 0, NULL, &event, &irp_status )))
        return;
169 170 171 172 173 174 175

    irpsp = IoGetNextIrpStackLocation( irp );
    irpsp->MinorFunction = IRP_MN_SET_POWER;

    irpsp->Parameters.Power.Type = DevicePowerState;
    irpsp->Parameters.Power.State.DeviceState = power;

176 177 178
    irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
    if (IoCallDriver( device, irp ) == STATUS_PENDING)
        KeWaitForSingleObject( &event, Executive, KernelMode, FALSE, NULL );
179 180
}

181
static void load_function_driver( DEVICE_OBJECT *device, HDEVINFO set, SP_DEVINFO_DATA *sp_device )
182 183 184 185 186 187 188 189
{
    static const WCHAR driverW[] = {'\\','D','r','i','v','e','r','\\',0};
    WCHAR buffer[MAX_SERVICE_NAME + ARRAY_SIZE(servicesW)];
    WCHAR driver[MAX_SERVICE_NAME] = {0};
    DRIVER_OBJECT *driver_obj;
    UNICODE_STRING string;
    NTSTATUS status;

190 191
    if (!SetupDiGetDeviceRegistryPropertyW( set, sp_device, SPDRP_SERVICE,
            NULL, (BYTE *)driver, sizeof(driver), NULL ))
192
    {
193
        WARN("No driver registered for device %p.\n", device);
194 195 196
        return;
    }

197 198
    lstrcpyW( buffer, servicesW );
    lstrcatW( buffer, driver );
199 200 201 202 203 204 205 206
    RtlInitUnicodeString( &string, buffer );
    status = ZwLoadDriver( &string );
    if (status != STATUS_SUCCESS && status != STATUS_IMAGE_ALREADY_LOADED)
    {
        ERR("Failed to load driver %s, status %#x.\n", debugstr_w(driver), status);
        return;
    }

207 208
    lstrcpyW( buffer, driverW );
    lstrcatW( buffer, driver );
209 210 211 212 213 214 215 216
    RtlInitUnicodeString( &string, buffer );
    if (ObReferenceObjectByName( &string, OBJ_CASE_INSENSITIVE, NULL,
                                 0, NULL, KernelMode, NULL, (void **)&driver_obj ) != STATUS_SUCCESS)
    {
        ERR("Failed to locate loaded driver %s.\n", debugstr_w(driver));
        return;
    }

217
    TRACE("Calling AddDevice routine %p.\n", driver_obj->DriverExtension->AddDevice);
218 219 220 221
    if (driver_obj->DriverExtension->AddDevice)
        status = driver_obj->DriverExtension->AddDevice( driver_obj, device );
    else
        status = STATUS_NOT_IMPLEMENTED;
222
    TRACE("AddDevice routine %p returned %#x.\n", driver_obj->DriverExtension->AddDevice, status);
223 224 225 226 227

    ObDereferenceObject( driver_obj );

    if (status != STATUS_SUCCESS)
        ERR("AddDevice failed for driver %s, status %#x.\n", debugstr_w(driver), status);
228 229 230 231 232 233 234
}

/* Return the total number of characters in a REG_MULTI_SZ string, including
 * the final terminating null. */
static size_t sizeof_multiszW( const WCHAR *str )
{
    const WCHAR *p;
235
    for (p = str; *p; p += lstrlenW(p) + 1);
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    return p + 1 - str;
}

/* This does almost the same thing as UpdateDriverForPlugAndPlayDevices(),
 * except that we don't know the INF path beforehand. */
static BOOL install_device_driver( DEVICE_OBJECT *device, HDEVINFO set, SP_DEVINFO_DATA *sp_device )
{
    static const DWORD dif_list[] =
    {
        DIF_REGISTERDEVICE,
        DIF_SELECTBESTCOMPATDRV,
        DIF_ALLOW_INSTALL,
        DIF_INSTALLDEVICEFILES,
        DIF_REGISTER_COINSTALLERS,
        DIF_INSTALLINTERFACES,
        DIF_INSTALLDEVICE,
        DIF_NEWDEVICEWIZARD_FINISHINSTALL,
    };

    NTSTATUS status;
    unsigned int i;
    WCHAR *ids;

    if ((status = get_device_id( device, BusQueryHardwareIDs, &ids )) || !ids)
    {
        ERR("Failed to get hardware IDs, status %#x.\n", status);
        return FALSE;
    }

    SetupDiSetDeviceRegistryPropertyW( set, sp_device, SPDRP_HARDWAREID, (BYTE *)ids,
            sizeof_multiszW( ids ) * sizeof(WCHAR) );
    ExFreePool( ids );

    if ((status = get_device_id( device, BusQueryCompatibleIDs, &ids )) || !ids)
    {
        ERR("Failed to get compatible IDs, status %#x.\n", status);
        return FALSE;
    }

    SetupDiSetDeviceRegistryPropertyW( set, sp_device, SPDRP_COMPATIBLEIDS, (BYTE *)ids,
            sizeof_multiszW( ids ) * sizeof(WCHAR) );
    ExFreePool( ids );

    if (!SetupDiBuildDriverInfoList( set, sp_device, SPDIT_COMPATDRIVER ))
    {
        ERR("Failed to build compatible driver list, error %#x.\n", GetLastError());
        return FALSE;
    }

    for (i = 0; i < ARRAY_SIZE(dif_list); ++i)
    {
        if (!SetupDiCallClassInstaller(dif_list[i], set, sp_device) && GetLastError() != ERROR_DI_DO_DEFAULT)
        {
289
            WARN("Install function %#x failed, error %#x.\n", dif_list[i], GetLastError());
290 291 292 293 294 295 296
            return FALSE;
        }
    }

    return TRUE;
}

297 298 299 300 301 302 303 304 305 306 307 308
/* Load the function driver for a newly created PDO, if one is present, and
 * send IRPs to start the device. */
static void start_device( DEVICE_OBJECT *device, HDEVINFO set, SP_DEVINFO_DATA *sp_device )
{
    load_function_driver( device, set, sp_device );
    if (device->DriverObject)
    {
        send_pnp_irp( device, IRP_MN_START_DEVICE );
        send_power_irp( device, PowerDeviceD0 );
    }
}

309
static void enumerate_new_device( DEVICE_OBJECT *device, HDEVINFO set )
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
{
    static const WCHAR infpathW[] = {'I','n','f','P','a','t','h',0};

    SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
    WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
    BOOL need_driver = TRUE;
    HKEY key;

    if (get_device_instance_id( device, device_instance_id ))
        return;

    if (!SetupDiCreateDeviceInfoW( set, device_instance_id, &GUID_NULL, NULL, NULL, 0, &sp_device )
            && !SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device ))
    {
        ERR("Failed to create or open device %s, error %#x.\n", debugstr_w(device_instance_id), GetLastError());
325 326 327
        return;
    }

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    TRACE("Creating new device %s.\n", debugstr_w(device_instance_id));

    /* Check if the device already has a driver registered; if not, find one
     * and install it. */
    key = SetupDiOpenDevRegKey( set, &sp_device, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_READ );
    if (key != INVALID_HANDLE_VALUE)
    {
        if (!RegQueryValueExW( key, infpathW, NULL, NULL, NULL, NULL ))
            need_driver = FALSE;
        RegCloseKey( key );
    }

    if (need_driver && !install_device_driver( device, set, &sp_device ))
        return;

343
    start_device( device, set, &sp_device );
344 345
}

346
static void remove_device( DEVICE_OBJECT *device )
347
{
348 349
    struct wine_device *wine_device = CONTAINING_RECORD(device, struct wine_device, device_obj);

350
    TRACE("Removing device %p.\n", device);
351

352 353 354 355 356 357 358
    if (wine_device->children)
    {
        ULONG i;
        for (i = 0; i < wine_device->children->Count; ++i)
            remove_device( wine_device->children->Objects[i] );
    }

359 360 361 362 363
    send_power_irp( device, PowerDeviceD3 );
    send_pnp_irp( device, IRP_MN_SURPRISE_REMOVAL );
    send_pnp_irp( device, IRP_MN_REMOVE_DEVICE );
}

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
static BOOL device_in_list( const DEVICE_RELATIONS *list, const DEVICE_OBJECT *device )
{
    ULONG i;
    for (i = 0; i < list->Count; ++i)
    {
        if (list->Objects[i] == device)
            return TRUE;
    }
    return FALSE;
}

static void handle_bus_relations( DEVICE_OBJECT *parent )
{
    struct wine_device *wine_parent = CONTAINING_RECORD(parent, struct wine_device, device_obj);
    SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
    DEVICE_RELATIONS *relations;
    IO_STATUS_BLOCK irp_status;
    IO_STACK_LOCATION *irpsp;
    HDEVINFO set;
383
    KEVENT event;
384 385 386 387 388 389 390 391 392
    IRP *irp;
    ULONG i;

    TRACE( "(%p)\n", parent );

    set = SetupDiCreateDeviceInfoList( NULL, NULL );

    parent = IoGetAttachedDevice( parent );

393 394
    KeInitializeEvent( &event, NotificationEvent, FALSE );
    if (!(irp = IoBuildSynchronousFsdRequest( IRP_MJ_PNP, parent, NULL, 0, NULL, &event, &irp_status )))
395 396 397 398 399 400 401 402
    {
        SetupDiDestroyDeviceInfoList( set );
        return;
    }

    irpsp = IoGetNextIrpStackLocation( irp );
    irpsp->MinorFunction = IRP_MN_QUERY_DEVICE_RELATIONS;
    irpsp->Parameters.QueryDeviceRelations.Type = BusRelations;
403 404 405 406 407

    irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
    if (IoCallDriver( parent, irp ) == STATUS_PENDING)
        KeWaitForSingleObject( &event, Executive, KernelMode, FALSE, NULL );

408 409
    relations = (DEVICE_RELATIONS *)irp_status.Information;
    if (irp_status.u.Status)
410
    {
411
        ERR("Failed to enumerate child devices, status %#x.\n", irp_status.u.Status);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        SetupDiDestroyDeviceInfoList( set );
        return;
    }

    TRACE("Got %u devices.\n", relations->Count);

    for (i = 0; i < relations->Count; ++i)
    {
        DEVICE_OBJECT *child = relations->Objects[i];

        if (!wine_parent->children || !device_in_list( wine_parent->children, child ))
        {
            TRACE("Adding new device %p.\n", child);
            enumerate_new_device( child, set );
        }
    }

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    if (wine_parent->children)
    {
        for (i = 0; i < wine_parent->children->Count; ++i)
        {
            DEVICE_OBJECT *child = wine_parent->children->Objects[i];

            if (!device_in_list( relations, child ))
            {
                TRACE("Removing device %p.\n", child);
                remove_device( child );
            }
            ObDereferenceObject( child );
        }
    }

444 445 446 447 448 449
    ExFreePool( wine_parent->children );
    wine_parent->children = relations;

    SetupDiDestroyDeviceInfoList( set );
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
/***********************************************************************
 *           IoInvalidateDeviceRelations (NTOSKRNL.EXE.@)
 */
void WINAPI IoInvalidateDeviceRelations( DEVICE_OBJECT *device_object, DEVICE_RELATION_TYPE type )
{
    TRACE("device %p, type %#x.\n", device_object, type);

    switch (type)
    {
        case BusRelations:
            handle_bus_relations( device_object );
            break;
        default:
            FIXME("Unhandled relation %#x.\n", type);
            break;
    }
}

/***********************************************************************
 *           IoGetDeviceProperty   (NTOSKRNL.EXE.@)
 */
NTSTATUS WINAPI IoGetDeviceProperty( DEVICE_OBJECT *device, DEVICE_REGISTRY_PROPERTY property,
                                     ULONG length, void *buffer, ULONG *needed )
{
474 475 476 477 478 479
    SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
    WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
    DWORD sp_property = -1;
    NTSTATUS status;
    HDEVINFO set;

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    TRACE("device %p, property %u, length %u, buffer %p, needed %p.\n",
            device, property, length, buffer, needed);

    switch (property)
    {
        case DevicePropertyEnumeratorName:
        {
            WCHAR *id, *ptr;

            status = get_device_id( device, BusQueryInstanceID, &id );
            if (status != STATUS_SUCCESS)
            {
                ERR("Failed to get instance ID, status %#x.\n", status);
                break;
            }

496 497
            wcsupr( id );
            ptr = wcschr( id, '\\' );
498 499
            if (ptr) *ptr = 0;

500
            *needed = sizeof(WCHAR) * (lstrlenW(id) + 1);
501 502 503 504 505
            if (length >= *needed)
                memcpy( buffer, id, *needed );
            else
                status = STATUS_BUFFER_TOO_SMALL;

506
            ExFreePool( id );
507
            return status;
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        }
        case DevicePropertyPhysicalDeviceObjectName:
        {
            ULONG used_len, len = length + sizeof(OBJECT_NAME_INFORMATION);
            OBJECT_NAME_INFORMATION *name = HeapAlloc(GetProcessHeap(), 0, len);
            HANDLE handle;

            status = ObOpenObjectByPointer( device, OBJ_KERNEL_HANDLE, NULL, 0, NULL, KernelMode, &handle );
            if (!status)
            {
                status = NtQueryObject( handle, ObjectNameInformation, name, len, &used_len );
                NtClose( handle );
            }
            if (status == STATUS_SUCCESS)
            {
                /* Ensure room for NULL termination */
                if (length >= name->Name.MaximumLength)
                    memcpy(buffer, name->Name.Buffer, name->Name.MaximumLength);
                else
                    status = STATUS_BUFFER_TOO_SMALL;
                *needed = name->Name.MaximumLength;
            }
            else
            {
                if (status == STATUS_INFO_LENGTH_MISMATCH ||
                    status == STATUS_BUFFER_OVERFLOW)
                {
                    status = STATUS_BUFFER_TOO_SMALL;
                    *needed = used_len - sizeof(OBJECT_NAME_INFORMATION);
                }
                else
                    *needed = 0;
            }
            HeapFree(GetProcessHeap(), 0, name);
542
            return status;
543
        }
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
        case DevicePropertyDeviceDescription:
            sp_property = SPDRP_DEVICEDESC;
            break;
        case DevicePropertyHardwareID:
            sp_property = SPDRP_HARDWAREID;
            break;
        case DevicePropertyCompatibleIDs:
            sp_property = SPDRP_COMPATIBLEIDS;
            break;
        case DevicePropertyClassName:
            sp_property = SPDRP_CLASS;
            break;
        case DevicePropertyClassGuid:
            sp_property = SPDRP_CLASSGUID;
            break;
        case DevicePropertyManufacturer:
            sp_property = SPDRP_MFG;
            break;
        case DevicePropertyFriendlyName:
            sp_property = SPDRP_FRIENDLYNAME;
            break;
        case DevicePropertyLocationInformation:
            sp_property = SPDRP_LOCATION_INFORMATION;
            break;
        case DevicePropertyBusTypeGuid:
            sp_property = SPDRP_BUSTYPEGUID;
            break;
        case DevicePropertyLegacyBusType:
            sp_property = SPDRP_LEGACYBUSTYPE;
            break;
        case DevicePropertyBusNumber:
            sp_property = SPDRP_BUSNUMBER;
            break;
        case DevicePropertyAddress:
            sp_property = SPDRP_ADDRESS;
            break;
        case DevicePropertyUINumber:
            sp_property = SPDRP_UI_NUMBER;
            break;
        case DevicePropertyInstallState:
            sp_property = SPDRP_INSTALL_STATE;
            break;
        case DevicePropertyRemovalPolicy:
            sp_property = SPDRP_REMOVAL_POLICY;
            break;
589 590
        default:
            FIXME("Unhandled property %u.\n", property);
591 592 593 594 595 596 597 598 599 600
            return STATUS_NOT_IMPLEMENTED;
    }

    if ((status = get_device_instance_id( device, device_instance_id )))
        return status;

    if ((set = SetupDiCreateDeviceInfoList( &GUID_NULL, NULL )) == INVALID_HANDLE_VALUE)
    {
        ERR("Failed to create device list, error %#x.\n", GetLastError());
        return GetLastError();
601
    }
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616

    if (!SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device))
    {
        ERR("Failed to open device, error %#x.\n", GetLastError());
        SetupDiDestroyDeviceInfoList( set );
        return GetLastError();
    }

    if (SetupDiGetDeviceRegistryPropertyW( set, &sp_device, sp_property, NULL, buffer, length, needed ))
        status = STATUS_SUCCESS;
    else
        status = GetLastError();

    SetupDiDestroyDeviceInfoList( set );

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    return status;
}

static NTSTATUS create_device_symlink( DEVICE_OBJECT *device, UNICODE_STRING *symlink_name )
{
    UNICODE_STRING device_nameU;
    WCHAR *device_name;
    ULONG len = 0;
    NTSTATUS ret;

    ret = IoGetDeviceProperty( device, DevicePropertyPhysicalDeviceObjectName, 0, NULL, &len );
    if (ret != STATUS_BUFFER_TOO_SMALL)
        return ret;

    device_name = heap_alloc( len );
    ret = IoGetDeviceProperty( device, DevicePropertyPhysicalDeviceObjectName, len, device_name, &len );
    if (ret)
    {
        heap_free( device_name );
        return ret;
    }

    RtlInitUnicodeString( &device_nameU, device_name );
    ret = IoCreateSymbolicLink( symlink_name, &device_nameU );
    heap_free( device_name );
    return ret;
}

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
void  __RPC_FAR * __RPC_USER MIDL_user_allocate( SIZE_T len )
{
    return heap_alloc( len );
}

void __RPC_USER MIDL_user_free( void __RPC_FAR *ptr )
{
    heap_free( ptr );
}

static LONG WINAPI rpc_filter( EXCEPTION_POINTERS *eptr )
{
    return I_RpcExceptionFilter( eptr->ExceptionRecord->ExceptionCode );
}

static void send_devicechange( DWORD code, void *data, unsigned int size )
{
    __TRY
    {
        plugplay_send_event( code, data, size );
    }
    __EXCEPT(rpc_filter)
    {
        WARN("Failed to send event, exception %#x.\n", GetExceptionCode());
    }
    __ENDTRY
}

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
/***********************************************************************
 *           IoSetDeviceInterfaceState   (NTOSKRNL.EXE.@)
 */
NTSTATUS WINAPI IoSetDeviceInterfaceState( UNICODE_STRING *name, BOOLEAN enable )
{
    static const WCHAR DeviceClassesW[] = {'\\','R','E','G','I','S','T','R','Y','\\',
        'M','a','c','h','i','n','e','\\','S','y','s','t','e','m','\\',
        'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
        'C','o','n','t','r','o','l','\\',
        'D','e','v','i','c','e','C','l','a','s','s','e','s','\\',0};
    static const WCHAR controlW[] = {'C','o','n','t','r','o','l',0};
    static const WCHAR linkedW[] = {'L','i','n','k','e','d',0};
    static const WCHAR slashW[] = {'\\',0};
    static const WCHAR hashW[] = {'#',0};

    size_t namelen = name->Length / sizeof(WCHAR);
    DEV_BROADCAST_DEVICEINTERFACE_W *broadcast;
    struct device_interface *iface;
    HANDLE iface_key, control_key;
    OBJECT_ATTRIBUTES attr = {0};
    struct wine_rb_entry *entry;
    WCHAR *path, *refstr, *p;
    UNICODE_STRING string;
    DWORD data = enable;
    NTSTATUS ret;
    ULONG len;

    TRACE("device %s, enable %u.\n", debugstr_us(name), enable);

    entry = wine_rb_get( &device_interfaces, name );
    if (!entry)
        return STATUS_OBJECT_NAME_NOT_FOUND;

    iface = WINE_RB_ENTRY_VALUE( entry, struct device_interface, entry );

    if (!enable && !iface->enabled)
        return STATUS_OBJECT_NAME_NOT_FOUND;

    if (enable && iface->enabled)
        return STATUS_OBJECT_NAME_EXISTS;

714 715 716
    for (p = name->Buffer + 4, refstr = NULL; p < name->Buffer + namelen; p++)
        if (*p == '\\') refstr = p;
    if (!refstr) refstr = p;
717

718
    len = lstrlenW(DeviceClassesW) + 38 + 1 + namelen + 2 + 1;
719 720 721 722

    if (!(path = heap_alloc( len * sizeof(WCHAR) )))
        return STATUS_NO_MEMORY;

723 724 725 726 727
    lstrcpyW( path, DeviceClassesW );
    lstrcpynW( path + lstrlenW( path ), refstr - 38, 39 );
    lstrcatW( path, slashW );
    p = path + lstrlenW( path );
    lstrcpynW( path + lstrlenW( path ), name->Buffer, (refstr - name->Buffer) + 1 );
728
    p[0] = p[1] = p[3] = '#';
729 730 731 732
    lstrcatW( path, slashW );
    lstrcatW( path, hashW );
    if (refstr < name->Buffer + namelen)
        lstrcpynW( path + lstrlenW( path ), refstr, name->Buffer + namelen - refstr + 1 );
733 734 735 736 737 738 739 740 741 742 743

    attr.Length = sizeof(attr);
    attr.ObjectName = &string;
    RtlInitUnicodeString( &string, path );
    ret = NtOpenKey( &iface_key, KEY_CREATE_SUB_KEY, &attr );
    heap_free(path);
    if (ret)
        return ret;

    attr.RootDirectory = iface_key;
    RtlInitUnicodeString( &string, controlW );
744
    ret = NtCreateKey( &control_key, KEY_SET_VALUE, &attr, 0, NULL, REG_OPTION_VOLATILE, NULL );
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    NtClose( iface_key );
    if (ret)
        return ret;

    RtlInitUnicodeString( &string, linkedW );
    ret = NtSetValueKey( control_key, &string, 0, REG_DWORD, &data, sizeof(data) );
    if (ret)
    {
        NtClose( control_key );
        return ret;
    }

    if (enable)
        ret = create_device_symlink( iface->device, name );
    else
        ret = IoDeleteSymbolicLink( name );
    if (ret)
    {
        NtDeleteValueKey( control_key, &string );
        NtClose( control_key );
        return ret;
    }

    iface->enabled = enable;

    len = offsetof(DEV_BROADCAST_DEVICEINTERFACE_W, dbcc_name[namelen + 1]);

    if ((broadcast = heap_alloc( len )))
    {
774
        broadcast->dbcc_size       = len;
775
        broadcast->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
776 777
        broadcast->dbcc_reserved   = 0;
        broadcast->dbcc_classguid  = iface->interface_class;
778
        lstrcpynW( broadcast->dbcc_name, name->Buffer, namelen + 1 );
779
        send_devicechange( enable ? DBT_DEVICEARRIVAL : DBT_DEVICEREMOVECOMPLETE, broadcast, len );
780 781 782 783 784 785 786 787 788
        heap_free( broadcast );
    }
    return ret;
}

/***********************************************************************
 *           IoRegisterDeviceInterface (NTOSKRNL.EXE.@)
 */
NTSTATUS WINAPI IoRegisterDeviceInterface(DEVICE_OBJECT *device, const GUID *class_guid,
789
        UNICODE_STRING *refstr, UNICODE_STRING *symbolic_link)
790 791 792
{
    SP_DEVICE_INTERFACE_DATA sp_iface = {sizeof(sp_iface)};
    SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
793
    WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
794 795
    SP_DEVICE_INTERFACE_DETAIL_DATA_W *data;
    NTSTATUS status = STATUS_SUCCESS;
796
    UNICODE_STRING device_path;
797
    struct device_interface *iface;
798
    struct wine_rb_entry *entry;
799 800 801
    DWORD required;
    HDEVINFO set;

802 803
    TRACE("device %p, class_guid %s, refstr %s, symbolic_link %p.\n",
            device, debugstr_guid(class_guid), debugstr_us(refstr), symbolic_link);
804

805 806 807
    if ((status = get_device_instance_id( device, device_instance_id )))
        return status;

808
    set = SetupDiGetClassDevsW( class_guid, NULL, NULL, DIGCF_DEVICEINTERFACE );
809 810
    if (set == INVALID_HANDLE_VALUE) return STATUS_UNSUCCESSFUL;

811 812
    if (!SetupDiCreateDeviceInfoW( set, device_instance_id, class_guid, NULL, NULL, 0, &sp_device )
            && !SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device ))
813
    {
814
        ERR("Failed to create device %s, error %#x.\n", debugstr_w(device_instance_id), GetLastError());
815
        return GetLastError();
816 817
    }

818
    if (!SetupDiCreateDeviceInterfaceW( set, &sp_device, class_guid, refstr ? refstr->Buffer : NULL, 0, &sp_iface ))
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
        return STATUS_UNSUCCESSFUL;

    required = 0;
    SetupDiGetDeviceInterfaceDetailW( set, &sp_iface, NULL, 0, &required, NULL );
    if (required == 0) return STATUS_UNSUCCESSFUL;

    data = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, required );
    data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);

    if (!SetupDiGetDeviceInterfaceDetailW( set, &sp_iface, data, required, NULL, NULL ))
    {
        HeapFree( GetProcessHeap(), 0, data );
        return STATUS_UNSUCCESSFUL;
    }

    data->DevicePath[1] = '?';
    TRACE("Returning path %s.\n", debugstr_w(data->DevicePath));
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    RtlCreateUnicodeString( &device_path, data->DevicePath);

    entry = wine_rb_get( &device_interfaces, &device_path );
    if (entry)
    {
        iface = WINE_RB_ENTRY_VALUE( entry, struct device_interface, entry );
        if (iface->enabled)
            ERR("Device interface %s is still enabled.\n", debugstr_us(&iface->symbolic_link));
    }
    else
    {
        iface = heap_alloc_zero( sizeof(struct device_interface) );
        RtlCreateUnicodeString(&iface->symbolic_link, data->DevicePath);
        if (wine_rb_put( &device_interfaces, &iface->symbolic_link, &iface->entry ))
            ERR("Failed to insert interface %s into tree.\n", debugstr_us(&iface->symbolic_link));
    }
852 853 854 855 856 857 858 859

    iface->device = device;
    iface->interface_class = *class_guid;
    if (symbolic_link)
        RtlCreateUnicodeString( symbolic_link, data->DevicePath);

    HeapFree( GetProcessHeap(), 0, data );

860 861
    RtlFreeUnicodeString( &device_path );

862 863 864
    return status;
}

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
/***********************************************************************
 *           IoOpenDeviceRegistryKey   (NTOSKRNL.EXE.@)
 */
NTSTATUS WINAPI IoOpenDeviceRegistryKey( DEVICE_OBJECT *device, ULONG type, ACCESS_MASK access, HANDLE *key )
{
    SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
    WCHAR device_instance_id[MAX_DEVICE_ID_LEN];
    NTSTATUS status;
    HDEVINFO set;

    TRACE("device %p, type %#x, access %#x, key %p.\n", device, type, access, key);

    if ((status = get_device_instance_id( device, device_instance_id )))
    {
        ERR("Failed to get device instance ID, error %#x.\n", status);
        return status;
    }

    set = SetupDiCreateDeviceInfoList( &GUID_NULL, NULL );

    SetupDiOpenDeviceInfoW( set, device_instance_id, NULL, 0, &sp_device );

    *key = SetupDiOpenDevRegKey( set, &sp_device, DICS_FLAG_GLOBAL, 0, type, access );
    SetupDiDestroyDeviceInfoList( set );
    if (*key == INVALID_HANDLE_VALUE)
        return GetLastError();
    return STATUS_SUCCESS;
}

894 895 896 897 898 899 900 901
/***********************************************************************
 *           PoSetPowerState   (NTOSKRNL.EXE.@)
 */
POWER_STATE WINAPI PoSetPowerState( DEVICE_OBJECT *device, POWER_STATE_TYPE type, POWER_STATE state)
{
    FIXME("device %p, type %u, state %u, stub!\n", device, type, state.DeviceState);
    return state;
}
902

903 904 905 906 907 908 909 910
/*****************************************************
 *           PoStartNextPowerIrp   (NTOSKRNL.EXE.@)
 */
void WINAPI PoStartNextPowerIrp( IRP *irp )
{
    FIXME("irp %p, stub!\n", irp);
}

911 912 913 914 915 916 917 918 919
/*****************************************************
 *           PoCallDriver   (NTOSKRNL.EXE.@)
 */
NTSTATUS WINAPI PoCallDriver( DEVICE_OBJECT *device, IRP *irp )
{
    TRACE("device %p, irp %p.\n", device, irp);
    return IoCallDriver( device, irp );
}

920 921
static DRIVER_OBJECT *pnp_manager;

922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
struct root_pnp_device
{
    WCHAR id[MAX_DEVICE_ID_LEN];
    struct wine_rb_entry entry;
    DEVICE_OBJECT *device;
};

static int root_pnp_devices_rb_compare( const void *key, const struct wine_rb_entry *entry )
{
    const struct root_pnp_device *device = WINE_RB_ENTRY_VALUE( entry, const struct root_pnp_device, entry );
    const WCHAR *k = key;

    return wcsicmp( k, device->id );
}

static struct wine_rb_tree root_pnp_devices = { root_pnp_devices_rb_compare };

939 940 941
static NTSTATUS WINAPI pnp_manager_device_pnp( DEVICE_OBJECT *device, IRP *irp )
{
    IO_STACK_LOCATION *stack = IoGetCurrentIrpStackLocation( irp );
942
    struct root_pnp_device *root_device = device->DeviceExtension;
943
    NTSTATUS status;
944 945 946

    TRACE("device %p, irp %p, minor function %#x.\n", device, irp, stack->MinorFunction);

947 948
    switch (stack->MinorFunction)
    {
949 950 951
    case IRP_MN_QUERY_DEVICE_RELATIONS:
        /* The FDO above already handled this, so return the same status. */
        break;
952 953 954 955 956 957
    case IRP_MN_START_DEVICE:
    case IRP_MN_SURPRISE_REMOVAL:
    case IRP_MN_REMOVE_DEVICE:
        /* Nothing to do. */
        irp->IoStatus.u.Status = STATUS_SUCCESS;
        break;
958 959 960
    case IRP_MN_QUERY_CAPABILITIES:
        irp->IoStatus.u.Status = STATUS_SUCCESS;
        break;
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    case IRP_MN_QUERY_ID:
    {
        BUS_QUERY_ID_TYPE type = stack->Parameters.QueryId.IdType;
        WCHAR *id, *p;

        TRACE("Received IRP_MN_QUERY_ID, type %#x.\n", type);

        switch (type)
        {
        case BusQueryDeviceID:
            p = wcsrchr( root_device->id, '\\' );
            if ((id = ExAllocatePool( NonPagedPool, (p - root_device->id + 1) * sizeof(WCHAR) )))
            {
                memcpy( id, root_device->id, (p - root_device->id) * sizeof(WCHAR) );
                id[p - root_device->id] = 0;
                irp->IoStatus.Information = (ULONG_PTR)id;
                irp->IoStatus.u.Status = STATUS_SUCCESS;
            }
            else
            {
                irp->IoStatus.Information = 0;
                irp->IoStatus.u.Status = STATUS_NO_MEMORY;
            }
            break;
        case BusQueryInstanceID:
            p = wcsrchr( root_device->id, '\\' );
            if ((id = ExAllocatePool( NonPagedPool, (wcslen( p + 1 ) + 1) * sizeof(WCHAR) )))
            {
                wcscpy( id, p + 1 );
                irp->IoStatus.Information = (ULONG_PTR)id;
                irp->IoStatus.u.Status = STATUS_SUCCESS;
            }
            else
            {
                irp->IoStatus.Information = 0;
                irp->IoStatus.u.Status = STATUS_NO_MEMORY;
            }
            break;
        default:
            FIXME("Unhandled IRP_MN_QUERY_ID type %#x.\n", type);
        }
        break;
    }
1004 1005 1006 1007
    default:
        FIXME("Unhandled PnP request %#x.\n", stack->MinorFunction);
    }

1008
    status = irp->IoStatus.u.Status;
1009
    IoCompleteRequest( irp, IO_NO_INCREMENT );
1010
    return status;
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
}

static NTSTATUS WINAPI pnp_manager_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *keypath )
{
    pnp_manager = driver;
    driver->MajorFunction[IRP_MJ_PNP] = pnp_manager_device_pnp;
    return STATUS_SUCCESS;
}

void pnp_manager_start(void)
{
    static const WCHAR driver_nameW[] = {'\\','D','r','i','v','e','r','\\','P','n','p','M','a','n','a','g','e','r',0};
1023 1024
    WCHAR endpoint[] = L"\\pipe\\wine_plugplay";
    WCHAR protseq[] = L"ncalrpc";
1025
    UNICODE_STRING driver_nameU;
1026
    RPC_WSTR binding_str;
1027
    NTSTATUS status;
1028
    RPC_STATUS err;
1029 1030 1031 1032

    RtlInitUnicodeString( &driver_nameU, driver_nameW );
    if ((status = IoCreateDriver( &driver_nameU, pnp_manager_driver_entry )))
        ERR("Failed to create PnP manager driver, status %#x.\n", status);
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

    if ((err = RpcStringBindingComposeW( NULL, protseq, NULL, endpoint, NULL, &binding_str )))
    {
        ERR("RpcStringBindingCompose() failed, error %#x\n", err);
        return;
    }
    err = RpcBindingFromStringBindingW( binding_str, &plugplay_binding_handle );
    RpcStringFreeW( &binding_str );
    if (err)
        ERR("RpcBindingFromStringBinding() failed, error %#x\n", err);
1043 1044
}

1045 1046 1047 1048 1049 1050
static void destroy_root_pnp_device( struct wine_rb_entry *entry, void *context )
{
    struct root_pnp_device *device = WINE_RB_ENTRY_VALUE(entry, struct root_pnp_device, entry);
    remove_device( device->device );
}

1051 1052
void pnp_manager_stop(void)
{
1053
    wine_rb_destroy( &root_pnp_devices, destroy_root_pnp_device, NULL );
1054
    IoDeleteDriver( pnp_manager );
1055
    RpcBindingFree( &plugplay_binding_handle );
1056
}
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

void pnp_manager_enumerate_root_devices( const WCHAR *driver_name )
{
    static const WCHAR driverW[] = {'\\','D','r','i','v','e','r','\\',0};
    static const WCHAR rootW[] = {'R','O','O','T',0};
    WCHAR buffer[MAX_SERVICE_NAME + ARRAY_SIZE(driverW)], id[MAX_DEVICE_ID_LEN];
    SP_DEVINFO_DATA sp_device = {sizeof(sp_device)};
    struct root_pnp_device *pnp_device;
    DEVICE_OBJECT *device;
    NTSTATUS status;
    unsigned int i;
    HDEVINFO set;

    TRACE("Searching for new root-enumerated devices for driver %s.\n", debugstr_w(driver_name));

    set = SetupDiGetClassDevsW( NULL, rootW, NULL, DIGCF_ALLCLASSES );
    if (set == INVALID_HANDLE_VALUE)
    {
        ERR("Failed to build device set, error %#x.\n", GetLastError());
        return;
    }

    for (i = 0; SetupDiEnumDeviceInfo( set, i, &sp_device ); ++i)
    {
        if (!SetupDiGetDeviceRegistryPropertyW( set, &sp_device, SPDRP_SERVICE,
                NULL, (BYTE *)buffer, sizeof(buffer), NULL )
                || lstrcmpiW( buffer, driver_name ))
        {
            continue;
        }

        SetupDiGetDeviceInstanceIdW( set, &sp_device, id, ARRAY_SIZE(id), NULL );

        if (wine_rb_get( &root_pnp_devices, id ))
            continue;

        TRACE("Adding new root-enumerated device %s.\n", debugstr_w(id));

        if ((status = IoCreateDevice( pnp_manager, sizeof(struct root_pnp_device), NULL,
                FILE_DEVICE_CONTROLLER, FILE_AUTOGENERATED_DEVICE_NAME, FALSE, &device )))
        {
            ERR("Failed to create root-enumerated PnP device %s, status %#x.\n", debugstr_w(id), status);
            continue;
        }

        pnp_device = device->DeviceExtension;
        wcscpy( pnp_device->id, id );
        pnp_device->device = device;
        if (wine_rb_put( &root_pnp_devices, id, &pnp_device->entry ))
        {
            ERR("Failed to insert device %s into tree.\n", debugstr_w(id));
            IoDeleteDevice( device );
            continue;
        }

        start_device( device, set, &sp_device );
    }

    SetupDiDestroyDeviceInfoList(set);
}