bulkpwr.c 34.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 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 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 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 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
/*++

Copyright (c) 1997-1998  Microsoft Corporation

Module Name:

    BulkPwr.c

Abstract:

    Bulk USB device driver for Intel 82930 USB test board
    Power Management module


Environment:

    kernel mode only

Notes:

  THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
  PURPOSE.

  Copyright (c) 1997-1998 Microsoft Corporation.  All Rights Reserved.


Revision History:

    2/8/98: created

--*/


#include "wdm.h"
#include "stdarg.h"
#include "stdio.h"

#include "usbdi.h"
#include "usbdlib.h"
#include "Blk82930.h"


NTSTATUS
BulkUsb_ProcessPowerIrp(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP           Irp
    )
/*++

Routine Description:

    This is our FDO's dispatch table function for IRP_MJ_POWER.
    It processes the Power IRPs sent to the PDO for this device.

    For every power IRP, drivers must call PoStartNextPowerIrp and use PoCallDriver
    to pass the IRP all the way down the driver stack to the underlying PDO.


Arguments:

    DeviceObject - pointer to our device object (FDO)

    Irp          - pointer to an I/O Request Packet

Return Value:

    NT status code

--*/
{

    PIO_STACK_LOCATION irpStack;
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PDEVICE_EXTENSION deviceExtension;
    BOOLEAN fGoingToD0 = FALSE;
    POWER_STATE sysPowerState, desiredDevicePowerState;
    KEVENT event;

    BULKUSB_KdPrint( DBGLVL_MEDIUM,(" BulkUsb_ProcessPowerIrp() IRP_MJ_POWER\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    irpStack = IoGetCurrentIrpStackLocation (Irp);
    BulkUsb_IncrementIoCount(DeviceObject);

    switch (irpStack->MinorFunction) {
    case IRP_MN_WAIT_WAKE:
        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Enter IRP_MN_WAIT_WAKE\n"));

                // A driver sends IRP_MN_WAIT_WAKE to indicate that the system should
                // wait for its device to signal a wake event. The exact nature of the event
                // is device-dependent.
                // Drivers send this IRP for two reasons:
                // 1) To allow a device to wake the system
                // 2) To wake a device that has been put into a sleep state to save power
                //    but still must be able to communicate with its driver under certain circumstances.
                // When a wake event occurs, the driver completes the IRP and returns
                // STATUS_SUCCESS. If the device is sleeping when the event occurs,
                // the driver must first wake up the device before completing the IRP.
                // In a completion routine, the driver calls PoRequestPowerIrp to send a
                // PowerDeviceD0 request. When the device has powered up, the driver can
                //  handle the IRP_MN_WAIT_WAKE request.

        // deviceExtension->DeviceCapabilities.DeviceWake specifies the lowest device power state (least powered)
        // from which the device can signal a wake event
        deviceExtension->PowerDownLevel = deviceExtension->DeviceCapabilities.DeviceWake;


        if  ( ( PowerDeviceD0 == deviceExtension->CurrentDevicePowerState )  ||
              ( deviceExtension->DeviceCapabilities.DeviceWake > deviceExtension->CurrentDevicePowerState ) ) {
                        //
                        //    STATUS_INVALID_DEVICE_STATE is returned if the device in the PowerD0 state
                        //    or a state below which it can support waking, or if the SystemWake state
                        //    is below a state which can be supported. A pending IRP_MN_WAIT_WAKE will complete
                        //    with this error if the device's state is changed to be incompatible with the wake
                        //    request.

            //  If a driver fails this IRP, it should complete the IRP immediately without
            //  passing the IRP to the next-lower driver.
            ntStatus = STATUS_INVALID_DEVICE_STATE;
            Irp->IoStatus.Status = ntStatus;
            IoCompleteRequest (Irp,IO_NO_INCREMENT );
            BULKUSB_KdPrint( DBGLVL_HIGH, ( "Exit BulkUsb_ProcessPowerIrp(), ntStatus STATUS_INVALID_DEVICE_STATE\n" ) );
            BulkUsb_DecrementIoCount(DeviceObject);
            return ntStatus;
        }

        // flag we're enabled for wakeup
        deviceExtension->EnabledForWakeup = TRUE;

        // init an event for our completion routine to signal when PDO is done with this Irp
        KeInitializeEvent(&event, NotificationEvent, FALSE);

       // If not failing outright, pass this on to our PDO for further handling
        IoCopyCurrentIrpStackLocationToNext(Irp);

        // Set a completion routine so it can signal our event when
        //  the PDO is done with the Irp
        IoSetCompletionRoutine(Irp,
                               BulkUsb_IrpCompletionRoutine,
                               &event,  // pass the event to the completion routine as the Context
                               TRUE,    // invoke on success
                               TRUE,    // invoke on error
                               TRUE);   // invoke on cancellation

        PoStartNextPowerIrp(Irp);
        ntStatus = PoCallDriver(deviceExtension->TopOfStackDeviceObject,
                                Irp);

         // if PDO is not done yet, wait for the event to be set in our completion routine
        if (ntStatus == STATUS_PENDING) {
             // wait for irp to complete

            NTSTATUS waitStatus = KeWaitForSingleObject(
                &event,
                Suspended,
                KernelMode,
                FALSE,
                NULL);

            BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() done waiting for PDO to finish IRP_MN_WAIT_WAKE\n"));
        }

                // now tell the device to actually wake up
                BulkUsb_SelfSuspendOrActivate( DeviceObject, FALSE );

        // flag we're done with wakeup irp
        deviceExtension->EnabledForWakeup = FALSE;

        BulkUsb_DecrementIoCount(DeviceObject);

        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Exit IRP_MN_WAIT_WAKE\n"));
        break;

    case IRP_MN_SET_POWER:
        {

                // The system power policy manager sends this IRP to set the system power state.
                // A device power policy manager sends this IRP to set the device power state for a device.

        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Enter IRP_MN_SET_POWER\n"));

        // Set Irp->IoStatus.Status to STATUS_SUCCESS to indicate that the device
        // has entered the requested state. Drivers cannot fail this IRP.

        switch (irpStack->Parameters.Power.Type) {
            case SystemPowerState:

                // Get input system power state
                sysPowerState.SystemState = irpStack->Parameters.Power.State.SystemState;

                BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Set Power, type SystemPowerState = %s\n",
                    BULKUSB_StringForSysState( sysPowerState.SystemState ) ));

                // If system is in working state always set our device to D0
                //  regardless of the wait state or system-to-device state power map
                if ( sysPowerState.SystemState ==  PowerSystemWorking) {
                    desiredDevicePowerState.DeviceState = PowerDeviceD0;

                     BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() PowerSystemWorking, will set D0, not use state map\n"));


                } else {
                     // set to corresponding system state if IRP_MN_WAIT_WAKE pending
                    if ( deviceExtension->EnabledForWakeup ) { // got a WAIT_WAKE IRP pending?

                        // Find the device power state equivalent to the given system state.
                        // We get this info from the DEVICE_CAPABILITIES struct in our device
                        // extension (initialized in BulkUsb_PnPAddDevice() )
                        desiredDevicePowerState.DeviceState =
                            deviceExtension->DeviceCapabilities.DeviceState[ sysPowerState.SystemState ];

                        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() IRP_MN_WAIT_WAKE pending, will use state map\n"));

                    } else {
                        // if no wait pending and the system's not in working state, just turn off
                        desiredDevicePowerState.DeviceState = PowerDeviceD3;

                        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Not EnabledForWakeup and the system's not in working state,\n  settting PowerDeviceD3 (off )\n"));
                    }
                }

                //
                // We've determined the desired device state; are we already in this state?
                //

                BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Set Power, desiredDevicePowerState = %s\n",
                    BULKUSB_StringForDevState( desiredDevicePowerState.DeviceState ) ));

                if (desiredDevicePowerState.DeviceState !=
                    deviceExtension->CurrentDevicePowerState) {

                    // BulkUsb_IncrementIoCount(DeviceObject);

                    // No, request that we be put into this state
                                        // by requesting a new Power Irp from the Pnp manager
                    deviceExtension->PowerIrp = Irp;
                    ntStatus = PoRequestPowerIrp(deviceExtension->PhysicalDeviceObject,
                                               IRP_MN_SET_POWER,
                                               desiredDevicePowerState,
                                                                                           // completion routine will pass the Irp down to the PDO
                                               BulkUsb_PoRequestCompletion,
                                               DeviceObject,
                                               NULL);

                } else {
                    // Yes, just pass it on to PDO (Physical Device Object)
                    IoCopyCurrentIrpStackLocationToNext(Irp);
                    PoStartNextPowerIrp(Irp);
                    ntStatus = PoCallDriver(deviceExtension->TopOfStackDeviceObject,
                                            Irp);

                    BulkUsb_DecrementIoCount(DeviceObject);
                    BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Exit IRP_MN_SET_POWER\n"));

                }
                break;

            case DevicePowerState:

                BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Set Power, type DevicePowerState = %s\n",
                    BULKUSB_StringForDevState( irpStack->Parameters.Power.State.DeviceState ) ));

                // For requests to D1, D2, or D3 ( sleep or off states ),
                                // sets deviceExtension->CurrentDevicePowerState to DeviceState immediately.
                                // This enables any code checking state to consider us as sleeping or off
                                // already, as this will imminently become our state.

                // For requests to DeviceState D0 ( fully on ), sets fGoingToD0 flag TRUE
                // to flag that we must set a completion routine and update
                                // deviceExtension->CurrentDevicePowerState there.
                                // In the case of powering up to fully on, we really want to make sure
                                // the process is completed before updating our CurrentDevicePowerState,
                                // so no IO will be attempted or accepted before we're really ready.

                fGoingToD0 = BulkUsb_SetDevicePowerState(DeviceObject,
                                                      irpStack->Parameters.Power.State.DeviceState
                                                      ); // returns TRUE for D0

                IoCopyCurrentIrpStackLocationToNext(Irp);

                if (fGoingToD0) {
                    BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Set PowerIrp Completion Routine, fGoingToD0 =%d\n", fGoingToD0));
                    IoSetCompletionRoutine(Irp,
                           BulkUsb_PowerIrp_Complete,
                           // Always pass FDO to completion routine as its Context;
                           // This is because the DriverObject passed by the system to the routine
                           // is the Physical Device Object ( PDO ) not the Functional Device Object ( FDO )
                           DeviceObject,
                           TRUE,            // invoke on success
                           TRUE,            // invoke on error
                           TRUE);           // invoke on cancellation of the Irp
                }

                PoStartNextPowerIrp(Irp);
                ntStatus = PoCallDriver(deviceExtension->TopOfStackDeviceObject,
                                        Irp);

                if ( !fGoingToD0 ) // completion routine will decrement
                    BulkUsb_DecrementIoCount(DeviceObject);

                BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() Exit IRP_MN_SET_POWER\n"));
                break;
            } /* case irpStack->Parameters.Power.Type */

        }
        break; /* IRP_MN_SET_POWER */

    case IRP_MN_QUERY_POWER:
                //
                // A power policy manager sends this IRP to determine whether it can change
                // the system or device power state, typically to go to sleep.
                //

        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() IRP_MN_QUERY_POWER\n"));

        // We do nothing special here, just let the PDO handle it
        IoCopyCurrentIrpStackLocationToNext(Irp);
        PoStartNextPowerIrp(Irp);
        ntStatus = PoCallDriver(deviceExtension->TopOfStackDeviceObject,
                                Irp);


        BulkUsb_DecrementIoCount(DeviceObject);

        break; /* IRP_MN_QUERY_POWER */

    default:

        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_ProcessPowerIrp() UNKNOWN POWER MESSAGE (%x)\n", irpStack->MinorFunction));

        //
        // All unhandled power messages are passed on to the PDO
        //

        IoCopyCurrentIrpStackLocationToNext(Irp);
        PoStartNextPowerIrp(Irp);
        ntStatus = PoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);

        BulkUsb_DecrementIoCount(DeviceObject);

    } /* irpStack->MinorFunction */

    BULKUSB_KdPrint( DBGLVL_MEDIUM,  ( "Exit BulkUsb_ProcessPowerIrp()  ntStatus = 0x%x\n", ntStatus ) );
    return ntStatus;
}


