summaryrefslogblamecommitdiffstats
path: root/private/ntos/po/postate.c
blob: bbf55c4c8bec4c30a130cbeeb1b55bcabb835d0a (plain) (tree)
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



















































































































































































































































































































































































































































































































































































































































































































































































                                                                                                      
/*++

Copyright (c) 1990  Microsoft Corporation

Module Name:

    state.c

Abstract:

    Maintains state changes for power management power states
    for device objects

Author:

    Ken Reneris (kenr) 19-July-1994

Revision History:

--*/


#include "pop.h"

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, PopStateChangeWorker)
#endif


NTSTATUS
PoRequestPowerChange (
    IN PDEVICE_OBJECT   DeviceObject,
    IN POWER_STATE      SystemPowerState,
    IN ULONG            DevicePowerState
    )
/*++

Routine Description:

    Request to put the supplied device object into the supplied power
    state.   If need be the device will be sent a SetPower irp to
    allow it to change into the specific power state.

Arguments:

    DeviceObject - Device Object to change power state
    SystsemPowerState - Desired system specified power state
    DevicePowerState - Desired device specific power state

Return Value:

    Success if state change is pending; otherwise error

--*/
{
    KIRQL   OldIrql;

#ifndef _PNP_POWER_

    return STATUS_NOT_IMPLEMENTED;

#else

    PopLockStateDatabase (&OldIrql);

    PopRequestPowerChange (
       DeviceObject->DeviceObjectExtension,
       SystemPowerState,
       DevicePowerState
       );

    PopUnlockStateDatabase (OldIrql);

    return STATUS_SUCCESS;

#endif
}

#ifdef _PNP_POWER_

VOID
PopRequestPowerChange (
    IN PDEVOBJ_EXTENSION DeviceObjectExt,
    IN POWER_STATE      SystemPowerState,
    IN ULONG            DevicePowerState
    )
