2 * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
22 #include <IOKit/IOWorkLoop.h>
23 #include <IOKit/IOCommandQueue.h>
24 #include <IOKit/IOTimerEventSource.h>
25 #include <IOKit/IOPlatformExpert.h>
26 #include <IOKit/pwr_mgt/RootDomain.h>
27 #include <IOKit/pwr_mgt/IOPMPrivate.h>
28 #include <IOKit/IOMessage.h>
29 #include "RootDomainUserClient.h"
30 #include "IOKit/pwr_mgt/IOPowerConnection.h"
32 extern "C" void kprintf(const char *, ...);
34 extern const IORegistryPlane
* gIOPowerPlane
;
36 void PMreceiveCmd ( OSObject
*, void *, void *, void *, void * );
37 static void sleepTimerExpired(thread_call_param_t
);
38 static void wakeupClamshellTimerExpired ( thread_call_param_t us
);
41 #define number_of_power_states 5
43 #define RESTART_STATE 1
48 #define ON_POWER kIOPMPowerOn
49 #define RESTART_POWER kIOPMRestart
50 #define SLEEP_POWER kIOPMAuxPowerOn
51 #define DOZE_POWER kIOPMDoze
53 static IOPMPowerState ourPowerStates
[number_of_power_states
] = {
54 {1,0, 0, 0,0,0,0,0,0,0,0,0}, // state 0, off
55 {1,kIOPMRestartCapability
, kIOPMRestart
, RESTART_POWER
,0,0,0,0,0,0,0,0}, // state 1, restart
56 {1,kIOPMSleepCapability
, kIOPMSleep
, SLEEP_POWER
,0,0,0,0,0,0,0,0}, // state 2, sleep
57 {1,kIOPMDoze
, kIOPMDoze
, DOZE_POWER
,0,0,0,0,0,0,0,0}, // state 3, doze
58 {1,kIOPMPowerOn
, kIOPMPowerOn
, ON_POWER
,0,0,0,0,0,0,0,0}, // state 4, on
61 static IOPMrootDomain
* gRootDomain
;
62 static UInt32 gSleepOrShutdownPending
= 0;
65 #define super IOService
66 OSDefineMetaClassAndStructors(IOPMrootDomain
,IOService
)
70 IONotifier
* registerSleepWakeInterest(IOServiceInterestHandler handler
, void * self
, void * ref
= 0)
72 return gRootDomain
->registerInterest( gIOGeneralInterest
, handler
, self
, ref
);
75 IONotifier
* registerPrioritySleepWakeInterest(IOServiceInterestHandler handler
, void * self
, void * ref
= 0)
77 return gRootDomain
->registerInterest( gIOPriorityPowerStateInterest
, handler
, self
, ref
);
80 IOReturn
acknowledgeSleepWakeNotification(void * PMrefcon
)
82 return gRootDomain
->allowPowerChange ( (unsigned long)PMrefcon
);
85 IOReturn
vetoSleepWakeNotification(void * PMrefcon
)
87 return gRootDomain
->cancelPowerChange ( (unsigned long)PMrefcon
);
90 IOReturn
rootDomainRestart ( void )
92 return gRootDomain
->restartSystem();
95 IOReturn
rootDomainShutdown ( void )
97 return gRootDomain
->shutdownSystem();
100 void IOSystemShutdownNotification ( void )
102 for ( int i
= 0; i
< 100; i
++ )
104 if ( OSCompareAndSwap( 0, 1, &gSleepOrShutdownPending
) ) break;
109 int sync_internal(void);
113 A device is always in the highest power state which satisfies its driver, its policy-maker, and any power domain
114 children it has, but within the constraint of the power state provided by its parent. The driver expresses its desire by
115 calling changePowerStateTo(), the policy-maker expresses its desire by calling changePowerStateToPriv(), and the children
116 express their desires by calling requestPowerDomainState().
118 The Root Power Domain owns the policy for idle and demand sleep and doze for the system. It is a power-managed IOService just
119 like the others in the system. It implements several power states which correspond to what we see as Sleep, Doze, etc.
121 The sleep/doze policy is as follows:
122 Sleep and Doze are prevented if the case is open so that nobody will think the machine is off and plug/unplug cards.
123 Sleep and Doze are prevented if the sleep timeout slider in the preferences panel is at zero.
124 The system cannot Sleep, but can Doze if some object in the tree is in a power state marked kIOPMPreventSystemSleep.
126 These three conditions are enforced using the "driver clamp" by calling changePowerStateTo(). For example, if the case is
127 opened, changePowerStateTo(ON_STATE) is called to hold the system on regardless of the desires of the children of the root or
128 the state of the other clamp.
130 Demand Sleep/Doze is initiated by pressing the front panel power button, closing the clamshell, or selecting the menu item.
131 In this case the root's parent actually initiates the power state change so that the root has no choice and does not give
132 applications the opportunity to veto the change.
134 Idle Sleep/Doze occurs if no objects in the tree are in a state marked kIOPMPreventIdleSleep. When this is true, the root's
135 children are not holding the root on, so it sets the "policy-maker clamp" by calling changePowerStateToPriv(ON_STATE)
136 to hold itself on until the sleep timer expires. This timer is set for the difference between the sleep timeout slider and
137 the larger of the display dim timeout slider and the disk spindown timeout slider in the Preferences panel. For example, if
138 the system is set to sleep after thirty idle minutes, and the display and disk are set to sleep after five idle minutes,
139 when there is no longer an object in the tree holding the system out of Idle Sleep (via kIOPMPreventIdleSleep), the root
140 sets its timer for 25 minutes (30 - 5). When the timer expires, it releases its clamp and now nothing is holding it awake,
143 Demand sleep is prevented when the system is booting. When preferences are transmitted by the loginwindow at the end of
144 boot, a flag is cleared, and this allows subsequent Demand Sleep.
146 The system will not Sleep, but will Doze if some object calls setSleepSupported(kPCICantSleep) during a power change to the sleep state (this can be done by the PCI Aux Power Supply drivers, Slots99, MacRISC299, etc.). This is not enforced with
147 a clamp, but sets a flag which is noticed before actually sleeping the kernel. If the flag is set, the root steps up
148 one power state from Sleep to Doze, and any objects in the tree for which this is relevent will act appropriately (USB and
149 ADB will turn on again so that they can wake the system out of Doze (keyboard/mouse activity will cause the Display Wrangler
154 // **********************************************************************************
156 IOPMrootDomain
* IOPMrootDomain::construct( void )
158 IOPMrootDomain
* root
;
160 root
= new IOPMrootDomain
;
167 // **********************************************************************************
169 static void disk_sync_callout(thread_call_param_t p0
, thread_call_param_t p1
)
171 IOService
* rootDomain
= (IOService
*) p0
;
172 unsigned long pmRef
= (unsigned long) p1
;
175 rootDomain
->allowPowerChange(pmRef
);
178 // **********************************************************************************
181 // We don't do much here. The real initialization occurs when the platform
182 // expert informs us we are the root.
183 // **********************************************************************************
186 bool IOPMrootDomain::start ( IOService
* nub
)
188 OSDictionary
*tmpDict
;
195 setProperty("IOSleepSupported","");
197 sleepIsSupported
= true;
198 systemBooting
= true;
199 ignoringClamshell
= true;
201 idleSleepPending
= false;
205 ignoringClamshellDuringWakeup
= false;
207 tmpDict
= OSDictionary::withCapacity(1);
208 setProperty(kRootDomainSupportedFeatures
, tmpDict
);
211 pm_vars
->PMworkloop
= IOWorkLoop::workLoop(); // make the workloop
212 pm_vars
->commandQueue
= IOCommandQueue::commandQueue(this, PMreceiveCmd
); // make a command queue
213 if (! pm_vars
->commandQueue
||
214 ( pm_vars
->PMworkloop
->addEventSource( pm_vars
->commandQueue
) != kIOReturnSuccess
) ) {
217 extraSleepTimer
= thread_call_allocate((thread_call_func_t
)sleepTimerExpired
, (thread_call_param_t
) this);
218 clamshellWakeupIgnore
= thread_call_allocate((thread_call_func_t
)wakeupClamshellTimerExpired
, (thread_call_param_t
) this);
219 diskSyncCalloutEntry
= thread_call_allocate(&disk_sync_callout
, (thread_call_param_t
) this);
221 patriarch
= new IORootParent
; // create our parent
223 patriarch
->attach(this);
224 patriarch
->start(this);
225 patriarch
->youAreRoot();
226 patriarch
->wakeSystem();
227 patriarch
->addPowerChild(this);
229 registerPowerDriver(this,ourPowerStates
,number_of_power_states
);
231 setPMRootDomain(this);
232 changePowerStateToPriv(ON_STATE
); // set a clamp until we sleep
234 registerPrioritySleepWakeInterest( &sysPowerDownHandler
, this, 0); // install power change handler
236 // Register for a notification when IODisplayWrangler is published
237 addNotification( gIOPublishNotification
, serviceMatching("IODisplayWrangler"), &displayWranglerPublished
, this, 0);
239 registerService(); // let clients find us
245 //*********************************************************************************
248 // Power Managment is informing us that we are the root power domain.
249 // We know we are not the root however, since we have just instantiated a parent
250 // for ourselves and made it the root. We override this method so it will have
252 //*********************************************************************************
253 IOReturn
IOPMrootDomain::youAreRoot ( void )
258 // **********************************************************************************
261 // We have received a command from ourselves on the command queue.
262 // If it is to send a recently-received aggressiveness factor, do so.
263 // Otherwise, it's something the superclass enqueued.
264 // **********************************************************************************
265 void IOPMrootDomain::command_received ( void * command
, void * x
, void * y
, void * z
)
267 switch ( (int)command
) {
268 case kIOPMBroadcastAggressiveness
:
270 super::setAggressiveness((unsigned long)x
,(unsigned long)y
);
272 // Save user's spin down timer to restore after we replace it for idle sleep
273 if( (int)x
== kPMMinutesToSpinDown
) user_spindown
= (unsigned int) y
;
275 // Use longestNonSleepSlider to calculate dimming adjust idle sleep timer
276 longestNonSleepSlider
= pm_vars
->current_aggressiveness_values
[kPMMinutesToDim
];
279 if ( (int)x
== kPMMinutesToSleep
) {
280 if ( (sleepSlider
== 0) && ((int)y
!= 0) ) {
281 sleepSlider
= (int)y
;
282 adjustPowerState(); // idle sleep is now enabled, maybe sleep now
284 sleepSlider
= (int)y
;
285 if ( sleepSlider
== 0 ) {
286 adjustPowerState(); // idle sleep is now disabled
287 patriarch
->wakeSystem(); // make sure we're powered
290 if ( sleepSlider
> longestNonSleepSlider
) {
291 extraSleepDelay
= sleepSlider
- longestNonSleepSlider
;
299 super::command_received(command
,x
,y
,z
);
305 // **********************************************************************************
308 // **********************************************************************************
309 static void sleepTimerExpired ( thread_call_param_t us
)
311 ((IOPMrootDomain
*)us
)->handleSleepTimerExpiration();
315 static void wakeupClamshellTimerExpired ( thread_call_param_t us
)
317 ((IOPMrootDomain
*)us
)->stopIgnoringClamshellEventsDuringWakeup();
321 // **********************************************************************************
322 // handleSleepTimerExpiration
324 // The time between the sleep idle timeout and the next longest one has elapsed.
325 // It's time to sleep. Start that by removing the clamp that's holding us awake.
326 // **********************************************************************************
327 void IOPMrootDomain::handleSleepTimerExpiration ( void )
329 // accelerate disk spin down if spin down timer is non-zero (zero = never spin down)
330 if(0 != user_spindown
)
331 setQuickSpinDownTimeout();
338 void IOPMrootDomain::stopIgnoringClamshellEventsDuringWakeup(void)
342 // Allow clamshell-induced sleep now
343 ignoringClamshellDuringWakeup
= false;
345 if ((state
= getProperty(kAppleClamshellStateKey
)))
346 publishResource(kAppleClamshellStateKey
, state
);
349 //*********************************************************************************
352 // Some aggressiveness factor has changed. We put this change on our
353 // command queue so that we can broadcast it to the hierarchy while on
354 // the Power Mangement workloop thread. This enables objects in the
355 // hierarchy to successfully alter their idle timers, which are all on the
357 //*********************************************************************************
359 IOReturn
IOPMrootDomain::setAggressiveness ( unsigned long type
, unsigned long newLevel
)
362 if ( systemBooting
&& (type
== kPMMinutesToDim
) ) {
363 systemBooting
= false; // when the login window launches, this method gets called -- system booting is done.
364 IOLog("Root power domain receiving initial preferences\n");
368 pm_vars
->commandQueue
->enqueueCommand(true, (void *)kIOPMBroadcastAggressiveness
, (void *) type
, (void *) newLevel
);
370 return kIOReturnSuccess
;
374 // **********************************************************************************
377 // **********************************************************************************
378 IOReturn
IOPMrootDomain::sleepSystem ( void )
380 kprintf("sleep demand received\n");
381 if ( !systemBooting
&& allowSleep
&& sleepIsSupported
) {
382 patriarch
->sleepSystem();
383 return kIOReturnSuccess
;
385 if ( !systemBooting
&& allowSleep
&& !sleepIsSupported
) {
386 patriarch
->dozeSystem();
387 return kIOReturnSuccess
;
389 return kIOReturnSuccess
;
393 // **********************************************************************************
396 // **********************************************************************************
397 IOReturn
IOPMrootDomain::shutdownSystem ( void )
399 patriarch
->shutDownSystem();
400 return kIOReturnSuccess
;
404 // **********************************************************************************
407 // **********************************************************************************
408 IOReturn
IOPMrootDomain::restartSystem ( void )
410 patriarch
->restartSystem();
411 return kIOReturnSuccess
;
415 // **********************************************************************************
418 // This overrides powerChangeDone in IOService.
420 // Finder sleep and idle sleep move us from the ON state to the SLEEP_STATE.
422 // If we just finished going to the SLEEP_STATE, and the platform is capable of true sleep,
423 // sleep the kernel. Otherwise switch up to the DOZE_STATE which will keep almost
424 // everything as off as it can get.
426 // **********************************************************************************
427 void IOPMrootDomain::powerChangeDone ( unsigned long previousState
)
429 OSNumber
* propertyPtr
;
430 unsigned short theProperty
;
431 AbsoluteTime deadline
;
433 switch ( pm_vars
->myCurrentState
) {
435 if ( canSleep
&& sleepIsSupported
) {
436 idleSleepPending
= false; // re-enable this timer for next sleep
437 IOLog("System Sleep\n");
438 pm_vars
->thePlatform
->sleepKernel(); // sleep now
441 clock_interval_to_deadline(30, kSecondScale
, &deadline
); // stay awake for at least 30 seconds
442 thread_call_enter_delayed(extraSleepTimer
, deadline
);
443 idleSleepPending
= true; // this gets turned off when we sleep again
445 // Ignore closed clamshell during wakeup and for a few seconds
446 // after wakeup is complete
447 ignoringClamshellDuringWakeup
= true;
449 gSleepOrShutdownPending
= 0; // sleep transition complete
450 patriarch
->wakeSystem(); // get us some power
452 IOLog("System Wake\n");
453 systemWake(); // tell the tree we're waking
455 // Allow drivers to request extra processing time before clamshell
456 // sleep if kIOREMSleepEnabledKey is present.
457 // Ignore clamshell events for at least 5 seconds
458 if(getProperty(kIOREMSleepEnabledKey
)) {
459 // clamshellWakeupIgnore callout clears ignoreClamshellDuringWakeup bit
460 clock_interval_to_deadline(5, kSecondScale
, &deadline
);
461 if(clamshellWakeupIgnore
) thread_call_enter_delayed(clamshellWakeupIgnore
, deadline
);
462 } else ignoringClamshellDuringWakeup
= false;
464 propertyPtr
= OSDynamicCast(OSNumber
,getProperty("WakeEvent"));
465 if ( propertyPtr
) { // find out what woke us
466 theProperty
= propertyPtr
->unsigned16BitValue();
467 IOLog("Wake event %04x\n",theProperty
);
468 if ( (theProperty
== 0x0008) || //lid
469 (theProperty
== 0x0800) || // front panel button
470 (theProperty
== 0x0020) || // external keyboard
471 (theProperty
== 0x0001) ) { // internal keyboard
476 IOLog("Unknown wake event\n");
477 reportUserInput(); // don't know, call it user input then
480 changePowerStateToPriv(ON_STATE
); // wake for thirty seconds
481 powerOverrideOffPriv();
484 patriarch
->sleepToDoze(); // allow us to step up a power state
485 changePowerStateToPriv(DOZE_STATE
); // and do it
490 if ( previousState
!= DOZE_STATE
) {
491 IOLog("System Doze\n");
493 idleSleepPending
= false; // re-enable this timer for next sleep
494 gSleepOrShutdownPending
= 0;
498 IOLog("System Restart\n");
499 PEHaltRestart(kPERestartCPU
);
503 IOLog("System Halt\n");
504 PEHaltRestart(kPEHaltCPU
);
510 // **********************************************************************************
513 // The Display Wrangler calls here when it switches to its highest state. If the
514 // system is currently dozing, allow it to wake by making sure the parent is
516 // **********************************************************************************
517 void IOPMrootDomain::wakeFromDoze( void )
519 if ( pm_vars
->myCurrentState
== DOZE_STATE
) {
520 canSleep
= true; // reset this till next attempt
521 powerOverrideOffPriv();
522 patriarch
->wakeSystem(); // allow us to wake if children so desire
527 // **********************************************************************************
530 // Adds a new feature to the supported features dictionary
533 // **********************************************************************************
534 void IOPMrootDomain::publishFeature( const char * feature
)
536 OSDictionary
*features
= (OSDictionary
*)getProperty(kRootDomainSupportedFeatures
);
538 features
->setObject(feature
, kOSBooleanTrue
);
542 // **********************************************************************************
545 // **********************************************************************************
546 IOReturn
IOPMrootDomain::newUserClient( task_t owningTask
, void * /* security_id */, UInt32 type
, IOUserClient
** handler
)
548 IOReturn err
= kIOReturnSuccess
;
549 RootDomainUserClient
* client
;
551 client
= RootDomainUserClient::withTask(owningTask
);
553 if( !client
|| (false == client
->attach( this )) ||
554 (false == client
->start( this )) ) {
556 client
->detach( this );
560 err
= kIOReturnNoMemory
;
566 //*********************************************************************************
567 // receivePowerNotification
569 // The power controller is notifying us of a hardware-related power management
570 // event that we must handle. This is a result of an 'environment' interrupt from
571 // the power mgt micro.
572 //*********************************************************************************
574 IOReturn
IOPMrootDomain::receivePowerNotification (UInt32 msg
)
576 if (msg
& kIOPMSetDesktopMode
) {
577 desktopMode
= (0 != (msg
& kIOPMSetValue
));
578 msg
&= ~(kIOPMSetDesktopMode
| kIOPMSetValue
);
580 if (msg
& kIOPMSetACAdaptorConnected
) {
581 acAdaptorConnect
= (0 != (msg
& kIOPMSetValue
));
582 msg
&= ~(kIOPMSetACAdaptorConnected
| kIOPMSetValue
);
584 if (msg
& kIOPMEnableClamshell
) {
585 ignoringClamshell
= false;
587 if (msg
& kIOPMDisableClamshell
) {
588 ignoringClamshell
= true;
591 if (msg
& kIOPMProcessorSpeedChange
) {
592 IOService
*pmu
= waitForService(serviceMatching("ApplePMU"));
593 pmu
->callPlatformFunction("prepareForSleep", false, 0, 0, 0, 0);
594 pm_vars
->thePlatform
->sleepKernel();
595 pmu
->callPlatformFunction("recoverFromSleep", false, 0, 0, 0, 0);
598 if (msg
& kIOPMSleepNow
) {
599 (void) sleepSystem ();
602 if (msg
& kIOPMPowerEmergency
) {
603 (void) sleepSystem ();
606 if (msg
& kIOPMOverTemp
) {
607 IOLog("Power Management received emergency overtemp signal. Going to sleep.");
608 (void) sleepSystem ();
611 if (msg
& kIOPMClamshellClosed
) {
612 if ( !ignoringClamshell
&& !ignoringClamshellDuringWakeup
613 && (!desktopMode
|| !acAdaptorConnect
) ) {
615 (void) sleepSystem ();
619 if (msg
& kIOPMPowerButton
) { // toggle state of sleep/wake
620 if ( pm_vars
->myCurrentState
== DOZE_STATE
) { // are we dozing?
621 systemWake(); // yes, tell the tree we're waking
622 reportUserInput(); // wake the Display Wrangler
625 (void) sleepSystem ();
629 // if the case has been closed, we allow
630 // the machine to be put to sleep or to idle sleep
632 if ( (msg
& kIOPMAllowSleep
) && !allowSleep
) {
637 // if the case has been opened, we disallow sleep/doze
639 if (msg
& kIOPMPreventSleep
) {
641 if ( pm_vars
->myCurrentState
== DOZE_STATE
) { // are we dozing?
642 systemWake(); // yes, tell the tree we're waking
644 reportUserInput(); // wake the Display Wrangler
648 patriarch
->wakeSystem(); // make sure we have power to clamp
656 //*********************************************************************************
659 //*********************************************************************************
661 void IOPMrootDomain::setSleepSupported( IOOptionBits flags
)
663 if ( flags
& kPCICantSleep
) {
667 platformSleepSupport
= flags
;
672 //*********************************************************************************
673 // requestPowerDomainState
675 // The root domain intercepts this call to the superclass.
677 // If the clamp bit is not set in the desire, then the child doesn't need the power
678 // state it's requesting; it just wants it. The root ignores desires but not needs.
679 // If the clamp bit is not set, the root takes it that the child can tolerate no
680 // power and interprets the request accordingly. If all children can thus tolerate
681 // no power, we are on our way to idle sleep.
682 //*********************************************************************************
684 IOReturn
IOPMrootDomain::requestPowerDomainState ( IOPMPowerFlags desiredState
, IOPowerConnection
* whichChild
, unsigned long specification
)
688 IOPowerConnection
* connection
;
689 unsigned long powerRequestFlag
= 0;
690 IOPMPowerFlags editedDesire
= desiredState
;
692 if ( !(desiredState
& kIOPMPreventIdleSleep
) ) { // if they don't really need it, they don't get it
697 IOLockLock(pm_vars
->childLock
); // recompute sleepIsSupported
698 // and see if all children are asleep
699 iter
= getChildIterator(gIOPowerPlane
);
700 sleepIsSupported
= true;
703 while ( (next
= iter
->getNextObject()) ) {
704 if ( (connection
= OSDynamicCast(IOPowerConnection
,next
)) ) {
705 if ( connection
== whichChild
) {
706 powerRequestFlag
+= editedDesire
;
707 if ( desiredState
& kIOPMPreventSystemSleep
) {
708 sleepIsSupported
= false;
712 powerRequestFlag
+= connection
->getDesiredDomainState();
713 if ( connection
->getPreventSystemSleepFlag() ) {
714 sleepIsSupported
= false;
722 if ( (extraSleepDelay
== 0) && (powerRequestFlag
== 0) ) {
726 adjustPowerState(); // this may put the system to sleep
728 IOLockUnlock(pm_vars
->childLock
);
730 editedDesire
|= desiredState
& kIOPMPreventSystemSleep
;
732 return super::requestPowerDomainState(editedDesire
,whichChild
,specification
);
736 //*********************************************************************************
739 //*********************************************************************************
741 IOOptionBits
IOPMrootDomain::getSleepSupported( void )
743 return( platformSleepSupport
);
747 //*********************************************************************************
750 // We override the superclass implementation so we can send a different message
751 // type to the client or application being notified.
752 //*********************************************************************************
754 bool IOPMrootDomain::tellChangeDown ( unsigned long stateNum
)
756 switch ( stateNum
) {
759 return super::tellClientsWithResponse(kIOMessageSystemWillSleep
);
761 return super::tellClientsWithResponse(kIOMessageSystemWillRestart
);
763 return super::tellClientsWithResponse(kIOMessageSystemWillPowerOff
);
765 return super::tellChangeDown(stateNum
); // this shouldn't execute
769 //*********************************************************************************
772 // We override the superclass implementation so we can send a different message
773 // type to the client or application being notified.
775 // This must be idle sleep since we don't ask apps during any other power change.
776 //*********************************************************************************
778 bool IOPMrootDomain::askChangeDown ( unsigned long )
780 return super::tellClientsWithResponse(kIOMessageCanSystemSleep
);
784 //*********************************************************************************
787 // Notify registered applications and kernel clients that we are not
790 // We override the superclass implementation so we can send a different message
791 // type to the client or application being notified.
793 // This must be a vetoed idle sleep, since no other power change can be vetoed.
794 //*********************************************************************************
796 void IOPMrootDomain::tellNoChangeDown ( unsigned long )
798 return tellClients(kIOMessageSystemWillNotSleep
);
802 //*********************************************************************************
805 // Notify registered applications and kernel clients that we are raising power.
807 // We override the superclass implementation so we can send a different message
808 // type to the client or application being notified.
809 //*********************************************************************************
811 void IOPMrootDomain::tellChangeUp ( unsigned long stateNum
)
813 if ( stateNum
== ON_STATE
) {
814 return tellClients(kIOMessageSystemHasPoweredOn
);
818 //*********************************************************************************
821 //*********************************************************************************
823 void IOPMrootDomain::reportUserInput ( void )
828 iter
= getMatchingServices(serviceMatching("IODisplayWrangler"));
830 wrangler
= (IOService
*) iter
->getNextObject();
836 wrangler
->activityTickle(0,0);
839 //*********************************************************************************
840 // setQuickSpinDownTimeout
842 //*********************************************************************************
844 void IOPMrootDomain::setQuickSpinDownTimeout ( void )
846 //IOLog("setQuickSpinDownTimeout\n");
847 super::setAggressiveness((unsigned long)kPMMinutesToSpinDown
,(unsigned long)1);
850 //*********************************************************************************
851 // restoreUserSpinDownTimeout
853 //*********************************************************************************
855 void IOPMrootDomain::restoreUserSpinDownTimeout ( void )
857 super::setAggressiveness((unsigned long)kPMMinutesToSpinDown
,(unsigned long)user_spindown
);
861 //*********************************************************************************
862 // sysPowerDownHandler
864 // Receives a notification when the RootDomain changes state.
866 // Allows us to take action on system sleep, power down, and restart after
867 // applications have received their power change notifications and replied,
868 // but before drivers have powered down. We perform a vfs sync on power down.
869 //*********************************************************************************
871 IOReturn
IOPMrootDomain::sysPowerDownHandler( void * target
, void * refCon
,
872 UInt32 messageType
, IOService
* service
,
873 void * messageArgument
, vm_size_t argSize
)
876 IOPowerStateChangeNotification
* params
= (IOPowerStateChangeNotification
*) messageArgument
;
877 IOPMrootDomain
* rootDomain
= OSDynamicCast(IOPMrootDomain
, service
);
880 return kIOReturnUnsupported
;
882 switch (messageType
) {
883 case kIOMessageSystemWillSleep
:
884 rootDomain
->powerOverrideOnPriv(); // start ignoring children's requests
885 // (fall through to other cases)
887 // Interested applications have been notified of an impending power
888 // change and have acked (when applicable).
889 // This is our chance to save whatever state we can before powering
891 // We call sync_internal defined in xnu/bsd/vfs/vfs_syscalls.c,
894 // We will ack within 20 seconds
895 params
->returnValue
= 20 * 1000 * 1000;
897 if ( ! OSCompareAndSwap( 0, 1, &gSleepOrShutdownPending
) )
899 // Purposely delay the ack and hope that shutdown occurs quickly.
900 // Another option is not to schedule the thread and wait for
902 AbsoluteTime deadline
;
903 clock_interval_to_deadline( 15, kSecondScale
, &deadline
);
904 thread_call_enter1_delayed( rootDomain
->diskSyncCalloutEntry
,
905 (thread_call_param_t
)params
->powerRef
,
909 thread_call_enter1(rootDomain
->diskSyncCalloutEntry
, (thread_call_param_t
)params
->powerRef
);
910 ret
= kIOReturnSuccess
;
913 case kIOMessageSystemWillPowerOff
:
914 case kIOMessageSystemWillRestart
:
915 ret
= kIOReturnUnsupported
;
919 ret
= kIOReturnUnsupported
;
925 //*********************************************************************************
926 // displayWranglerNotification
928 // Receives a notification when the IODisplayWrangler changes state.
930 // Allows us to take action on display dim/undim.
932 // When the display goes dim we:
933 // - Start the idle sleep timer
934 // - set the quick spin down timeout
936 // On wake from display dim:
937 // - Cancel the idle sleep timer
938 // - restore the user's chosen spindown timer from the "quick" spin down value
939 //*********************************************************************************
941 IOReturn
IOPMrootDomain::displayWranglerNotification( void * target
, void * refCon
,
942 UInt32 messageType
, IOService
* service
,
943 void * messageArgument
, vm_size_t argSize
)
945 IOPMrootDomain
* rootDomain
= OSDynamicCast(IOPMrootDomain
, (IOService
*)target
);
946 AbsoluteTime deadline
;
947 static bool deviceAlreadyPoweredOff
= false;
950 return kIOReturnUnsupported
;
952 switch (messageType
) {
953 case kIOMessageDeviceWillPowerOff
:
954 // The IODisplayWrangler has powered off either because of idle display sleep
955 // or force system sleep.
957 // The display wrangler will send the DeviceWillPowerOff message 4 times until
958 // it gets into its lowest state. We only want to act on the first of those 4.
959 if( deviceAlreadyPoweredOff
) return kIOReturnUnsupported
;
961 deviceAlreadyPoweredOff
= true;
963 if( rootDomain
->extraSleepDelay
) {
965 // start the extra sleep timer
966 clock_interval_to_deadline(rootDomain
->extraSleepDelay
*60, kSecondScale
, &deadline
);
967 thread_call_enter_delayed(rootDomain
->extraSleepTimer
, deadline
);
968 rootDomain
->idleSleepPending
= true;
972 // accelerate disk spin down if spin down timer is non-zero (zero = never spin down)
973 if(0 != rootDomain
->user_spindown
)
974 rootDomain
->setQuickSpinDownTimeout();
979 case kIOMessageDeviceHasPoweredOn
:
981 // The display has powered on either because of UI activity or wake from sleep/doze
982 deviceAlreadyPoweredOff
= false;
983 rootDomain
->adjustPowerState();
986 // cancel any pending idle sleep
987 if(rootDomain
->idleSleepPending
) {
988 thread_call_cancel(rootDomain
->extraSleepTimer
);
989 rootDomain
->idleSleepPending
= false;
992 // Change the spindown value back to the user's selection from our accelerated setting
993 if(0 != rootDomain
->user_spindown
)
994 rootDomain
->restoreUserSpinDownTimeout();
996 // Put on the policy maker's on clamp.
1003 return kIOReturnUnsupported
;
1006 //*********************************************************************************
1007 // displayWranglerPublished
1009 // Receives a notification when the IODisplayWrangler is published.
1010 // When it's published we install a power state change handler.
1012 //*********************************************************************************
1014 bool IOPMrootDomain::displayWranglerPublished( void * target
, void * refCon
,
1015 IOService
* newService
)
1017 IOPMrootDomain
* rootDomain
= OSDynamicCast(IOPMrootDomain
, (IOService
*)target
);
1022 rootDomain
->wrangler
= newService
;
1024 // we found the display wrangler, now install a handler
1025 if( !rootDomain
->wrangler
->registerInterest( gIOGeneralInterest
, &displayWranglerNotification
, target
, 0) ) {
1026 IOLog("IOPMrootDomain::displayWranglerPublished registerInterest failed\n");
1034 //*********************************************************************************
1037 // Some condition that affects our wake/sleep/doze decision has changed.
1039 // If the sleep slider is in the off position, we cannot sleep or doze.
1040 // If the enclosure is open, we cannot sleep or doze.
1041 // If the system is still booting, we cannot sleep or doze.
1043 // In those circumstances, we prevent sleep and doze by holding power on with
1044 // changePowerStateToPriv(ON).
1046 // If the above conditions do not exist, and also the sleep timer has expired, we
1047 // allow sleep or doze to occur with either changePowerStateToPriv(SLEEP) or
1048 // changePowerStateToPriv(DOZE) depending on whether or not we already know the
1049 // platform cannot sleep.
1051 // In this case, sleep or doze will either occur immediately or at the next time
1052 // that no children are holding the system out of idle sleep via the
1053 // kIOPMPreventIdleSleep flag in their power state arrays.
1054 //*********************************************************************************
1056 void IOPMrootDomain::adjustPowerState( void )
1058 if ( (sleepSlider
== 0) ||
1061 changePowerStateToPriv(ON_STATE
);
1066 if ( sleepIsSupported
) {
1067 changePowerStateToPriv(SLEEP_STATE
);
1070 changePowerStateToPriv(DOZE_STATE
);
1077 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1080 #define super IOService
1082 OSDefineMetaClassAndStructors(IORootParent
, IOService
)
1084 // This array exactly parallels the state array for the root domain.
1085 // Power state changes initiated by a device can be vetoed by a client of the device, and
1086 // power state changes initiated by the parent of a device cannot be vetoed by a client of the device,
1087 // so when the root domain wants a power state change that cannot be vetoed (e.g. demand sleep), it asks
1088 // its parent to make the change. That is the reason for this complexity.
1090 static IOPMPowerState patriarchPowerStates
[number_of_power_states
] = {
1091 {1,0,0,0,0,0,0,0,0,0,0,0}, // off
1092 {1,0,RESTART_POWER
,0,0,0,0,0,0,0,0,0}, // reset
1093 {1,0,SLEEP_POWER
,0,0,0,0,0,0,0,0,0}, // sleep
1094 {1,0,DOZE_POWER
,0,0,0,0,0,0,0,0,0}, // doze
1095 {1,0,ON_POWER
,0,0,0,0,0,0,0,0,0} // running
1098 bool IORootParent::start ( IOService
* nub
)
1100 mostRecentChange
= ON_STATE
;
1103 registerPowerDriver(this,patriarchPowerStates
,number_of_power_states
);
1104 powerOverrideOnPriv();
1109 void IORootParent::shutDownSystem ( void )
1111 mostRecentChange
= OFF_STATE
;
1112 changePowerStateToPriv(OFF_STATE
);
1116 void IORootParent::restartSystem ( void )
1118 mostRecentChange
= RESTART_STATE
;
1119 changePowerStateToPriv(RESTART_STATE
);
1123 void IORootParent::sleepSystem ( void )
1125 mostRecentChange
= SLEEP_STATE
;
1126 changePowerStateToPriv(SLEEP_STATE
);
1130 void IORootParent::dozeSystem ( void )
1132 mostRecentChange
= DOZE_STATE
;
1133 changePowerStateToPriv(DOZE_STATE
);
1136 // Called in demand sleep when sleep discovered to be impossible after actually attaining that state.
1137 // This brings the parent to doze, which allows the root to step up from sleep to doze.
1139 // In idle sleep, do nothing because the parent is still on and the root can freely change state.
1141 void IORootParent::sleepToDoze ( void )
1143 if ( mostRecentChange
== SLEEP_STATE
) {
1144 changePowerStateToPriv(DOZE_STATE
);
1149 void IORootParent::wakeSystem ( void )
1151 mostRecentChange
= ON_STATE
;
1152 changePowerStateToPriv(ON_STATE
);