NTSTATUS
BulkUsb_PoRequestCompletion(
    IN PDEVICE_OBJECT       DeviceObject,
    IN UCHAR                MinorFunction,
    IN POWER_STATE          PowerState,
    IN PVOID                Context,
    IN PIO_STATUS_BLOCK     IoStatus
    )
/*++

Routine Description:

        This is the completion routine set in a call to PoRequestPowerIrp()
        that was made in BulkUsb_ProcessPowerIrp() in response to receiving
    an IRP_MN_SET_POWER of type 'SystemPowerState' when the device was
        not in a compatible device power state. In this case, a pointer to
        the IRP_MN_SET_POWER Irp is saved into the FDO device extension
        (deviceExtension->PowerIrp), and then a call must be
        made to PoRequestPowerIrp() to put the device into a proper power state,
        and this routine is set as the completion routine.

    We decrement our pending io count and pass the saved IRP_MN_SET_POWER Irp
        on to the next driver

Arguments:

    DeviceObject - Pointer to the device object for the class device.
        Note that we must get our own device object from the Context

    Context - Driver defined context, in this case our own functional device object ( FDO )

Return Value:

    The function value is the final status from the operation.

--*/
{
    PIRP irp;
    PDEVICE_EXTENSION deviceExtension;
    PDEVICE_OBJECT deviceObject = Context;
    NTSTATUS ntStatus;

    deviceExtension = deviceObject->DeviceExtension;

        // Get the Irp we saved for later processing in BulkUsb_ProcessPowerIrp()
        // when we decided to request the Power Irp that this routine
        // is the completion routine for.
    irp = deviceExtension->PowerIrp;

        // We will return the status set by the PDO for the power request we're completing
    ntStatus = IoStatus->Status;

    BULKUSB_KdPrint( DBGLVL_HIGH,("Enter BulkUsb_PoRequestCompletion()\n"));

    // we should not be in the midst of handling a self-generated power irp
    BULKUSB_ASSERT( !deviceExtension->SelfPowerIrp );

    // we must pass down to the next driver in the stack
    IoCopyCurrentIrpStackLocationToNext(irp);

    // Calling PoStartNextPowerIrp() indicates that the driver is finished
    // with the previous power IRP, if any, and is ready to handle the next power IRP.
    // It must be called for every power IRP.Although power IRPs are completed only once,
    // typically by the lowest-level driver for a device, PoStartNextPowerIrp must be called
    // for every stack location. Drivers must call PoStartNextPowerIrp while the current IRP
    // stack location points to the current driver. Therefore, this routine must be called
    // before IoCompleteRequest, IoSkipCurrentStackLocation, and PoCallDriver.

    PoStartNextPowerIrp(irp);

    // PoCallDriver is used to pass any power IRPs to the PDO instead of IoCallDriver.
    // When passing a power IRP down to a lower-level driver, the caller should use
    // IoSkipCurrentIrpStackLocation or IoCopyCurrentIrpStackLocationToNext to copy the IRP to
    // the next stack location, then call PoCallDriver. Use IoCopyCurrentIrpStackLocationToNext
    // if processing the IRP requires setting a completion routine, or IoSkipCurrentStackLocation
    // if no completion routine is needed.

    PoCallDriver(deviceExtension->TopOfStackDeviceObject,
                 irp);

    BulkUsb_DecrementIoCount(deviceObject);

    BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_PoRequestCompletion() Exit IRP_MN_SET_POWER\n"));

    deviceExtension->PowerIrp = NULL;

    return ntStatus;
}