/*++

Routine Description:

    Request to set the devices PendingPowerState and PendingDevicePowerState
    to the passed parameters.  This function will merge multiple power
    state requests and queue the device object for later processing if
    needed.

    Assumes the caller has the power state database lock

Arguments:

    DeviceObject - Device Object to change power state
    SystsemPowerState - Desired system specified power state
    DevicePowerState - Desired device specific power state

Return Value:

    none.

--*/
{
    PLIST_ENTRY     WhichQueue;


    ASSERT (SystemPowerState <= PowerDown);

    //
    // If device is already queued onto a power state change queue, remove it
    //

    if (DeviceObjectExt->PowerStateChange.Flink) {
        RemoveEntryList (&DeviceObjectExt->PowerStateChange);
        DeviceObjectExt->PowerStateChange.Flink = NULL;
    }

    //
    // If this device isn't concerned with power management, then set it
    // to whatever state we're in
    //

    if (!DeviceObjectExt->PowerControlNeeded) {
        DeviceObjectExt->CurrentPowerState = SystemPowerState;
        DeviceObjectExt->PendingPowerState = SystemPowerState;
        return ;
    }

    //
    // If device specific state specified, set it as pending
    //

    if (DevicePowerState != 0) {
        DeviceObjectExt->PendingDevicePowerState = DevicePowerState;
    }

    //
    // If power management has been disabled, then devices should always
    // be in the PowerUp state.
    //

    if (!PoEnabled) {
        // hardcoded to PowerUp state when not enabled
        SystemPowerState = PowerUp;
    }

    //
    // Merge the pending state with the current pending state.
    //

    SystemPowerState = PopNewPendingState[DeviceObjectExt->PendingPowerState]
                                         [SystemPowerState];
    ASSERT (SystemPowerState != PowerUnspecified);

    //
    // If the new state is PowerUp but the pending state is either suspend
    // or hibernate, delay the powerup until the SuspendInProgress
    // flag is clear
    //

    if (SystemPowerState == VerifyUp) {
        DeviceObjectExt->SetPowerUpPending = TRUE;

        //
        // Change requesting state to the pending state
        //

        SystemPowerState = DeviceObjectExt->PendingPowerState;
    }

    //
    // If delayed powerup is needed and the current state matches the
    // new state, and a suspend is no longer in progress then
    // change requesting state to be a PowerUp
    //

    if (DeviceObjectExt->SetPowerUpPending &&
        DeviceObjectExt->CurrentPowerState == SystemPowerState &&
        !DeviceObjectExt->Suspending) {

        DeviceObjectExt->SetPowerUpPending = FALSE;
        SystemPowerState = PowerUp;
    }

    //
    // Set new pending state
    //

    DeviceObjectExt->PendingPowerState = SystemPowerState;

    //
    // Determine which PowerChange queue to enqueue devices request
    //

    if (DeviceObjectExt->CurrentSetPowerIrp) {

        //
        // Power state change in progress for this device, put
        // device back on InProgress queue
        //

        WhichQueue = &PopStateChangeInProgress;

    } else if (DeviceObjectExt->CurrentPowerState == DeviceObjectExt->PendingPowerState  &&
               DeviceObjectExt->CurrentDevicePowerState == DeviceObjectExt->PendingDevicePowerState) {

        //
        // Pending power states match current states, no need to queue
        //

        WhichQueue = NULL;

    } else if (DeviceObjectExt->PendingPowerState == PowerUp  &&
               !DeviceObjectExt->UseAsyncPowerUp) {

        //
        // PowerUp and the device does not support AsyncPowerUp, so it's a
        // system synchronous power state change
        //

        WhichQueue = &PopSyncStateChangeQueue;

    } else {

        //
        // Asynchronous state change
        //

        WhichQueue = &PopAsyncStateChangeQueue;
    }

    if (WhichQueue) {

        //
        // Enqueue device onto it's queue & kick off a DPC to handle it
        //

        InsertTailList (WhichQueue, &DeviceObjectExt->PowerStateChange);
        if (!PopStateChangeDpcActive) {
            PopStateChangeDpcActive = TRUE;
            KeInsertQueueDpc (&PopStateChangeDpc, NULL, NULL);
        }

#if 0
        //
        // Stop IoStartPacket from sending any new non-power irps
        // to the device driver.  Once the device reaches an
        // steady-state of PowerUp the queue will be released
        //

        DeviceObjectExt->StartIoQueueHolding = TRUE;
#endif

    } else {

        //
        // Device was not added to any work queue, if all state change
        // queues are empty notify Suspend/Hibernate code
        //

        if (PopIsStateDatabaseIdle()) {
            if (!KeReadStateEvent (&PopStateDatabaseIdle)) {
                KeSetEvent (&PopStateDatabaseIdle, 0, FALSE);
            }
        }
    }
}



VOID
PopStateChange (
    IN PKDPC    Dpc,
    IN PVOID    DeferredContext,
    IN PVOID    SystemArgument1,
    IN PVOID    SystemArgument2
    )
