IOPMrootDomain.cpp [plain text]
#include <IOKit/IOWorkLoop.h>
#include <IOKit/IOCommandGate.h>
#include <IOKit/IOTimerEventSource.h>
#include <IOKit/IOPlatformExpert.h>
#include <IOKit/IOKitDebug.h>
#include <IOKit/IOTimeStamp.h>
#include <IOKit/pwr_mgt/RootDomain.h>
#include <IOKit/pwr_mgt/IOPMPrivate.h>
#include <IOKit/IODeviceTreeSupport.h>
#include <IOKit/IOMessage.h>
#include <IOKit/IOReturn.h>
#include "RootDomainUserClient.h"
#include "IOKit/pwr_mgt/IOPowerConnection.h"
#include "IOPMPowerStateQueue.h"
#include <IOKit/IOCatalogue.h>
#include <IOKit/IOHibernatePrivate.h>
#include "IOPMWorkArbiter.h"
#ifdef __ppc__
#include <ppc/pms.h>
#endif
extern "C" {
IOReturn OSMetaClassSystemSleepOrWake( UInt32 );
}
extern const IORegistryPlane * gIOPowerPlane;
IOReturn broadcast_aggressiveness ( OSObject *, void *, void *, void *, void * );
static void sleepTimerExpired(thread_call_param_t);
static void wakeupClamshellTimerExpired ( thread_call_param_t us);
static const OSSymbol *sleepSupportedPEFunction = NULL;
#define kIOSleepSupportedKey "IOSleepSupported"
#define kRD_AllPowerSources (kIOPMSupportedOnAC \
| kIOPMSupportedOnBatt \
| kIOPMSupportedOnUPS)
#define number_of_power_states 5
#define OFF_STATE 0
#define RESTART_STATE 1
#define SLEEP_STATE 2
#define DOZE_STATE 3
#define ON_STATE 4
#define ON_POWER kIOPMPowerOn
#define RESTART_POWER kIOPMRestart
#define SLEEP_POWER kIOPMAuxPowerOn
#define DOZE_POWER kIOPMDoze
#define kLocalEvalClamshellCommand (1 << 15)
static IOPMPowerState ourPowerStates[number_of_power_states] = {
{1,0, 0, 0,0,0,0,0,0,0,0,0},
{1,kIOPMRestartCapability, kIOPMRestart, RESTART_POWER,0,0,0,0,0,0,0,0},
{1,kIOPMSleepCapability, kIOPMSleep, SLEEP_POWER,0,0,0,0,0,0,0,0},
{1,kIOPMDoze, kIOPMDoze, DOZE_POWER,0,0,0,0,0,0,0,0},
{1,kIOPMPowerOn, kIOPMPowerOn, ON_POWER,0,0,0,0,0,0,0,0},
};
static IOPMrootDomain * gRootDomain;
static UInt32 gSleepOrShutdownPending = 0;
class PMSettingObject : public OSObject
{
OSDeclareDefaultStructors(PMSettingObject)
private:
IOPMrootDomain *parent;
IOPMSettingControllerCallback func;
OSObject *target;
uintptr_t refcon;
uint32_t *publishedFeatureID;
int releaseAtCount;
public:
static PMSettingObject *pmSettingObject(
IOPMrootDomain *parent_arg,
IOPMSettingControllerCallback handler_arg,
OSObject *target_arg,
uintptr_t refcon_arg,
uint32_t supportedPowerSources,
const OSSymbol *settings[]);
void setPMSetting(const OSSymbol *type, OSObject *obj);
void taggedRelease(const void *tag, const int when) const;
void free(void);
};
#define super IOService
OSDefineMetaClassAndStructors(IOPMrootDomain,IOService)
extern "C"
{
IONotifier * registerSleepWakeInterest(IOServiceInterestHandler handler, void * self, void * ref)
{
return gRootDomain->registerInterest( gIOGeneralInterest, handler, self, ref );
}
IONotifier * registerPrioritySleepWakeInterest(IOServiceInterestHandler handler, void * self, void * ref)
{
return gRootDomain->registerInterest( gIOPriorityPowerStateInterest, handler, self, ref );
}
IOReturn acknowledgeSleepWakeNotification(void * PMrefcon)
{
return gRootDomain->allowPowerChange ( (unsigned long)PMrefcon );
}
IOReturn vetoSleepWakeNotification(void * PMrefcon)
{
return gRootDomain->cancelPowerChange ( (unsigned long)PMrefcon );
}
IOReturn rootDomainRestart ( void )
{
return gRootDomain->restartSystem();
}
IOReturn rootDomainShutdown ( void )
{
return gRootDomain->shutdownSystem();
}
void IOSystemShutdownNotification ( void )
{
IOCatalogue::disableExternalLinker();
for ( int i = 0; i < 100; i++ )
{
if ( OSCompareAndSwap( 0, 1, &gSleepOrShutdownPending ) ) break;
IOSleep( 100 );
}
}
int sync_internal(void);
}
IOPMrootDomain * IOPMrootDomain::construct( void )
{
IOPMrootDomain *root;
root = new IOPMrootDomain;
if( root)
root->init();
return( root );
}
static void disk_sync_callout(thread_call_param_t p0, thread_call_param_t p1)
{
IOService *rootDomain = (IOService *) p0;
unsigned long pmRef = (unsigned long) p1;
IOHibernateSystemSleep();
sync_internal();
rootDomain->allowPowerChange(pmRef);
}
IOPMWorkArbiter *IOPMrootDomain::getPMArbiter(void)
{
return pmArbiter;
}
#define kRootDomainSettingsCount 13
bool IOPMrootDomain::start ( IOService * nub )
{
OSIterator *psIterator;
OSDictionary *tmpDict;
const OSSymbol *settingsArr[kRootDomainSettingsCount] =
{
OSSymbol::withCString(kIOPMSettingSleepOnPowerButtonKey),
OSSymbol::withCString(kIOPMSettingAutoWakeSecondsKey),
OSSymbol::withCString(kIOPMSettingAutoPowerSecondsKey),
OSSymbol::withCString(kIOPMSettingAutoWakeCalendarKey),
OSSymbol::withCString(kIOPMSettingAutoPowerCalendarKey),
OSSymbol::withCString(kIOPMSettingDebugWakeRelativeKey),
OSSymbol::withCString(kIOPMSettingDebugPowerRelativeKey),
OSSymbol::withCString(kIOPMSettingWakeOnRingKey),
OSSymbol::withCString(kIOPMSettingRestartOnPowerLossKey),
OSSymbol::withCString(kIOPMSettingWakeOnClamshellKey),
OSSymbol::withCString(kIOPMSettingWakeOnACChangeKey),
OSSymbol::withCString(kIOPMSettingTimeZoneOffsetKey),
OSSymbol::withCString(kIOPMSettingMobileMotionModuleKey)
};
pmPowerStateQueue = 0;
_reserved = (ExpansionData *)IOMalloc(sizeof(ExpansionData));
if(!_reserved) return false;
super::start(nub);
gRootDomain = this;
PMinit();
sleepSupportedPEFunction = OSSymbol::withCString("IOPMSetSleepSupported");
canSleep = true;
setProperty(kIOSleepSupportedKey,true);
allowSleep = true;
sleepIsSupported = true;
systemBooting = true;
sleepSlider = 0;
idleSleepPending = false;
wrangler = NULL;
sleepASAP = false;
clamshellIsClosed = false;
clamshellExists = false;
ignoringClamshell = true;
ignoringClamshellDuringWakeup = false;
acAdaptorConnect = true;
tmpDict = OSDictionary::withCapacity(1);
setProperty(kRootDomainSupportedFeatures, tmpDict);
tmpDict->release();
settingsCallbacks = OSDictionary::withCapacity(1);
allowedPMSettings = OSArray::withObjects(
(const OSObject **)settingsArr,
kRootDomainSettingsCount,
0);
fPMSettingsDict = OSDictionary::withCapacity(5);
pm_vars->PMworkloop = IOWorkLoop::workLoop();
pmPowerStateQueue = IOPMPowerStateQueue::PMPowerStateQueue(this);
pm_vars->PMworkloop->addEventSource(pmPowerStateQueue);
pmArbiter = IOPMWorkArbiter::pmWorkArbiter(this);
arbiterWorkLoop = IOWorkLoop::workLoop();
arbiterWorkLoop->addEventSource(pmArbiter);
featuresDictLock = IOLockAlloc();
settingsCtrlLock = IORecursiveLockAlloc();
extraSleepTimer = thread_call_allocate(
(thread_call_func_t)sleepTimerExpired,
(thread_call_param_t) this);
clamshellWakeupIgnore = thread_call_allocate(
(thread_call_func_t)wakeupClamshellTimerExpired,
(thread_call_param_t) this);
diskSyncCalloutEntry = thread_call_allocate(
&disk_sync_callout,
(thread_call_param_t) this);
patriarch = new IORootParent;
patriarch->init();
patriarch->attach(this);
patriarch->start(this);
patriarch->youAreRoot();
patriarch->wakeSystem();
patriarch->addPowerChild(this);
registerPowerDriver(this,ourPowerStates,number_of_power_states);
setPMRootDomain(this);
changePowerStateToPriv(ON_STATE);
registerPrioritySleepWakeInterest( &sysPowerDownHandler, this, 0);
_displayWranglerNotifier = addNotification(
gIOPublishNotification, serviceMatching("IODisplayWrangler"),
&displayWranglerPublished, this, 0);
_batteryPublishNotifier = addNotification(
gIOPublishNotification, serviceMatching("IOPMPowerSource"),
&batteryPublished, this, this);
const OSSymbol *ucClassName = OSSymbol::withCStringNoCopy("RootDomainUserClient");
setProperty(gIOUserClientClassKey, (OSObject *) ucClassName);
ucClassName->release();
psIterator = getMatchingServices( serviceMatching("IOPMPowerSource") );
if( psIterator && psIterator->getNextObject() )
{
publishFeature("DisplayDims");
}
if(psIterator) {
psIterator->release();
}
IOHibernateSystemInit(this);
registerService();
return true;
}
IOReturn IOPMrootDomain::setProperties ( OSObject *props_obj)
{
IOReturn return_value = kIOReturnSuccess;
OSDictionary *dict = OSDynamicCast(OSDictionary, props_obj);
OSBoolean *b;
OSNumber *n;
OSString *str;
OSSymbol *type;
OSObject *obj;
unsigned int i;
const OSSymbol *boot_complete_string =
OSSymbol::withCString("System Boot Complete");
const OSSymbol *sys_shutdown_string =
OSSymbol::withCString("System Shutdown");
const OSSymbol *stall_halt_string =
OSSymbol::withCString("StallSystemAtHalt");
const OSSymbol *hibernatemode_string =
OSSymbol::withCString(kIOHibernateModeKey);
const OSSymbol *hibernatefile_string =
OSSymbol::withCString(kIOHibernateFileKey);
const OSSymbol *hibernatefreeratio_string =
OSSymbol::withCString(kIOHibernateFreeRatioKey);
const OSSymbol *hibernatefreetime_string =
OSSymbol::withCString(kIOHibernateFreeTimeKey);
if(!dict)
{
return_value = kIOReturnBadArgument;
goto exit;
}
if( systemBooting
&& boot_complete_string
&& dict->getObject(boot_complete_string))
{
systemBooting = false;
adjustPowerState();
if( clamshellIsClosed )
{
this->receivePowerNotification(kLocalEvalClamshellCommand);
}
}
if( sys_shutdown_string
&& (b = OSDynamicCast(OSBoolean, dict->getObject(sys_shutdown_string))))
{
if(kOSBooleanTrue == b)
{
kprintf("systemShutdown true\n");
systemShutdown = true;
} else {
kprintf("systemShutdown false\n");
systemShutdown = false;
}
}
if( stall_halt_string
&& (b = OSDynamicCast(OSBoolean, dict->getObject(stall_halt_string))) )
{
setProperty(stall_halt_string, b);
}
if ( hibernatemode_string
&& (n = OSDynamicCast(OSNumber, dict->getObject(hibernatemode_string))))
{
setProperty(hibernatemode_string, n);
}
if ( hibernatefreeratio_string
&& (n = OSDynamicCast(OSNumber, dict->getObject(hibernatefreeratio_string))))
{
setProperty(hibernatefreeratio_string, n);
}
if ( hibernatefreetime_string
&& (n = OSDynamicCast(OSNumber, dict->getObject(hibernatefreetime_string))))
{
setProperty(hibernatefreetime_string, n);
}
if ( hibernatefile_string
&& (str = OSDynamicCast(OSString, dict->getObject(hibernatefile_string))))
{
setProperty(hibernatefile_string, str);
}
for(i = 0; i < allowedPMSettings->getCount(); i++) {
type = (OSSymbol *)allowedPMSettings->getObject(i);
if(!type) continue;
obj = dict->getObject(type);
if(!obj) continue;
return_value = setPMSetting(type, obj);
if(kIOReturnSuccess != return_value) goto exit;
}
exit:
if(boot_complete_string) boot_complete_string->release();
if(stall_halt_string) stall_halt_string->release();
return return_value;
}
IOReturn IOPMrootDomain::youAreRoot ( void )
{
return IOPMNoErr;
}
void IOPMrootDomain::command_received ( void * w, void * x, void * y, void * z )
{
super::command_received(w,x,y,z);
}
IOReturn broadcast_aggressiveness ( OSObject * root, void * x, void * y, void *, void * )
{
((IOPMrootDomain *)root)->broadcast_it((unsigned long)x,(unsigned long)y);
return IOPMNoErr;
}
void IOPMrootDomain::broadcast_it (unsigned long type, unsigned long value)
{
super::setAggressiveness(type,value);
if( type == kPMMinutesToSpinDown ) user_spindown = value;
longestNonSleepSlider = pm_vars->current_aggressiveness_values[kPMMinutesToDim];
if ( type == kPMMinutesToSleep ) {
if ( (sleepSlider == 0) && (value != 0) ) {
sleepSlider = value;
adjustPowerState();
}
sleepSlider = value;
if ( sleepSlider == 0 ) {
adjustPowerState();
patriarch->wakeSystem();
}
}
if ( sleepSlider > longestNonSleepSlider ) {
extraSleepDelay = sleepSlider - longestNonSleepSlider ;
}
else {
extraSleepDelay = 0;
}
}
static void sleepTimerExpired ( thread_call_param_t us)
{
((IOPMrootDomain *)us)->handleSleepTimerExpiration();
}
static void wakeupClamshellTimerExpired ( thread_call_param_t us)
{
((IOPMrootDomain *)us)->stopIgnoringClamshellEventsDuringWakeup();
}
void IOPMrootDomain::handleSleepTimerExpiration ( void )
{
if(0 != user_spindown)
setQuickSpinDownTimeout();
sleepASAP = true;
adjustPowerState();
}
void IOPMrootDomain::stopIgnoringClamshellEventsDuringWakeup(void)
{
ignoringClamshellDuringWakeup = false;
if(clamshellIsClosed)
this->receivePowerNotification( kLocalEvalClamshellCommand );
}
static int pmsallsetup = 0;
IOReturn IOPMrootDomain::setAggressiveness ( unsigned long type, unsigned long newLevel )
{
#ifdef __ppc__
if(pmsExperimental & 3) kprintf("setAggressiveness: type = %08X, newlevel = %08X\n", type, newLevel);
if(pmsExperimental & 1) {
if(pmsInstalled && (type == kPMSetProcessorSpeed)) {
if(pmsallsetup) return kIOReturnSuccess;
kprintf("setAggressiveness: starting stepper...\n");
pmsallsetup = 1;
pmsPark();
pmsStart();
return kIOReturnSuccess;
}
}
#endif
if ( pm_vars->PMcommandGate ) {
pm_vars->PMcommandGate->runAction(broadcast_aggressiveness,(void *)type,(void *)newLevel);
}
return kIOReturnSuccess;
}
IOReturn IOPMrootDomain::sleepSystem ( void )
{
if(systemShutdown) {
kprintf("Preventing system sleep on grounds of systemShutdown.\n");
}
if ( !systemBooting && !systemShutdown && allowSleep && sleepIsSupported ) {
patriarch->sleepSystem();
return kIOReturnSuccess;
}
if ( !systemBooting && !systemShutdown && allowSleep && !sleepIsSupported ) {
patriarch->dozeSystem();
return kIOReturnSuccess;
}
return kIOReturnError;
}
IOReturn IOPMrootDomain::shutdownSystem ( void )
{
return kIOReturnUnsupported;
}
IOReturn IOPMrootDomain::restartSystem ( void )
{
return kIOReturnUnsupported;
}
void IOPMrootDomain::powerChangeDone ( unsigned long previousState )
{
OSNumber * propertyPtr;
unsigned short theProperty;
AbsoluteTime deadline;
switch ( pm_vars->myCurrentState ) {
case SLEEP_STATE:
if ( canSleep && sleepIsSupported )
{
idleSleepPending = false;
IOLog("System %sSleep\n", gIOHibernateState ? "Safe" : "");
IOHibernateSystemHasSlept();
pm_vars->thePlatform->sleepKernel();
IOHibernateSystemWake();
clock_interval_to_deadline(30, kSecondScale, &deadline);
thread_call_enter_delayed(extraSleepTimer, deadline);
idleSleepPending = true;
ignoringClamshellDuringWakeup = true;
gSleepOrShutdownPending = 0;
clock_wakeup_calendar();
patriarch->wakeSystem();
tellClients(kIOMessageSystemWillPowerOn);
IOLog("System %sWake\n", gIOHibernateState ? "SafeSleep " : "");
systemWake();
if(getProperty(kIOREMSleepEnabledKey)) {
clock_interval_to_deadline(5, kSecondScale, &deadline);
if(clamshellWakeupIgnore) {
thread_call_enter_delayed(clamshellWakeupIgnore, deadline);
}
} else ignoringClamshellDuringWakeup = false;
propertyPtr = OSDynamicCast(OSNumber,getProperty("WakeEvent"));
if ( propertyPtr ) {
theProperty = propertyPtr->unsigned16BitValue();
IOLog("Wake event %04x\n",theProperty);
if ( (theProperty & 0x0008) || (theProperty & 0x0800) || (theProperty & 0x0020) || (theProperty & 0x0001) ) { reportUserInput();
}
} else {
reportUserInput();
}
changePowerStateToPriv(ON_STATE);
powerOverrideOffPriv();
} else {
patriarch->sleepToDoze();
changePowerStateToPriv(DOZE_STATE);
}
break;
case DOZE_STATE:
if ( previousState != DOZE_STATE )
{
IOLog("System Doze\n");
}
idleSleepPending = false;
gSleepOrShutdownPending = 0;
break;
case RESTART_STATE:
IOLog("System Restart\n");
PEHaltRestart(kPERestartCPU);
break;
case OFF_STATE:
IOLog("System Halt\n");
PEHaltRestart(kPEHaltCPU);
break;
}
}
void IOPMrootDomain::wakeFromDoze( void )
{
if ( pm_vars->myCurrentState == DOZE_STATE )
{
setSleepSupported(0);
powerOverrideOffPriv();
tellClients(kIOMessageSystemWillPowerOn);
patriarch->wakeSystem();
}
}
void IOPMrootDomain::publishFeature( const char * feature )
{
publishFeature(feature, kIOPMSupportedOnAC
| kIOPMSupportedOnBatt
| kIOPMSupportedOnUPS,
NULL);
return;
}
void IOPMrootDomain::publishFeature(
const char *feature,
uint32_t supportedWhere,
uint32_t *uniqueFeatureID)
{
static uint16_t next_feature_id = 500;
OSNumber *new_feature_data = NULL;
OSNumber *existing_feature = NULL;
OSArray *existing_feature_arr = NULL;
OSObject *osObj = NULL;
uint32_t feature_value = 0;
supportedWhere &= kRD_AllPowerSources;
if(!supportedWhere) {
return;
}
if(next_feature_id > 5000) {
return;
}
if(featuresDictLock) IOLockLock(featuresDictLock);
OSDictionary *features =
(OSDictionary *) getProperty(kRootDomainSupportedFeatures);
if ( features && OSDynamicCast(OSDictionary, features)) {
features = OSDictionary::withDictionary(features);
} else {
features = OSDictionary::withCapacity(1);
}
next_feature_id += 1;
if( uniqueFeatureID ) {
*uniqueFeatureID = next_feature_id;
}
feature_value = supportedWhere + (next_feature_id << 16);
new_feature_data = OSNumber::withNumber(
(unsigned long long)feature_value, 32);
if( (osObj = features->getObject(feature)) )
{
if(( existing_feature = OSDynamicCast(OSNumber, osObj) ))
{
existing_feature_arr = OSArray::withObjects(
(const OSObject **)&existing_feature, 1, 2);
existing_feature_arr->setObject(new_feature_data);
features->setObject(feature, existing_feature_arr);
} else if(( existing_feature_arr = OSDynamicCast(OSArray, osObj) ))
{
existing_feature_arr->setObject(new_feature_data);
}
} else {
features->setObject(feature, new_feature_data);
}
new_feature_data->release();
setProperty(kRootDomainSupportedFeatures, features);
features->release();
messageClients(kIOPMMessageFeatureChange, this);
if(featuresDictLock) IOLockUnlock(featuresDictLock);
}
IOReturn IOPMrootDomain::removePublishedFeature( uint32_t removeFeatureID )
{
IOReturn ret = kIOReturnError;
uint32_t feature_value = 0;
uint16_t feature_id = 0;
bool madeAChange = false;
OSSymbol *dictKey = NULL;
OSCollectionIterator *dictIterator = NULL;
OSArray *arrayMember = NULL;
OSNumber *numberMember = NULL;
OSObject *osObj = NULL;
OSNumber *osNum = NULL;
if(featuresDictLock) IOLockLock(featuresDictLock);
OSDictionary *features =
(OSDictionary *) getProperty(kRootDomainSupportedFeatures);
if ( features && OSDynamicCast(OSDictionary, features) )
{
features = OSDictionary::withDictionary(features);
} else {
features = NULL;
ret = kIOReturnNotFound;
goto exit;
}
dictIterator = OSCollectionIterator::withCollection(features);
if(!dictIterator) {
goto exit;
}
while( (dictKey = OSDynamicCast(OSSymbol, dictIterator->getNextObject())) )
{
osObj = features->getObject(dictKey);
if( osObj && (numberMember = OSDynamicCast(OSNumber, osObj)) )
{
feature_value = numberMember->unsigned32BitValue();
feature_id = (uint16_t)(feature_value >> 16);
if( feature_id == (uint16_t)removeFeatureID )
{
features->removeObject(dictKey);
madeAChange = true;
break;
}
} else if( osObj && (arrayMember = OSDynamicCast(OSArray, osObj)) )
{
unsigned int arrayCount = arrayMember->getCount();
for(unsigned int i=0; i<arrayCount; i++)
{
osNum = OSDynamicCast(OSNumber, arrayMember->getObject(i));
if(!osNum) {
continue;
}
feature_value = osNum->unsigned32BitValue();
feature_id = (uint16_t)(feature_value >> 16);
if( feature_id == (uint16_t)removeFeatureID )
{
if( 1 == arrayCount ) {
features->removeObject(dictKey);
} else {
arrayMember->removeObject(i);
}
madeAChange = true;
break;
}
}
}
}
dictIterator->release();
if( madeAChange )
{
ret = kIOReturnSuccess;
setProperty(kRootDomainSupportedFeatures, features);
messageClients(kIOPMMessageFeatureChange, this);
} else {
ret = kIOReturnNotFound;
}
exit:
if(features) features->release();
if(featuresDictLock) IOLockUnlock(featuresDictLock);
return ret;
}
void IOPMrootDomain::unIdleDevice( IOService *theDevice, unsigned long theState )
{
if(pmPowerStateQueue)
pmPowerStateQueue->unIdleOccurred(theDevice, theState);
}
void IOPMrootDomain::announcePowerSourceChange( void )
{
IORegistryEntry *_batteryRegEntry = (IORegistryEntry *) getProperty("BatteryEntry");
if(_batteryRegEntry)
{
OSArray *batt_info;
batt_info = (OSArray *) _batteryRegEntry->getProperty(kIOBatteryInfoKey);
if(batt_info)
setProperty(kIOBatteryInfoKey, batt_info);
}
}
IOReturn IOPMrootDomain::setPMSetting(
const OSSymbol *type,
OSObject *obj)
{
OSArray *arr = NULL;
PMSettingObject *p_obj = NULL;
int count;
int i;
if(NULL == type) return kIOReturnBadArgument;
IORecursiveLockLock(settingsCtrlLock);
fPMSettingsDict->setObject(type, obj);
arr = (OSArray *)settingsCallbacks->getObject(type);
if(NULL == arr) goto exit;
count = arr->getCount();
for(i=0; i<count; i++) {
p_obj = (PMSettingObject *)OSDynamicCast(PMSettingObject, arr->getObject(i));
if(p_obj) p_obj->setPMSetting(type, obj);
}
exit:
IORecursiveLockUnlock(settingsCtrlLock);
return kIOReturnSuccess;
}
OSObject * IOPMrootDomain::copyPMSetting(
OSSymbol *whichSetting)
{
OSObject *obj = NULL;
if(!whichSetting) return NULL;
IORecursiveLockLock(settingsCtrlLock);
obj = fPMSettingsDict->getObject(whichSetting);
if(obj) {
obj->retain();
}
IORecursiveLockUnlock(settingsCtrlLock);
return obj;
}
IOReturn IOPMrootDomain::registerPMSettingController(
const OSSymbol * settings[],
IOPMSettingControllerCallback func,
OSObject *target,
uintptr_t refcon,
OSObject **handle)
{
return registerPMSettingController(
settings,
(kIOPMSupportedOnAC | kIOPMSupportedOnBatt | kIOPMSupportedOnUPS),
func, target, refcon, handle);
}
IOReturn IOPMrootDomain::registerPMSettingController(
const OSSymbol * settings[],
uint32_t supportedPowerSources,
IOPMSettingControllerCallback func,
OSObject *target,
uintptr_t refcon,
OSObject **handle)
{
PMSettingObject *pmso = NULL;
OSArray *list = NULL;
IOReturn ret = kIOReturnSuccess;
int i;
if( NULL == settings ||
NULL == func ||
NULL == handle)
{
return kIOReturnBadArgument;
}
pmso = PMSettingObject::pmSettingObject(
(IOPMrootDomain *)this, func, target,
refcon, supportedPowerSources, settings);
if(!pmso) {
ret = kIOReturnInternalError;
goto bail_no_unlock;
}
IORecursiveLockLock(settingsCtrlLock);
for(i=0; settings[i]; i++)
{
list = (OSArray *)settingsCallbacks->getObject(settings[i]);
if(!list) {
list = OSArray::withCapacity(1);
settingsCallbacks->setObject(settings[i], list);
list->release();
}
list->setObject(pmso);
}
ret = kIOReturnSuccess;
*handle = pmso;
IORecursiveLockUnlock(settingsCtrlLock);
bail_no_unlock:
if(kIOReturnSuccess != ret)
{
if(pmso) pmso->release();
if(handle) *handle = NULL;
}
return ret;
}
bool IOPMrootDomain::shouldSleepOnClamshellClosed ( void )
{
return ( !ignoringClamshell
&& !ignoringClamshellDuringWakeup
&& !(desktopMode && acAdaptorConnect) );
}
void IOPMrootDomain::sendClientClamshellNotification ( void )
{
if(!clamshellExists)
return;
setProperty(kAppleClamshellStateKey,
clamshellIsClosed ? kOSBooleanTrue : kOSBooleanFalse);
setProperty(kAppleClamshellCausesSleepKey,
shouldSleepOnClamshellClosed() ? kOSBooleanTrue : kOSBooleanFalse);
pmArbiter->clamshellStateChangeOccurred(
(uint32_t) ( (clamshellIsClosed ? kClamshellStateBit : 0)
| ( shouldSleepOnClamshellClosed() ? kClamshellSleepBit : 0)));
}
IOReturn IOPMrootDomain::receivePowerNotification (UInt32 msg)
{
bool eval_clamshell = false;
if (msg & kLocalEvalClamshellCommand)
{
eval_clamshell = true;
}
if (msg & kIOPMOverTemp)
{
IOLog("PowerManagement emergency overtemp signal. Going to sleep!");
(void) sleepSystem ();
}
if (msg & kIOPMProcessorSpeedChange)
{
IOService *pmu = waitForService(serviceMatching("ApplePMU"));
pmu->callPlatformFunction("prepareForSleep", false, 0, 0, 0, 0);
pm_vars->thePlatform->sleepKernel();
pmu->callPlatformFunction("recoverFromSleep", false, 0, 0, 0, 0);
}
if (msg & kIOPMSleepNow)
{
(void) sleepSystem ();
}
if (msg & kIOPMPowerEmergency)
{
(void) sleepSystem ();
}
if (msg & kIOPMClamshellOpened)
{
clamshellIsClosed = false;
clamshellExists = true;
sendClientClamshellNotification();
}
if (msg & kIOPMClamshellClosed)
{
clamshellIsClosed = true;
clamshellExists = true;
sendClientClamshellNotification();
eval_clamshell = true;
}
if (msg & kIOPMSetDesktopMode)
{
desktopMode = (0 != (msg & kIOPMSetValue));
msg &= ~(kIOPMSetDesktopMode | kIOPMSetValue);
sendClientClamshellNotification();
if( clamshellIsClosed )
{
eval_clamshell = true;
}
}
if (msg & kIOPMSetACAdaptorConnected)
{
acAdaptorConnect = (0 != (msg & kIOPMSetValue));
msg &= ~(kIOPMSetACAdaptorConnected | kIOPMSetValue);
sendClientClamshellNotification();
if( clamshellIsClosed )
{
eval_clamshell = true;
}
}
if (msg & kIOPMEnableClamshell)
{
if( clamshellIsClosed && (true == ignoringClamshell) )
{
eval_clamshell = true;
}
ignoringClamshell = false;
sendClientClamshellNotification();
}
if (msg & kIOPMDisableClamshell)
{
ignoringClamshell = true;
sendClientClamshellNotification();
}
if ( eval_clamshell && shouldSleepOnClamshellClosed() )
{
sleepSystem();
}
if (msg & kIOPMPowerButton)
{
if ( pm_vars->myCurrentState == DOZE_STATE )
{
systemWake();
reportUserInput();
}
else {
OSString *pbs = OSString::withCString("DisablePowerButtonSleep");
if( pbs ) {
if( kOSBooleanTrue != getProperty(pbs))
sleepSystem();
}
}
}
if ( (msg & kIOPMAllowSleep) && !allowSleep )
{
allowSleep = true;
adjustPowerState();
}
if (msg & kIOPMPreventSleep) {
allowSleep = false;
if ( pm_vars->myCurrentState == DOZE_STATE ) {
systemWake();
adjustPowerState();
reportUserInput();
} else {
adjustPowerState();
patriarch->wakeSystem();
}
}
return 0;
}
void IOPMrootDomain::setSleepSupported( IOOptionBits flags )
{
if ( flags & kPCICantSleep )
{
canSleep = false;
} else {
canSleep = true;
platformSleepSupport = flags;
}
setProperty(kIOSleepSupportedKey, canSleep);
}
IOReturn IOPMrootDomain::requestPowerDomainState ( IOPMPowerFlags desiredState, IOPowerConnection * whichChild, unsigned long specification )
{
OSIterator *iter;
OSObject *next;
IOPowerConnection *connection;
unsigned long powerRequestFlag = 0;
IOPMPowerFlags editedDesire = desiredState;
if ( !(desiredState & kIOPMPreventIdleSleep) ) {
editedDesire = 0;
}
IOLockLock(pm_vars->childLock);
iter = getChildIterator(gIOPowerPlane);
sleepIsSupported = true;
if ( iter )
{
while ( (next = iter->getNextObject()) )
{
if ( (connection = OSDynamicCast(IOPowerConnection,next)) )
{
if ( connection == whichChild )
{
powerRequestFlag += editedDesire;
if ( desiredState & kIOPMPreventSystemSleep )
{
sleepIsSupported = false;
}
} else {
powerRequestFlag += connection->getDesiredDomainState();
if ( connection->getPreventSystemSleepFlag() )
{
sleepIsSupported = false;
}
}
}
}
iter->release();
}
if ( (extraSleepDelay == 0) && (powerRequestFlag == 0) )
{
sleepASAP = true;
}
adjustPowerState();
IOLockUnlock(pm_vars->childLock);
editedDesire |= desiredState & kIOPMPreventSystemSleep;
return super::requestPowerDomainState(editedDesire,whichChild,specification);
}
IOOptionBits IOPMrootDomain::getSleepSupported( void )
{
return( platformSleepSupport );
}
bool IOPMrootDomain::tellChangeDown ( unsigned long stateNum )
{
switch ( stateNum ) {
case DOZE_STATE:
case SLEEP_STATE:
OSMetaClassSystemSleepOrWake( kIOMessageSystemWillSleep );
return super::tellClientsWithResponse(kIOMessageSystemWillSleep);
case RESTART_STATE:
super::tellClients(iokit_common_msg(0x759));
return super::tellClientsWithResponse(kIOMessageSystemWillRestart);
case OFF_STATE:
super::tellClients(iokit_common_msg(0x749));
return super::tellClientsWithResponse(kIOMessageSystemWillPowerOff);
}
return super::tellChangeDown(stateNum);
}
bool IOPMrootDomain::askChangeDown ( unsigned long )
{
return super::tellClientsWithResponse(kIOMessageCanSystemSleep);
}
void IOPMrootDomain::tellNoChangeDown ( unsigned long )
{
return tellClients(kIOMessageSystemWillNotSleep);
}
void IOPMrootDomain::tellChangeUp ( unsigned long stateNum)
{
if ( stateNum == ON_STATE )
{
OSMetaClassSystemSleepOrWake( kIOMessageSystemHasPoweredOn );
IOHibernateSystemPostWake();
return tellClients(kIOMessageSystemHasPoweredOn);
}
}
void IOPMrootDomain::reportUserInput ( void )
{
OSIterator * iter;
if(!wrangler)
{
iter = getMatchingServices(serviceMatching("IODisplayWrangler"));
if(iter)
{
wrangler = (IOService *) iter->getNextObject();
iter->release();
}
}
if(wrangler)
wrangler->activityTickle(0,0);
}
void IOPMrootDomain::setQuickSpinDownTimeout ( void )
{
super::setAggressiveness((unsigned long)kPMMinutesToSpinDown,(unsigned long)1);
}
void IOPMrootDomain::restoreUserSpinDownTimeout ( void )
{
super::setAggressiveness((unsigned long)kPMMinutesToSpinDown,(unsigned long)user_spindown);
}
IOReturn IOPMrootDomain::changePowerStateTo ( unsigned long ordinal )
{
return super::changePowerStateTo(ordinal);
}
IOReturn IOPMrootDomain::changePowerStateToPriv ( unsigned long ordinal )
{
IOReturn ret;
if( (systemBooting || systemShutdown) && (ordinal == SLEEP_STATE) )
{
kprintf("DANGER DANGER DANGER unexpected code path. aborting SLEEPSTATE change.\n");
super::changePowerStateToPriv(ON_STATE);
}
if( (SLEEP_STATE == ordinal) && sleepSupportedPEFunction )
{
ret = getPlatform()->callPlatformFunction(
sleepSupportedPEFunction, false,
NULL, NULL, NULL, NULL);
}
return super::changePowerStateToPriv(ordinal);
}
IOReturn IOPMrootDomain::sysPowerDownHandler( void * target, void * refCon,
UInt32 messageType, IOService * service,
void * messageArgument, vm_size_t argSize )
{
IOReturn ret;
IOPowerStateChangeNotification *params = (IOPowerStateChangeNotification *) messageArgument;
IOPMrootDomain *rootDomain = OSDynamicCast(IOPMrootDomain, service);
if(!rootDomain)
return kIOReturnUnsupported;
switch (messageType) {
case kIOMessageSystemWillSleep:
rootDomain->powerOverrideOnPriv();
params->returnValue = 20 * 1000 * 1000;
if (gIOHibernateState)
params->returnValue += gIOHibernateFreeTime * 1000;
if ( ! OSCompareAndSwap( 0, 1, &gSleepOrShutdownPending ) )
{
AbsoluteTime deadline;
clock_interval_to_deadline( 30, kSecondScale, &deadline );
thread_call_enter1_delayed( rootDomain->diskSyncCalloutEntry,
(thread_call_param_t)params->powerRef,
deadline );
}
else
thread_call_enter1(rootDomain->diskSyncCalloutEntry, (thread_call_param_t)params->powerRef);
ret = kIOReturnSuccess;
break;
case kIOMessageSystemWillPowerOff:
case kIOMessageSystemWillRestart:
ret = kIOReturnUnsupported;
break;
default:
ret = kIOReturnUnsupported;
break;
}
return ret;
}
IOReturn IOPMrootDomain::displayWranglerNotification( void * target, void * refCon,
UInt32 messageType, IOService * service,
void * messageArgument, vm_size_t argSize )
{
IOPMrootDomain * rootDomain = OSDynamicCast(IOPMrootDomain, (IOService *)target);
AbsoluteTime deadline;
static bool deviceAlreadyPoweredOff = false;
if(!rootDomain)
return kIOReturnUnsupported;
switch (messageType) {
case kIOMessageDeviceWillPowerOff:
if( deviceAlreadyPoweredOff ) return kIOReturnUnsupported;
deviceAlreadyPoweredOff = true;
if( rootDomain->extraSleepDelay )
{
clock_interval_to_deadline(rootDomain->extraSleepDelay*60, kSecondScale, &deadline );
thread_call_enter_delayed(rootDomain->extraSleepTimer, deadline);
rootDomain->idleSleepPending = true;
} else {
if( (0 != rootDomain->user_spindown) && (0 != rootDomain->sleepSlider) )
rootDomain->setQuickSpinDownTimeout();
}
break;
case kIOMessageDeviceHasPoweredOn:
deviceAlreadyPoweredOff = false;
rootDomain->adjustPowerState();
if(rootDomain->idleSleepPending)
{
thread_call_cancel(rootDomain->extraSleepTimer);
rootDomain->idleSleepPending = false;
}
if(0 != rootDomain->user_spindown)
rootDomain->restoreUserSpinDownTimeout();
break;
default:
break;
}
return kIOReturnUnsupported;
}
bool IOPMrootDomain::displayWranglerPublished(
void * target,
void * refCon,
IOService * newService)
{
IOPMrootDomain *rootDomain =
OSDynamicCast(IOPMrootDomain, (IOService *)target);
if(!rootDomain)
return false;
rootDomain->wrangler = newService;
if( !rootDomain->wrangler->registerInterest( gIOGeneralInterest,
&displayWranglerNotification, target, 0) )
{
return false;
}
return true;
}
bool IOPMrootDomain::batteryPublished(
void * target,
void * root_domain,
IOService * resourceService )
{
((IOPMrootDomain *)root_domain)->publishFeature("DisplayDims");
return (true);
}
void IOPMrootDomain::adjustPowerState( void )
{
if ( (sleepSlider == 0)
|| !allowSleep
|| systemBooting
|| systemShutdown )
{
if(systemBooting || systemShutdown) {
kprintf("adjusting power state to ON_STATE [2063] on grounds of systemBooting.\n");
}
changePowerStateToPriv(ON_STATE);
} else {
if ( sleepASAP )
{
sleepASAP = false;
if ( sleepIsSupported )
{
changePowerStateToPriv(SLEEP_STATE);
} else {
changePowerStateToPriv(DOZE_STATE);
}
}
}
}
#undef super
#define super OSObject
OSDefineMetaClassAndStructors(PMSettingObject, OSObject)
void PMSettingObject::setPMSetting(const OSSymbol *type, OSObject *obj)
{
(*func)(target, type, obj, refcon);
}
PMSettingObject *PMSettingObject::pmSettingObject(
IOPMrootDomain *parent_arg,
IOPMSettingControllerCallback handler_arg,
OSObject *target_arg,
uintptr_t refcon_arg,
uint32_t supportedPowerSources,
const OSSymbol * settings[])
{
uint32_t objCount = 0;
PMSettingObject *pmso;
if( !parent_arg || !handler_arg || !settings ) return NULL;
while( settings[objCount] ) {
objCount++;
}
if(0 == objCount) return NULL;
pmso = new PMSettingObject;
if(!pmso || !pmso->init()) return NULL;
pmso->parent = parent_arg;
pmso->func = handler_arg;
pmso->target = target_arg;
pmso->refcon = refcon_arg;
pmso->releaseAtCount = objCount + 1;
pmso->publishedFeatureID = (uint32_t *)IOMalloc(sizeof(uint32_t)*objCount);
if(pmso->publishedFeatureID) {
for(unsigned int i=0; i<objCount; i++) {
parent_arg->publishFeature( settings[i]->getCStringNoCopy(),
supportedPowerSources, &pmso->publishedFeatureID[i] );
}
}
return pmso;
}
void PMSettingObject::free(void)
{
OSCollectionIterator *settings_iter;
OSSymbol *sym;
OSArray *arr;
int arr_idx;
int i;
int objCount = releaseAtCount - 1;
if(publishedFeatureID) {
for(i=0; i<objCount; i++) {
if(0 != publishedFeatureID[i]) {
parent->removePublishedFeature( publishedFeatureID[i] );
}
}
IOFree(publishedFeatureID, sizeof(uint32_t) * objCount);
}
IORecursiveLockLock(parent->settingsCtrlLock);
settings_iter = OSCollectionIterator::withCollection(parent->settingsCallbacks);
if(settings_iter)
{
while(( sym = OSDynamicCast(OSSymbol, settings_iter->getNextObject()) ))
{
arr = (OSArray *)parent->settingsCallbacks->getObject(sym);
arr_idx = arr->getNextIndexOfObject(this, 0);
if(-1 != arr_idx) {
arr->removeObject(arr_idx);
}
}
settings_iter->release();
}
IORecursiveLockUnlock(parent->settingsCtrlLock);
super::free();
}
void PMSettingObject::taggedRelease(const void *tag, const int when) const
{
super::taggedRelease(tag, releaseAtCount);
}
#undef super
#define super IOService
OSDefineMetaClassAndStructors(IORootParent, IOService)
static IOPMPowerState patriarchPowerStates[number_of_power_states] = {
{1,0,0,0,0,0,0,0,0,0,0,0}, {1,0,RESTART_POWER,0,0,0,0,0,0,0,0,0}, {1,0,SLEEP_POWER,0,0,0,0,0,0,0,0,0}, {1,0,DOZE_POWER,0,0,0,0,0,0,0,0,0}, {1,0,ON_POWER,0,0,0,0,0,0,0,0,0} };
bool IORootParent::start ( IOService * nub )
{
mostRecentChange = ON_STATE;
super::start(nub);
PMinit();
registerPowerDriver(this,patriarchPowerStates,number_of_power_states);
powerOverrideOnPriv();
return true;
}
void IORootParent::shutDownSystem ( void )
{
mostRecentChange = OFF_STATE;
changePowerStateToPriv(OFF_STATE);
}
void IORootParent::restartSystem ( void )
{
mostRecentChange = RESTART_STATE;
changePowerStateToPriv(RESTART_STATE);
}
void IORootParent::sleepSystem ( void )
{
mostRecentChange = SLEEP_STATE;
changePowerStateToPriv(SLEEP_STATE);
}
void IORootParent::dozeSystem ( void )
{
mostRecentChange = DOZE_STATE;
changePowerStateToPriv(DOZE_STATE);
}
void IORootParent::sleepToDoze ( void )
{
if ( mostRecentChange == SLEEP_STATE ) {
changePowerStateToPriv(DOZE_STATE);
}
}
void IORootParent::wakeSystem ( void )
{
mostRecentChange = ON_STATE;
changePowerStateToPriv(ON_STATE);
}
IOReturn IORootParent::changePowerStateToPriv ( unsigned long ordinal )
{
IOReturn ret;
if( (SLEEP_STATE == ordinal) && sleepSupportedPEFunction )
{
ret = getPlatform()->callPlatformFunction(
sleepSupportedPEFunction, false,
NULL, NULL, NULL, NULL);
}
return super::changePowerStateToPriv(ordinal);
}