NTSTATUS
BulkUsb_PowerIrp_Complete(
    IN PDEVICE_OBJECT NullDeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
/*++

Routine Description:

    This routine is called when An IRP_MN_SET_POWER of type 'DevicePowerState'
    has been received by BulkUsb_ProcessPowerIrp(), and that routine has  determined
        1) the request is for full powerup ( to PowerDeviceD0 ), and
        2) We are not already in that state
    A call is then made to PoRequestPowerIrp() with this routine set as the completion routine.


Arguments:

    DeviceObject - Pointer to the device object for the class device.

    Irp - Irp completed.

    Context - Driver defined context.

Return Value:

    The function value is the final status from the operation.

--*/
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PDEVICE_OBJECT deviceObject;
    PIO_STACK_LOCATION irpStack;
    PDEVICE_EXTENSION deviceExtension;

    BULKUSB_KdPrint( DBGLVL_HIGH,("enter BulkUsb_PowerIrp_Complete\n"));

    deviceObject = (PDEVICE_OBJECT) Context;

    deviceExtension = (PDEVICE_EXTENSION) deviceObject->DeviceExtension;

    //  If the lower driver returned PENDING, mark our stack location as pending also.
    if (Irp->PendingReturned) {
        IoMarkIrpPending(Irp);
    }

    irpStack = IoGetCurrentIrpStackLocation (Irp);

    // We can assert that we're a  device powerup-to D0 request,
    // because that was the only type of request we set a completion routine
    // for in the first place
    BULKUSB_ASSERT(irpStack->MajorFunction == IRP_MJ_POWER);
    BULKUSB_ASSERT(irpStack->MinorFunction == IRP_MN_SET_POWER);
    BULKUSB_ASSERT(irpStack->Parameters.Power.Type==DevicePowerState);
    BULKUSB_ASSERT(irpStack->Parameters.Power.State.DeviceState==PowerDeviceD0);

    // Now that we know we've let the lower drivers do what was needed to power up,
    //  we can set our device extension flags accordingly
    deviceExtension->CurrentDevicePowerState = PowerDeviceD0;

    Irp->IoStatus.Status = ntStatus;

    BulkUsb_DecrementIoCount(deviceObject);

    BULKUSB_KdPrint( DBGLVL_MEDIUM,("exit BulkUsb_PowerIrp_Complete Exit IRP_MN_SET_POWER D0 complete\n"));
    return ntStatus;
}