/*++

Routine Description:

    DPC to process devices which have pending power state changes.

Arguments:

Return Value:

    none.

--*/
{
    PLIST_ENTRY         Entry;
    KIRQL               OldIrql;
    BOOLEAN             SyncRequest, CleanUpError;
    PDEVOBJ_EXTENSION   DeviceObjectExt;
    PIRP                irp;
    PIO_STACK_LOCATION  irpSp;
    POWER_STATE         NewPowerState;
    ULONG               NewDevicePowerState;
    PLIST_ENTRY         Link;


    CleanUpError = FALSE;

    for (; ;) {
        PopLockStateDatabase (&OldIrql);

        //
        // If there's a synchronous state change waiting, and no other
        // synchronous state change start one.
        //

        if (!IsListEmpty(&PopSyncStateChangeQueue)  &&  !PopSyncChangeInProgress) {

            //
            // Process entry in synchronous queue
            //

            PopSyncChangeInProgress = TRUE;
            SyncRequest = TRUE;
            Entry = RemoveHeadList (&PopSyncStateChangeQueue);

        } else if (!IsListEmpty(&PopAsyncStateChangeQueue)) {

            //
            // Process entry in asynchronous queue
            //

            SyncRequest = FALSE;
            Entry = RemoveHeadList (&PopAsyncStateChangeQueue);

        } else {

            //
            // No entries found to work on, done
            //

            break;
        }

        //
        // Put device in the state change in progress queue
        //

        InsertTailList (&PopStateChangeInProgress, Entry);
        DeviceObjectExt = CONTAINING_RECORD(Entry, DEVOBJ_EXTENSION, PowerStateChange);

        //
        // SetPower is in progress, put non-zero value in CurrentSetPowerIrp
        // and collect the new pending state information
        //

        DeviceObjectExt->CurrentSetPowerIrp = (PIRP) -1;
        NewPowerState = DeviceObjectExt->PendingPowerState;
        NewDevicePowerState = DeviceObjectExt->PendingDevicePowerState;

        //
        // Unlock power database
        //

        PopUnlockStateDatabase (OldIrql);

        //
        // Allocate and send the device a SetPower irp for it's new power
        // state
        //

        irp = IoAllocateIrp ( (CCHAR) 2, FALSE );

        if (!irp) {
            CleanUpError = TRUE;
            break;
        }

        //
        // Retain the current irp performing the SetPower for this device
        //

        DeviceObjectExt->CurrentSetPowerIrp = irp;

        //
        // Copy some state into the first stack location
        //

        irpSp = IoGetNextIrpStackLocation (irp);
        irpSp->Parameters.Others.Argument1 = (PVOID) NewPowerState;
        irpSp->Parameters.Others.Argument2 = (PVOID) NewDevicePowerState;
        irpSp->Parameters.Others.Argument3 = (PVOID) SyncRequest;
        irpSp->DeviceObject = DeviceObjectExt->DeviceObject;

        //
        // Fill in params for SetPower irp
        //

        IoSetNextIrpStackLocation (irp);
        irpSp = IoGetNextIrpStackLocation (irp);
        irpSp->MajorFunction = IRP_MJ_SET_POWER;
        irpSp->Parameters.SetPower.PowerState = NewPowerState;
        irpSp->Parameters.SetPower.DevicePowerState = NewDevicePowerState;
        irpSp->DeviceObject = DeviceObjectExt->DeviceObject;
        irp->UserIosb  = NULL;
        irp->UserEvent = NULL;

        IoHoldDeviceQueue (DeviceObjectExt->DeviceObject, irp);

        IoSetCompletionRoutine(
                irp,
                PopSetPowerComplete,
                NULL,  /* Context */
                TRUE,
                TRUE,
                TRUE
            );

        //
        // If the device is in the powered up state, then we will
        // send this initial !PowerUp request to the device via
        // a worker thread.  This allows the device driver to have
        // pagable code for it's SetPower handling as the first
        // request it will get to leave the PowerUp state will always
        // occur at IRQL < DISPATCH_LEVEL.
        //

        if (DeviceObjectExt->CurrentPowerState == PowerUp ||
            DeviceObjectExt->PowerControlPagable == TRUE) {

#if DBG
            //
            // If device has PowerControlPaged, it must also have
            // AsyncPowerUp
            //

            if (DeviceObjectExt->PowerControlPagable) {
                ASSERT (DeviceObjectExt->UseAsyncPowerUp);
            }
#endif

            //
            // Queue the IRP for the worker thread
            //

            Link = ExInterlockedInsertTailList (
                        &PopStateChangeWorkerList,
                        (PLIST_ENTRY) &irp->Tail.Overlay.ListEntry,
                        &PopStateLock
                        );

            if (Link == NULL) {
                ExQueueWorkItem (&PopStateChangeWorkItem, CriticalWorkQueue);
            }

        } else {

            //
            // send the IRP
            //

            irp->Tail.Overlay.Thread = PsGetCurrentThread();
            IoCallDriver( DeviceObjectExt->DeviceObject, irp );
        }

        //
        // loop, go look for more work
        //
    }

    if (CleanUpError) {

        //
        // Something happened and the power state change requested
        // on the DeviceObjectExt.  Undo the work, and
        // set a timer to try again later.
        //

        PopLockStateDatabase (&OldIrql);

        DeviceObjectExt->CurrentSetPowerIrp = NULL;
        if (SyncRequest) {
            PopSyncChangeInProgress = FALSE;
        }

        //
        // Request device's current state
        //

        PopRequestPowerChange (DeviceObjectExt, 0, 0);

        //
        // Try again later
        //

        KeSetTimer (
            &PopStateChangeTimer,
            PopIdleScanTime,
            &PopStateChangeDpc
            );

    } else {

        //
        // All pending work submitted, wait for more
        //

        PopStateChangeDpcActive = FALSE;
    }

    //
    // Unlock Power Manager Database
    //

    PopUnlockStateDatabase (OldIrql);
}