NTSTATUS
BulkUsb_SelfSuspendOrActivate(
    IN PDEVICE_OBJECT DeviceObject,
    IN BOOLEAN fSuspend
    )
/*++

Routine Description:

        Called on BulkUsb_PnPAddDevice() to power down until needed (i.e., till a pipe is actually opened).
        Called on BulkUsb_Create() to power up device to D0 before opening 1st pipe.
        Called on BulkUsb_Close() to power down device if this is the last pipe.

Arguments:

    DeviceObject - Pointer to the device object

    fSuspend; TRUE to Suspend, FALSE to acivate.


Return Value:

    If the operation is not attemtped, SUCCESS is returned.
    If the operation is attemtped, the value is the final status from the operation.

--*/
{
    NTSTATUS ntStatus = STATUS_SUCCESS;

    POWER_STATE PowerState;
    PDEVICE_EXTENSION deviceExtension;


    deviceExtension = DeviceObject->DeviceExtension;
    BULKUSB_KdPrint( DBGLVL_MAXIMUM,("Enter BulkUsb_SelfSuspendOrActivate(),fSuspend = %d\n", fSuspend));


        // Can't accept request if:
    //  1) device is removed,
    //  2) has never been started,
    //  3) is stopped,
    //  4) has a remove request pending,
    //  5) has a stop device pending
    if ( !BulkUsb_CanAcceptIoRequests( DeviceObject ) ) {
        ntStatus = STATUS_DELETE_PENDING;

                BULKUSB_KdPrint( DBGLVL_MEDIUM,("ABORTING BulkUsb_SelfSuspendOrActivate()\n"));
        return ntStatus;
    }


    // don't do anything if any System-generated Device Pnp irps are pending
    if ( NULL != deviceExtension->PowerIrp ) {
        BULKUSB_KdPrint( DBGLVL_MAXIMUM,("Exit BulkUsb_SelfSuspendOrActivate(),refusing on pending deviceExtension->PowerIrp 0x%x\n", deviceExtension->PowerIrp));
        return ntStatus;
    }

    // don't do anything if any self-generated Device Pnp irps are pending
    if ( deviceExtension->SelfPowerIrp ) {
        BULKUSB_KdPrint( DBGLVL_MAXIMUM,("Exit BulkUsb_SelfSuspendOrActivate(),refusing on pending deviceExtension->SelfPowerIrp\n" ));
        return ntStatus;
    }

    // don't auto-suspend if any pipes are open
    if ( fSuspend && ( 0 != deviceExtension->OpenPipeCount ) ) {
        BULKUSB_KdPrint( DBGLVL_MAXIMUM,("Exit BulkUsb_SelfSuspendOrActivate(),refusing to self-suspend on OpenPipeCount %d\n", deviceExtension->OpenPipeCount));
        return ntStatus;
    }

    // don't auto-activate if no pipes are open
    if ( !fSuspend && ( 0 == deviceExtension->OpenPipeCount ) ) {
        BULKUSB_KdPrint( DBGLVL_MAXIMUM,("Exit BulkUsb_SelfSuspendOrActivate(),refusing to self-activate, no pipes open\n"));
        return ntStatus;
    }

    // dont do anything if registry CurrentControlSet\Services\BulkUsb\Parameters\PowerDownLevel
    //  has been set to  zero, PowerDeviceD0 ( 1 ), or a bogus high value
    if ( ( deviceExtension->PowerDownLevel == PowerDeviceD0 ) ||
         ( deviceExtension->PowerDownLevel == PowerDeviceUnspecified)  ||
         ( deviceExtension->PowerDownLevel >= PowerDeviceMaximum ) ) {
        BULKUSB_KdPrint( DBGLVL_MAXIMUM,("Exit BulkUsb_SelfSuspendOrActivate(), refusing on deviceExtension->PowerDownLevel == %d\n", deviceExtension->PowerDownLevel));
        return ntStatus;
    }

    if ( fSuspend )
        PowerState.DeviceState = deviceExtension->PowerDownLevel;
    else
        PowerState.DeviceState = PowerDeviceD0;  // power up all the way; we're probably just about to do some IO

    ntStatus = BulkUsb_SelfRequestPowerIrp( DeviceObject, PowerState );

    BULKUSB_KdPrint( DBGLVL_MAXIMUM,("BulkUsb_SelfSuspendOrActivate() status 0x%x on setting dev state %s\n", ntStatus, BULKUSB_StringForDevState(PowerState.DeviceState ) ));

    return ntStatus;

}


NTSTATUS
BulkUsb_SelfRequestPowerIrp(
    IN PDEVICE_OBJECT DeviceObject,
    IN POWER_STATE PowerState
    )
/*++

Routine Description:

    This routine is called by BulkUsb_SelfSuspendOrActivate() to
    actually make the system request for a powerdown/up to PowerState.
    It first checks to see if we are already in Powerstate and immediately
    returns  SUCCESS with no further processing if so


Arguments:

    DeviceObject - Pointer to the device object

    PowerState. power state requested, e.g PowerDeviceD0.


Return Value:

    The function value is the final status from the operation.

--*/
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PDEVICE_EXTENSION deviceExtension;
    PIRP pIrp = NULL;

    deviceExtension =  DeviceObject->DeviceExtension;

    // This should have been reset in completion routine
    BULKUSB_ASSERT( !deviceExtension->SelfPowerIrp );

    if (  deviceExtension->CurrentDevicePowerState ==  PowerState.DeviceState )
        return STATUS_SUCCESS;  // nothing to do

    BULKUSB_KdPrint( DBGLVL_HIGH,("Enter BulkUsb_SelfRequestPowerIrp() will request power irp to state %s\n",
        BULKUSB_StringForDevState( PowerState.DeviceState )));

    BulkUsb_IncrementIoCount(DeviceObject);

        // flag we're handling a self-generated power irp
    deviceExtension->SelfPowerIrp = TRUE;

        // actually request the Irp
    ntStatus = PoRequestPowerIrp(deviceExtension->PhysicalDeviceObject,
                         IRP_MN_SET_POWER,
                         PowerState,
                         BulkUsb_PoSelfRequestCompletion,
                         DeviceObject,
                         NULL);


    if  ( ntStatus == STATUS_PENDING ) {
        // status pending is the return code we wanted

        // We only need to wait for completion if we're powering up
        if ( (ULONG) PowerState.DeviceState < deviceExtension->PowerDownLevel ) {

            NTSTATUS waitStatus;

            waitStatus = KeWaitForSingleObject(
                           &deviceExtension->SelfRequestedPowerIrpEvent,
                           Suspended,
                           KernelMode,
                           FALSE,
                           NULL);

        }

        ntStatus = STATUS_SUCCESS;

        deviceExtension->SelfPowerIrp = FALSE;

        BULKUSB_KdPrint( DBGLVL_HIGH, ("BulkUsb_SelfRequestPowerIrp() SUCCESS\n    IRP 0x%x to state %s\n",
            pIrp, BULKUSB_StringForDevState(PowerState.DeviceState) ));


    }
    else {
        // The return status was not STATUS_PENDING; any other codes must be considered in error here;
        //  i.e., it is not possible to get a STATUS_SUCCESS  or any other non-error return from this call;
        BULKUSB_KdPrint( DBGLVL_HIGH, ("BulkUsb_SelfRequestPowerIrp() to state %s FAILED, status = 0x%x\n",
            BULKUSB_StringForDevState( PowerState.DeviceState ),ntStatus));
    }

    return ntStatus;
}