VOID
PopStateChangeWorker (
    IN PVOID    WorkerContext
    )
/*++

Routine Description:

    Dispatches enqueued SetPower IRPs from PASSIVE_LEVEL.

Arguments:

Return Value:

--*/
{
    PLIST_ENTRY         Entry;
    PIRP                irp;
    PIO_STACK_LOCATION  irpSp;

    PAGED_CODE();

    //
    // Reset work queue item for next time
    //

    ExInitializeWorkItem (&PopStateChangeWorkItem, PopStateChangeWorker, NULL);

    //
    // Dispatch any pending state change irps
    //

    while (Entry = ExInterlockedRemoveHeadList (&PopStateChangeWorkerList, &PopStateLock)) {

        //
        // Send this state change IRP
        //

        irp = CONTAINING_RECORD(Entry, IRP, Tail.Overlay.ListEntry);
        irpSp = IoGetCurrentIrpStackLocation (irp);
        irp->Tail.Overlay.Thread = PsGetCurrentThread();
        IoCallDriver( irpSp->DeviceObject, irp );
    }
}


NTSTATUS
PopSetPowerComplete (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
/*++

Routine Description:

    Completion function for a SetPower IRP.  If the device completed
    the SetPower request sucessfully, then the drivers current power
    state is updated; otherwise, the devices current power state is
    not changed.

Arguments:

    DeviceObject - NULL.
    Irp          - SetPower irp which has completed
    Context      - NULL.

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED is returned to IoCompleteRequest
    to signify that IoCompleteRequest should not continue processing
    the IRP.

--*/
    )
{
    KIRQL               OldIrql;
    BOOLEAN             SetIdleTimer;
    BOOLEAN             SyncRequest;
    BOOLEAN             Failed;
    UCHAR               PowerState, DevicePowerState;
    PIO_STACK_LOCATION  irpSp;
    PDEVOBJ_EXTENSION   DeviceObjectExt;
#if DBG
    POWER_STATE                 FailedCurrentPowerState;
    POWER_STATE                 FailedPendingPowerState;
    POBJECT_NAME_INFORMATION    FailedObjectName;
#endif

    SetIdleTimer = FALSE;
    Failed = FALSE;

    //
    // Read state from Irp.
    //

    irpSp = IoGetCurrentIrpStackLocation (Irp);
    PowerState       = (UCHAR)   irpSp->Parameters.Others.Argument1;
    DevicePowerState = (UCHAR)   irpSp->Parameters.Others.Argument2;
    SyncRequest      = (BOOLEAN) irpSp->Parameters.Others.Argument3;
    DeviceObject     = irpSp->DeviceObject;
    DeviceObjectExt  = DeviceObject->DeviceObjectExtension;

    PopLockStateDatabase (&OldIrql);

    //
    // Set device's new power state to match those
    // of the requested state
    //

    if (NT_SUCCESS (Irp->IoStatus.Status)) {
        DeviceObjectExt->CurrentPowerState = PowerState;
        DeviceObjectExt->CurrentDevicePowerState = DevicePowerState;

    } else {

        //
        // Device failed to enter the requested power state.
        //

#if DBG
        if (DeviceObjectExt->PendingPowerState == PowerState &&
            DeviceObjectExt->CurrentPowerState != DeviceObjectExt->PendingPowerState) {

            Failed = TRUE;
            FailedCurrentPowerState = DeviceObjectExt->CurrentPowerState;
            FailedPendingPowerState = DeviceObjectExt->PendingPowerState;
        }
#endif
        //
        // If failed to set the pending power state, then abort the pending
        // power state back to the current state.
        //

        if (DeviceObjectExt->PendingPowerState == PowerState) {
            DeviceObjectExt->PendingPowerState = DeviceObjectExt->CurrentPowerState;
        }

        if (DeviceObjectExt->PendingDevicePowerState == DevicePowerState) {
            DeviceObjectExt->PendingDevicePowerState = DeviceObjectExt->CurrentDevicePowerState;
        }
    }

    //
    // Check to see if this was a synchronous state change which just completed,
    // if so allow the new synchronous state change.
    //

    if (SyncRequest) {
        ASSERT (PopSyncChangeInProgress == TRUE);
        PopSyncChangeInProgress = FALSE;
    }

    //
    // SetPower no longer in progress, clear the CurrentIrpSetPower pointer
    //

    DeviceObjectExt->CurrentSetPowerIrp = NULL;

    //
    // Request power state to match current pending state
    //

    PopRequestPowerChange (DeviceObjectExt, 0, 0);

    //
    // If the CurrentPowerState and the PendingPowerState are both
    // PowerUp, then the device is PoweredOn and a change is not pending
    //

    if (DeviceObjectExt->CurrentPowerState == PowerUp  &&
        DeviceObjectExt->PendingPowerState == PowerUp) {

        //
        // If the Device get Idle detection make sure it's in the
        // ActiveIdleScanQueue
        //

        if (DeviceObjectExt->MaxIdleCount != 0 &&
            DeviceObjectExt->IdleList.Flink == NULL) {

            SetIdleTimer = IsListEmpty(&PopActiveIdleScanQueue);
            InsertTailList (&PopActiveIdleScanQueue, &DeviceObjectExt->IdleList);
            PoSetDeviceBusy (DeviceObject);
        }

        //
        // Release any irps which were postponded from IoStartPacket
        //

        IoReleaseStartIoHoldingQueue (DeviceObject);
    }

    PopUnlockStateDatabase (OldIrql);

#if DBG
    if (Failed) {

        FailedObjectName = PopGetDeviceName (DeviceObject);
        if (FailedObjectName) {
            DbgPrint ("PO: Device %lx failed %s->%s  '%Z'\n",
                DeviceObject,
                PopPowerState (FailedCurrentPowerState),
                PopPowerState (FailedPendingPowerState),
                &FailedObjectName->Name
                );

            ExFreePool (FailedObjectName);
        } else {
            DbgPrint ("PO: Device %lx failed %s->%s\n",
                DeviceObject,
                PopPowerState (FailedCurrentPowerState),
                PopPowerState (FailedPendingPowerState)
                );
        }
    }
#endif

    //
    // If IdleScan list went from being empty to having something in it,
    // set the idle the timer
    //

    if (SetIdleTimer) {
        KeSetTimer (&PopIdleScanTimer, PopIdleScanTime, &PopIdleScanDpc);
    }

    //
    // Irp processing is complete, free the irp and then return
    // more_processing_requered which causes IoCompleteRequest to
    // stop "completing" this irp any future.
    //

    IoFreeIrp (Irp);
    return STATUS_MORE_PROCESSING_REQUIRED;
}

#endif // _PNP_POWER_