NTSTATUS
BulkUsb_PoSelfRequestCompletion(
    IN PDEVICE_OBJECT       DeviceObject,
    IN UCHAR                MinorFunction,
    IN POWER_STATE          PowerState,
    IN PVOID                Context,
    IN PIO_STATUS_BLOCK     IoStatus
    )
/*++

Routine Description:

    This routine is called when the driver completes a self-originated power IRP
        that was generated by a call to BulkUsb_SelfSuspendOrActivate().
    We power down whenever the last pipe is closed and power up when the first pipe is opened.

    For power-up , we set an event in our FDO extension to signal this IRP done
    so the power request can be treated as a synchronous call.
    We need to know the device is powered up before opening the first pipe, for example.
    For power-down, we do not set the event, as no caller waits for powerdown complete.

Arguments:

    DeviceObject - Pointer to the device object for the class device. ( Physical Device Object )

    Context - Driver defined context, in this case our FDO ( functional device object )

Return Value:

    The function value is the final status from the operation.

--*/
{
    PDEVICE_OBJECT deviceObject = Context;
    PDEVICE_EXTENSION deviceExtension = deviceObject->DeviceExtension;
    NTSTATUS ntStatus = IoStatus->Status;

    // we should not be in the midst of handling a system-generated power irp
    BULKUSB_ASSERT( NULL == deviceExtension->PowerIrp );

    // We only need to set the event if we're powering up;
    // No caller waits on power down complete
    if ( (ULONG) PowerState.DeviceState < deviceExtension->PowerDownLevel ) {

        // Trigger Self-requested power irp completed event;
        //  The caller is waiting for completion
        KeSetEvent(&deviceExtension->SelfRequestedPowerIrpEvent, 1, FALSE);
    }

    BulkUsb_DecrementIoCount(deviceObject);

    BULKUSB_KdPrintCond( DBGLVL_HIGH, !NT_SUCCESS(ntStatus),("Exit BulkUsb_PoSelfRequestCompletion() FAILED, ntStatus = 0x%x\n", ntStatus ));

    return ntStatus;
}


BOOLEAN
BulkUsb_SetDevicePowerState(
    IN PDEVICE_OBJECT DeviceObject,
    IN DEVICE_POWER_STATE DeviceState
    )
/*++

Routine Description:

    This routine is called when An IRP_MN_SET_POWER of type 'DevicePowerState'
    has been received by BulkUsb_ProcessPowerIrp().


Arguments:

    DeviceObject - Pointer to the device object for the class device.

    DeviceState - Device specific power state to set the device in to.


Return Value:

    For requests to DeviceState D0 ( fully on ), returns TRUE to signal caller
    that we must set a completion routine and finish there.

--*/
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PDEVICE_EXTENSION deviceExtension;
    BOOLEAN fRes = FALSE;

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    switch (DeviceState) {
    case PowerDeviceD3:

        //
        // Device will be going OFF,
                // TODO: add any needed device-dependent code to save state here.
                //  ( We have nothing to do in this sample )
        //

        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_SetDevicePowerState() PowerDeviceD3 (OFF)\n"));

        deviceExtension->CurrentDevicePowerState = DeviceState;
        break;

    case PowerDeviceD1:
    case PowerDeviceD2:
        //
        // power states D1,D2 translate to USB suspend

        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_SetDevicePowerState()  %s\n",
            BULKUSB_StringForDevState(DeviceState) ));

        deviceExtension->CurrentDevicePowerState = DeviceState;
        break;

    case PowerDeviceD0:


        BULKUSB_KdPrint( DBGLVL_MEDIUM,("BulkUsb_SetDevicePowerState() PowerDeviceD0 (ON)\n"));

        // We'll need to finish the rest in the completion routine;
        //   signal caller we're going to D0 and will need to set a completion routine
        fRes = TRUE;

        // Caller will pass on to PDO ( Physical Device object )
        break;

    default:

        BULKUSB_KdPrint( DBGLVL_MEDIUM,(" Bogus DeviceState = %x\n", DeviceState));
    }

    return fRes;
}



NTSTATUS
BulkUsb_QueryCapabilities(
    IN PDEVICE_OBJECT       LowerDeviceObject,
    IN PDEVICE_CAPABILITIES DeviceCapabilities
    )

/*++

Routine Description:

    This routine generates an internal IRP from this driver to the lower portion
    of the driver stack to obtain information on the Device Object's
    capabilities. We are most interested in learning which system power states
    are to be mapped to which device power states for honoring
    IRP_MJ_SET_POWER Irps.

    This is a blocking call which waits for the IRP completion routine
    to set an event on finishing.

Arguments:

    LowerDeviceObject        - DeviceObject beneath this driver in the stack.

Return Value:

    NTSTATUS value from the IoCallDriver() call.

--*/

{
    PIO_STACK_LOCATION nextStack;
    PIRP irp;
    NTSTATUS ntStatus;
    KEVENT event;


    // This is a DDK-defined DBG-only macro that ASSERTS we are not running pageable code
    // at higher than APC_LEVEL.
    PAGED_CODE();


    // Build an IRP for us to generate an internal query request to the PDO
    irp = IoAllocateIrp(LowerDeviceObject->StackSize, FALSE);

    if (!irp) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Preinit the device capability structures appropriately.
    //
    RtlZeroMemory( DeviceCapabilities, sizeof(DEVICE_CAPABILITIES) );
    DeviceCapabilities->Size = sizeof(DEVICE_CAPABILITIES);
    DeviceCapabilities->Version = 1;
    DeviceCapabilities->Address = -1;
    DeviceCapabilities->UINumber = -1;

    // IoGetNextIrpStackLocation gives a higher level driver access to the next-lower
    // driver's I/O stack location in an IRP so the caller can set it up for the lower driver.
    nextStack = IoGetNextIrpStackLocation(irp);
    nextStack->MajorFunction= IRP_MJ_PNP;
    nextStack->MinorFunction= IRP_MN_QUERY_CAPABILITIES;

    // init an event to tell us when the completion routine's been called
    KeInitializeEvent(&event, NotificationEvent, FALSE);

    // Set a completion routine so it can signal our event when
    //  the next lower driver is done with the Irp
    IoSetCompletionRoutine(irp,
                           BulkUsb_IrpCompletionRoutine,
                           &event,  // pass the event as Context to completion routine
                           TRUE,    // invoke on success
                           TRUE,    // invoke on error
                           TRUE);   // invoke on cancellation of the Irp


    // set our pointer to the DEVICE_CAPABILITIES struct
    nextStack->Parameters.DeviceCapabilities.Capabilities = DeviceCapabilities;

    // preset the irp to report not supported
    irp->IoStatus.Status = STATUS_NOT_SUPPORTED;

    ntStatus = IoCallDriver(LowerDeviceObject,
                            irp);

    BULKUSB_KdPrint( DBGLVL_MEDIUM,(" BulkUsb_QueryCapabilities() ntStatus from IoCallDriver to PCI = 0x%x\n", ntStatus));

    if (ntStatus == STATUS_PENDING) {
       // wait for irp to complete

       KeWaitForSingleObject(
            &event,
            Suspended,
            KernelMode,
            FALSE,
            NULL);

       ntStatus = irp->IoStatus.Status;
    }

    // failed? this is probably a bug
    BULKUSB_KdPrintCond( DBGLVL_DEFAULT,(!NT_SUCCESS(ntStatus)), ("BulkUsb_QueryCapabilities() failed\n"));

    IoFreeIrp(irp);

    return ntStatus;
}