+
+ param = (DriverCallParam *) fDriverCallParamPtr;
+ if (!param)
+ {
+ param = IONew(DriverCallParam, 1);
+ if (!param)
+ return false; // no memory
+
+ fDriverCallParamPtr = (void *) param;
+ fDriverCallParamSlots = 1;
+ }
+
+ param->Target = fControllingDriver;
+ fDriverCallParamCount = 1;
+ fDriverTimer = -1;
+
+ // Block state machine and wait for callout completion.
+ assert(!fDriverCallBusy);
+ fDriverCallBusy = true;
+ thread_call_enter( fDriverCallEntry );
+
+ return true;
+}
+
+//*********************************************************************************
+// [private] notifyControllingDriverDone
+//*********************************************************************************
+
+void IOService::notifyControllingDriverDone( void )
+{
+ DriverCallParam * param;
+ IOReturn result;
+
+ PM_ASSERT_IN_GATE();
+ param = (DriverCallParam *) fDriverCallParamPtr;
+
+ assert( fDriverCallBusy == false );
+ assert( fMachineState == kIOPM_DriverThreadCallDone );
+
+ if (param && fDriverCallParamCount)
+ {
+ assert(fDriverCallParamCount == 1);
+
+ // the return value from setPowerState()
+ result = param->Result;
+
+ if ((result == IOPMAckImplied) || (result < 0))
+ {
+ fDriverTimer = 0;
+ }
+ else if (fDriverTimer)
+ {
+ assert(fDriverTimer == -1);
+
+ // Driver has not acked, and has returned a positive result.
+ // Enforce a minimum permissible timeout value.
+ // Make the min value large enough so timeout is less likely
+ // to occur if a driver misinterpreted that the return value
+ // should be in microsecond units. And make it large enough
+ // to be noticeable if a driver neglects to ack.
+
+ if (result < kMinAckTimeoutTicks)
+ result = kMinAckTimeoutTicks;
+
+ fDriverTimer = (result / (ACK_TIMER_PERIOD / ns_per_us)) + 1;
+ }
+ // else, child has already acked and driver_timer reset to 0.
+
+ fDriverCallParamCount = 0;
+
+ if ( fDriverTimer )
+ {
+ OUR_PMLog(kPMLogStartAckTimer, 0, 0);
+ start_ack_timer();
+ }
+ }
+
+ MS_POP(); // pushed by OurChangeSetPowerState()
+ fIsPreChange = false;
+}
+
+//*********************************************************************************
+// [private] all_done
+//
+// A power change is done.
+//*********************************************************************************
+
+void IOService::all_done( void )
+{
+ IOPMPowerStateIndex prevPowerState;
+ const IOPMPSEntry * powerStatePtr;
+ IOPMDriverCallEntry callEntry;
+ uint32_t prevMachineState = fMachineState;
+ bool actionCalled = false;
+ uint64_t ts;
+
+ fMachineState = kIOPM_Finished;
+
+ if ((fHeadNoteChangeFlags & kIOPMSynchronize) &&
+ ((prevMachineState == kIOPM_Finished) ||
+ (prevMachineState == kIOPM_SyncFinish)))
+ {
+ // Sync operation and no power change occurred.
+ // Do not inform driver and clients about this request completion,
+ // except for the originator (root domain).
+
+ PM_ACTION_2(actionPowerChangeDone,
+ fHeadNotePowerState, fHeadNoteChangeFlags);
+
+ if (getPMRequestType() == kIOPMRequestTypeSynchronizePowerTree)
+ {
+ powerChangeDone(fCurrentPowerState);
+ }
+ else if (fAdvisoryTickleUsed)
+ {
+ // Not root domain and advisory tickle target.
+ // Re-adjust power after power tree sync at the 'did' pass
+ // to recompute desire and adjust power state between dark
+ // and full wake transitions. Root domain is responsible
+ // for calling setAdvisoryTickleEnable() before starting
+ // the kIOPMSynchronize power change.
+
+ if (!fAdjustPowerScheduled &&
+ (fHeadNoteChangeFlags & kIOPMDomainDidChange))
+ {
+ IOPMRequest * request;
+ request = acquirePMRequest( this, kIOPMRequestTypeAdjustPowerState );
+ if (request)
+ {
+ submitPMRequest( request );
+ fAdjustPowerScheduled = true;
+ }
+ }
+ }
+
+ return;
+ }
+
+ // our power change
+ if (fHeadNoteChangeFlags & kIOPMSelfInitiated)
+ {
+ // power state changed
+ if ((fHeadNoteChangeFlags & kIOPMNotDone) == 0)
+ {
+ trackSystemSleepPreventers(
+ fCurrentPowerState, fHeadNotePowerState, fHeadNoteChangeFlags);
+
+ // we changed, tell our parent
+ requestDomainPower(fHeadNotePowerState);
+
+ // yes, did power raise?
+ if ( StateOrder(fCurrentPowerState) < StateOrder(fHeadNotePowerState) )
+ {
+ // yes, inform clients and apps
+ tellChangeUp (fHeadNotePowerState);
+ }
+ prevPowerState = fCurrentPowerState;
+ // either way
+ fCurrentPowerState = fHeadNotePowerState;
+ PM_LOCK();
+ if (fReportBuf) {
+ ts = mach_absolute_time();
+ STATEREPORT_SETSTATE(fReportBuf, fCurrentPowerState, ts);
+ }
+ PM_UNLOCK();
+#if PM_VARS_SUPPORT
+ fPMVars->myCurrentState = fCurrentPowerState;
+#endif
+ OUR_PMLog(kPMLogChangeDone, fCurrentPowerState, prevPowerState);
+ PM_ACTION_2(actionPowerChangeDone,
+ fHeadNotePowerState, fHeadNoteChangeFlags);
+ actionCalled = true;
+
+ powerStatePtr = &fPowerStates[fCurrentPowerState];
+ fCurrentCapabilityFlags = powerStatePtr->capabilityFlags;
+ if (fCurrentCapabilityFlags & kIOPMStaticPowerValid)
+ fCurrentPowerConsumption = powerStatePtr->staticPower;
+
+ if (fHeadNoteChangeFlags & kIOPMRootChangeDown)
+ {
+ // Bump tickle generation count once the entire tree is down
+ gIOPMTickleGeneration++;
+ }
+
+ // inform subclass policy-maker
+ if (fPCDFunctionOverride && fParentsKnowState &&
+ assertPMDriverCall(&callEntry, kIOPMADC_NoInactiveCheck))
+ {
+ powerChangeDone(prevPowerState);
+ deassertPMDriverCall(&callEntry);
+ }
+ }
+ else if (getPMRequestType() == kIOPMRequestTypeRequestPowerStateOverride)
+ {
+ // changePowerStateWithOverrideTo() was cancelled
+ fOverrideMaxPowerState = kIOPMPowerStateMax;
+ }
+ }
+
+ // parent-initiated power change
+ if (fHeadNoteChangeFlags & kIOPMParentInitiated)
+ {
+ if (fHeadNoteChangeFlags & kIOPMRootChangeDown)
+ ParentChangeRootChangeDown();
+
+ // power state changed
+ if ((fHeadNoteChangeFlags & kIOPMNotDone) == 0)
+ {
+ trackSystemSleepPreventers(
+ fCurrentPowerState, fHeadNotePowerState, fHeadNoteChangeFlags);
+
+ // did power raise?
+ if ( StateOrder(fCurrentPowerState) < StateOrder(fHeadNotePowerState) )
+ {
+ // yes, inform clients and apps
+ tellChangeUp (fHeadNotePowerState);
+ }
+ // either way
+ prevPowerState = fCurrentPowerState;
+ fCurrentPowerState = fHeadNotePowerState;
+ PM_LOCK();
+ if (fReportBuf) {
+ ts = mach_absolute_time();
+ STATEREPORT_SETSTATE(fReportBuf, fCurrentPowerState, ts);
+ }
+ PM_UNLOCK();
+#if PM_VARS_SUPPORT
+ fPMVars->myCurrentState = fCurrentPowerState;
+#endif
+
+ OUR_PMLog(kPMLogChangeDone, fCurrentPowerState, prevPowerState);
+ PM_ACTION_2(actionPowerChangeDone,
+ fHeadNotePowerState, fHeadNoteChangeFlags);
+ actionCalled = true;
+
+ powerStatePtr = &fPowerStates[fCurrentPowerState];
+ fCurrentCapabilityFlags = powerStatePtr->capabilityFlags;
+ if (fCurrentCapabilityFlags & kIOPMStaticPowerValid)
+ fCurrentPowerConsumption = powerStatePtr->staticPower;
+
+ // inform subclass policy-maker
+ if (fPCDFunctionOverride && fParentsKnowState &&
+ assertPMDriverCall(&callEntry, kIOPMADC_NoInactiveCheck))
+ {
+ powerChangeDone(prevPowerState);
+ deassertPMDriverCall(&callEntry);
+ }
+ }
+ }
+
+ // When power rises enough to satisfy the tickle's desire for more power,
+ // the condition preventing idle-timer from dropping power is removed.
+
+ if (StateOrder(fCurrentPowerState) >= StateOrder(fIdleTimerMinPowerState))
+ {
+ fIdleTimerMinPowerState = kPowerStateZero;
+ }
+
+ if (!actionCalled)
+ {
+ PM_ACTION_2(actionPowerChangeDone,
+ fHeadNotePowerState, fHeadNoteChangeFlags);
+ }
+}
+
+// MARK: -
+// MARK: Power Change Initiated by Driver
+
+//*********************************************************************************
+// [private] OurChangeStart
+//
+// Begin the processing of a power change initiated by us.
+//*********************************************************************************
+
+void IOService::OurChangeStart( void )
+{
+ PM_ASSERT_IN_GATE();
+ OUR_PMLog( kPMLogStartDeviceChange, fHeadNotePowerState, fCurrentPowerState );
+
+ // fMaxPowerState is our maximum possible power state based on the current
+ // power state of our parents. If we are trying to raise power beyond the
+ // maximum, send an async request for more power to all parents.
+
+ if (!IS_PM_ROOT && (StateOrder(fMaxPowerState) < StateOrder(fHeadNotePowerState)))
+ {
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ requestDomainPower(fHeadNotePowerState);
+ OurChangeFinish();
+ return;
+ }
+
+ // Redundant power changes skips to the end of the state machine.
+
+ if (!fInitialPowerChange && (fHeadNotePowerState == fCurrentPowerState))
+ {
+ OurChangeFinish();
+ return;
+ }
+ fInitialPowerChange = false;
+
+ // Change started, but may not complete...
+ // Can be canceled (power drop) or deferred (power rise).
+
+ PM_ACTION_2(actionPowerChangeStart, fHeadNotePowerState, &fHeadNoteChangeFlags);
+
+ // Two separate paths, depending if power is being raised or lowered.
+ // Lowering power is subject to approval by clients of this service.
+
+ if (IS_POWER_DROP)
+ {
+ fDoNotPowerDown = false;
+
+ // Ask for persmission to drop power state
+ fMachineState = kIOPM_OurChangeTellClientsPowerDown;
+ fOutOfBandParameter = kNotifyApps;
+ askChangeDown(fHeadNotePowerState);
+ }
+ else
+ {
+ // This service is raising power and parents are able to support the
+ // new power state. However a parent may have already committed to
+ // drop power, which might force this object to temporarily drop power.
+ // This results in "oscillations" before the state machines converge
+ // to a steady state.
+ //
+ // To prevent this, a child must make a power reservation against all
+ // parents before raising power. If the reservation fails, indicating
+ // that the child will be unable to sustain the higher power state,
+ // then the child will signal the parent to adjust power, and the child
+ // will defer its power change.
+
+ IOReturn ret;
+
+ // Reserve parent power necessary to achieve fHeadNotePowerState.
+ ret = requestDomainPower( fHeadNotePowerState, kReserveDomainPower );
+ if (ret != kIOReturnSuccess)
+ {
+ // Reservation failed, defer power rise.
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ OurChangeFinish();
+ return;
+ }
+
+ OurChangeTellCapabilityWillChange();
+ }
+}
+
+//*********************************************************************************
+// [private] requestDomainPowerApplier
+//
+// Call requestPowerDomainState() on all power parents.
+//*********************************************************************************
+
+struct IOPMRequestDomainPowerContext {
+ IOService * child; // the requesting child
+ IOPMPowerFlags requestPowerFlags; // power flags requested by child
+};
+
+static void
+requestDomainPowerApplier(
+ IORegistryEntry * entry,
+ void * inContext )
+{
+ IOPowerConnection * connection;
+ IOService * parent;
+ IOPMRequestDomainPowerContext * context;
+
+ if ((connection = OSDynamicCast(IOPowerConnection, entry)) == 0)
+ return;
+ parent = (IOService *) connection->copyParentEntry(gIOPowerPlane);
+ if (!parent)
+ return;
+
+ assert(inContext);
+ context = (IOPMRequestDomainPowerContext *) inContext;
+
+ if (connection->parentKnowsState() && connection->getReadyFlag())
+ {
+ parent->requestPowerDomainState(
+ context->requestPowerFlags,
+ connection,
+ IOPMLowestState);
+ }
+
+ parent->release();
+}
+
+//*********************************************************************************
+// [private] requestDomainPower
+//
+// Called by a power child to broadcast its desired power state to all parents.
+// If the child self-initiates a power change, it must call this function to
+// allow its parents to adjust power state.
+//*********************************************************************************
+
+IOReturn IOService::requestDomainPower(
+ IOPMPowerStateIndex ourPowerState,
+ IOOptionBits options )
+{
+ IOPMPowerFlags requestPowerFlags;
+ IOPMPowerStateIndex maxPowerState;
+ IOPMRequestDomainPowerContext context;
+
+ PM_ASSERT_IN_GATE();
+ assert(ourPowerState < fNumberOfPowerStates);
+ if (ourPowerState >= fNumberOfPowerStates)
+ return kIOReturnBadArgument;
+ if (IS_PM_ROOT)
+ return kIOReturnSuccess;
+
+ // Fetch our input power flags for the requested power state.
+ // Parent request is stated in terms of required power flags.
+
+ requestPowerFlags = fPowerStates[ourPowerState].inputPowerFlags;
+
+ // Disregard the "previous request" for power reservation.
+
+ if (((options & kReserveDomainPower) == 0) &&
+ (fPreviousRequestPowerFlags == requestPowerFlags))
+ {
+ // skip if domain already knows our requirements
+ goto done;
+ }
+ fPreviousRequestPowerFlags = requestPowerFlags;
+
+ // The results will be collected by fHeadNoteDomainTargetFlags
+ context.child = this;
+ context.requestPowerFlags = requestPowerFlags;
+ fHeadNoteDomainTargetFlags = 0;
+ applyToParents(requestDomainPowerApplier, &context, gIOPowerPlane);
+
+ if (options & kReserveDomainPower)
+ {
+ maxPowerState = fControllingDriver->maxCapabilityForDomainState(
+ fHeadNoteDomainTargetFlags );
+
+ if (StateOrder(maxPowerState) < StateOrder(ourPowerState))
+ {
+ PM_LOG1("%s: power desired %u:0x%x got %u:0x%x\n",
+ getName(),
+ (uint32_t) ourPowerState, (uint32_t) requestPowerFlags,
+ (uint32_t) maxPowerState, (uint32_t) fHeadNoteDomainTargetFlags);
+ return kIOReturnNoPower;
+ }
+ }
+
+done:
+ return kIOReturnSuccess;
+}
+
+//*********************************************************************************
+// [private] OurSyncStart
+//*********************************************************************************
+
+void IOService::OurSyncStart( void )
+{
+ PM_ASSERT_IN_GATE();
+
+ if (fInitialPowerChange)
+ return;
+
+ PM_ACTION_2(actionPowerChangeStart, fHeadNotePowerState, &fHeadNoteChangeFlags);
+
+ if (fHeadNoteChangeFlags & kIOPMNotDone)
+ {
+ OurChangeFinish();
+ return;
+ }
+
+ if (fHeadNoteChangeFlags & kIOPMSyncTellPowerDown)
+ {
+ fDoNotPowerDown = false;
+
+ // Ask for permission to drop power state
+ fMachineState = kIOPM_SyncTellClientsPowerDown;
+ fOutOfBandParameter = kNotifyApps;
+ askChangeDown(fHeadNotePowerState);
+ }
+ else
+ {
+ // Only inform capability app and clients.
+ tellSystemCapabilityChange( kIOPM_SyncNotifyWillChange );
+ }
+}
+
+//*********************************************************************************
+// [private] OurChangeTellClientsPowerDown
+//
+// All applications and kernel clients have acknowledged our permission to drop
+// power. Here we notify them that we will lower the power and wait for acks.
+//*********************************************************************************
+
+void IOService::OurChangeTellClientsPowerDown( void )
+{
+ if(!IS_ROOT_DOMAIN)
+ fMachineState = kIOPM_OurChangeTellPriorityClientsPowerDown;
+ else
+ {
+ fMachineState = kIOPM_OurChangeTellUserPMPolicyPowerDown;
+ }
+ tellChangeDown1(fHeadNotePowerState);
+}
+
+//*********************************************************************************
+// [private] OurChangeTellUserPMPolicyPowerDown
+//
+// All applications and kernel clients have acknowledged our permission to drop
+// power. Here we notify power management policy in user-space and wait for acks
+// one last time before we lower power
+//*********************************************************************************
+void IOService::OurChangeTellUserPMPolicyPowerDown ( void )
+{
+ fMachineState = kIOPM_OurChangeTellPriorityClientsPowerDown;
+ fOutOfBandParameter = kNotifyApps;
+
+ tellClientsWithResponse(kIOPMMessageLastCallBeforeSleep);
+}
+
+//*********************************************************************************
+// [private] OurChangeTellPriorityClientsPowerDown
+//
+// All applications and kernel clients have acknowledged our intention to drop
+// power. Here we notify "priority" clients that we are lowering power.
+//*********************************************************************************
+
+void IOService::OurChangeTellPriorityClientsPowerDown( void )
+{
+ fMachineState = kIOPM_OurChangeNotifyInterestedDriversWillChange;
+ tellChangeDown2(fHeadNotePowerState);
+}
+
+//*********************************************************************************
+// [private] OurChangeTellCapabilityWillChange
+//
+// Extra stage for root domain to notify apps and drivers about the
+// system capability change when raising power state.
+//*********************************************************************************
+
+void IOService::OurChangeTellCapabilityWillChange( void )
+{
+ if (!IS_ROOT_DOMAIN)
+ return OurChangeNotifyInterestedDriversWillChange();
+
+ tellSystemCapabilityChange( kIOPM_OurChangeNotifyInterestedDriversWillChange );
+}
+
+//*********************************************************************************
+// [private] OurChangeNotifyInterestedDriversWillChange
+//
+// All applications and kernel clients have acknowledged our power state change.
+// Here we notify interested drivers pre-change.
+//*********************************************************************************
+
+void IOService::OurChangeNotifyInterestedDriversWillChange( void )
+{
+ IOPMrootDomain * rootDomain;
+ if ((rootDomain = getPMRootDomain()) == this)
+ {
+ if (IS_POWER_DROP)
+ {
+ rootDomain->tracePoint( kIOPMTracePointSleepWillChangeInterests );
+ }
+ else
+ rootDomain->tracePoint( kIOPMTracePointWakeWillChangeInterests );
+ }
+
+ notifyAll( kIOPM_OurChangeSetPowerState );
+}
+
+//*********************************************************************************
+// [private] OurChangeSetPowerState
+//
+// Instruct our controlling driver to program the hardware for the power state
+// change. Wait for async completions.
+//*********************************************************************************
+
+void IOService::OurChangeSetPowerState( void )
+{
+ MS_PUSH( kIOPM_OurChangeWaitForPowerSettle );
+ fMachineState = kIOPM_DriverThreadCallDone;
+ fDriverCallReason = kDriverCallSetPowerState;
+
+ if (notifyControllingDriver() == false)
+ notifyControllingDriverDone();
+}
+
+//*********************************************************************************
+// [private] OurChangeWaitForPowerSettle
+//
+// Our controlling driver has completed the power state change we initiated.
+// Wait for the driver specified settle time to expire.
+//*********************************************************************************
+
+void IOService::OurChangeWaitForPowerSettle( void )
+{
+ fMachineState = kIOPM_OurChangeNotifyInterestedDriversDidChange;
+ startSettleTimer();
+}
+
+//*********************************************************************************
+// [private] OurChangeNotifyInterestedDriversDidChange
+//
+// Power has settled on a power change we initiated. Here we notify
+// all our interested drivers post-change.
+//*********************************************************************************
+
+void IOService::OurChangeNotifyInterestedDriversDidChange( void )
+{
+ IOPMrootDomain * rootDomain;
+ if ((rootDomain = getPMRootDomain()) == this)
+ {
+ rootDomain->tracePoint( IS_POWER_DROP ?
+ kIOPMTracePointSleepDidChangeInterests :
+ kIOPMTracePointWakeDidChangeInterests );
+ }
+
+ notifyAll( kIOPM_OurChangeTellCapabilityDidChange );
+}
+
+//*********************************************************************************
+// [private] OurChangeTellCapabilityDidChange
+//
+// For root domain to notify capability power-change.
+//*********************************************************************************
+
+void IOService::OurChangeTellCapabilityDidChange( void )
+{
+ if (!IS_ROOT_DOMAIN)
+ return OurChangeFinish();
+
+ getPMRootDomain()->tracePoint( IS_POWER_DROP ?
+ kIOPMTracePointSleepCapabilityClients :
+ kIOPMTracePointWakeCapabilityClients );
+
+ tellSystemCapabilityChange( kIOPM_OurChangeFinish );
+}
+
+//*********************************************************************************
+// [private] OurChangeFinish
+//
+// Done with this self-induced power state change.
+//*********************************************************************************
+
+void IOService::OurChangeFinish( void )
+{
+ all_done();
+}
+
+// MARK: -
+// MARK: Power Change Initiated by Parent
+
+//*********************************************************************************
+// [private] ParentChangeStart
+//
+// Here we begin the processing of a power change initiated by our parent.
+//*********************************************************************************
+
+IOReturn IOService::ParentChangeStart( void )
+{
+ PM_ASSERT_IN_GATE();
+ OUR_PMLog( kPMLogStartParentChange, fHeadNotePowerState, fCurrentPowerState );
+
+ // Root power domain has transitioned to its max power state
+ if ((fHeadNoteChangeFlags & (kIOPMDomainDidChange | kIOPMRootChangeUp)) ==
+ (kIOPMDomainDidChange | kIOPMRootChangeUp))
+ {
+ // Restart the idle timer stopped by ParentChangeRootChangeDown()
+ if (fIdleTimerPeriod && fIdleTimerStopped)
+ {
+ restartIdleTimer();
+ }
+ }
+
+ // Power domain is forcing us to lower power
+ if ( StateOrder(fHeadNotePowerState) < StateOrder(fCurrentPowerState) )
+ {
+ PM_ACTION_2(actionPowerChangeStart, fHeadNotePowerState, &fHeadNoteChangeFlags);
+
+ // Tell apps and kernel clients
+ fInitialPowerChange = false;
+ fMachineState = kIOPM_ParentChangeTellPriorityClientsPowerDown;
+ tellChangeDown1(fHeadNotePowerState);
+ return IOPMWillAckLater;
+ }
+
+ // Power domain is allowing us to raise power up to fHeadNotePowerState
+ if ( StateOrder(fHeadNotePowerState) > StateOrder(fCurrentPowerState) )
+ {
+ if ( StateOrder(fDesiredPowerState) > StateOrder(fCurrentPowerState) )
+ {
+ if ( StateOrder(fDesiredPowerState) < StateOrder(fHeadNotePowerState) )
+ {
+ // We power up, but not all the way
+ fHeadNotePowerState = fDesiredPowerState;
+ fHeadNotePowerArrayEntry = &fPowerStates[fDesiredPowerState];
+ OUR_PMLog(kPMLogAmendParentChange, fHeadNotePowerState, 0);
+ }
+ } else {
+ // We don't need to change
+ fHeadNotePowerState = fCurrentPowerState;
+ fHeadNotePowerArrayEntry = &fPowerStates[fCurrentPowerState];
+ OUR_PMLog(kPMLogAmendParentChange, fHeadNotePowerState, 0);
+ }
+ }
+
+ if ( fHeadNoteChangeFlags & kIOPMDomainDidChange )
+ {
+ if ( StateOrder(fHeadNotePowerState) > StateOrder(fCurrentPowerState) )
+ {
+ PM_ACTION_2(actionPowerChangeStart,
+ fHeadNotePowerState, &fHeadNoteChangeFlags);
+
+ // Parent did change up - start our change up
+ fInitialPowerChange = false;
+ ParentChangeTellCapabilityWillChange();
+ return IOPMWillAckLater;
+ }
+ else if (fHeadNoteChangeFlags & kIOPMRootBroadcastFlags)
+ {
+ // No need to change power state, but broadcast change
+ // to our children.
+ fMachineState = kIOPM_SyncNotifyDidChange;
+ fDriverCallReason = kDriverCallInformPreChange;
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ notifyChildren();
+ return IOPMWillAckLater;
+ }
+ }
+
+ // No power state change necessary
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+
+ all_done();
+ return IOPMAckImplied;
+}
+
+//******************************************************************************
+// [private] ParentChangeRootChangeDown
+//
+// Root domain has finished the transition to the system sleep state. And all
+// drivers in the power plane should have powered down. Cancel the idle timer,
+// and also reset the device desire for those drivers that don't want power
+// automatically restored on wake.
+//******************************************************************************
+
+void IOService::ParentChangeRootChangeDown( void )
+{
+ // Always stop the idle timer before root power down
+ if (fIdleTimerPeriod && !fIdleTimerStopped)
+ {
+ fIdleTimerStopped = true;
+ if (fIdleTimer && thread_call_cancel(fIdleTimer))
+ release();
+ }
+
+ if (fResetPowerStateOnWake)
+ {
+ // Reset device desire down to the lowest power state.
+ // Advisory tickle desire is intentionally untouched since
+ // it has no effect until system is promoted to full wake.
+
+ if (fDeviceDesire != kPowerStateZero)
+ {
+ updatePowerClient(gIOPMPowerClientDevice, kPowerStateZero);
+ computeDesiredState(kPowerStateZero, true);
+ requestDomainPower( fDesiredPowerState );
+ PM_LOG1("%s: tickle desire removed\n", fName);
+ }
+
+ // Invalidate tickle cache so the next tickle will issue a request
+ IOLockLock(fActivityLock);
+ fDeviceWasActive = false;
+ fActivityTicklePowerState = kInvalidTicklePowerState;
+ IOLockUnlock(fActivityLock);
+
+ fIdleTimerMinPowerState = kPowerStateZero;
+ }
+ else if (fAdvisoryTickleUsed)
+ {
+ // Less aggressive mechanism to accelerate idle timer expiration
+ // before system sleep. May not always allow the driver to wake
+ // up from system sleep in the min power state.
+
+ AbsoluteTime now;
+ uint64_t nsec;
+ bool dropTickleDesire = false;
+
+ if (fIdleTimerPeriod && !fIdleTimerIgnored &&
+ (fIdleTimerMinPowerState == kPowerStateZero) &&
+ (fDeviceDesire != kPowerStateZero))
+ {
+ IOLockLock(fActivityLock);
+
+ if (!fDeviceWasActive)
+ {
+ // No tickles since the last idle timer expiration.
+ // Safe to drop the device desire to zero.
+ dropTickleDesire = true;
+ }
+ else
+ {
+ // Was tickled since the last idle timer expiration,
+ // but not in the last minute.
+ clock_get_uptime(&now);
+ SUB_ABSOLUTETIME(&now, &fDeviceActiveTimestamp);
+ absolutetime_to_nanoseconds(now, &nsec);
+ if (nsec >= kNoTickleCancelWindow)
+ {
+ dropTickleDesire = true;
+ }
+ }
+
+ if (dropTickleDesire)
+ {
+ // Force the next tickle to raise power state
+ fDeviceWasActive = false;
+ fActivityTicklePowerState = kInvalidTicklePowerState;
+ }
+
+ IOLockUnlock(fActivityLock);
+ }
+
+ if (dropTickleDesire)
+ {
+ // Advisory tickle desire is intentionally untouched since
+ // it has no effect until system is promoted to full wake.
+
+ updatePowerClient(gIOPMPowerClientDevice, kPowerStateZero);
+ computeDesiredState(kPowerStateZero, true);
+ PM_LOG1("%s: tickle desire dropped\n", fName);
+ }
+ }
+}
+
+//*********************************************************************************
+// [private] ParentChangeTellPriorityClientsPowerDown
+//
+// All applications and kernel clients have acknowledged our intention to drop
+// power. Here we notify "priority" clients that we are lowering power.
+//*********************************************************************************
+
+void IOService::ParentChangeTellPriorityClientsPowerDown( void )
+{
+ fMachineState = kIOPM_ParentChangeNotifyInterestedDriversWillChange;
+ tellChangeDown2(fHeadNotePowerState);
+}
+
+//*********************************************************************************
+// [private] ParentChangeTellCapabilityWillChange
+//
+// All (legacy) applications and kernel clients have acknowledged, extra stage for
+// root domain to notify apps and drivers about the system capability change.
+//*********************************************************************************
+
+void IOService::ParentChangeTellCapabilityWillChange( void )
+{
+ if (!IS_ROOT_DOMAIN)
+ return ParentChangeNotifyInterestedDriversWillChange();
+
+ tellSystemCapabilityChange( kIOPM_ParentChangeNotifyInterestedDriversWillChange );
+}
+
+//*********************************************************************************
+// [private] ParentChangeNotifyInterestedDriversWillChange
+//
+// All applications and kernel clients have acknowledged our power state change.
+// Here we notify interested drivers pre-change.
+//*********************************************************************************
+
+void IOService::ParentChangeNotifyInterestedDriversWillChange( void )
+{
+ notifyAll( kIOPM_ParentChangeSetPowerState );
+}
+
+//*********************************************************************************
+// [private] ParentChangeSetPowerState
+//
+// Instruct our controlling driver to program the hardware for the power state
+// change. Wait for async completions.
+//*********************************************************************************
+
+void IOService::ParentChangeSetPowerState( void )
+{
+ MS_PUSH( kIOPM_ParentChangeWaitForPowerSettle );
+ fMachineState = kIOPM_DriverThreadCallDone;
+ fDriverCallReason = kDriverCallSetPowerState;
+
+ if (notifyControllingDriver() == false)
+ notifyControllingDriverDone();
+}
+
+//*********************************************************************************
+// [private] ParentChangeWaitForPowerSettle
+//
+// Our controlling driver has completed the power state change initiated by our
+// parent. Wait for the driver specified settle time to expire.
+//*********************************************************************************
+
+void IOService::ParentChangeWaitForPowerSettle( void )
+{
+ fMachineState = kIOPM_ParentChangeNotifyInterestedDriversDidChange;
+ startSettleTimer();
+}
+
+//*********************************************************************************
+// [private] ParentChangeNotifyInterestedDriversDidChange
+//
+// Power has settled on a power change initiated by our parent. Here we notify
+// all our interested drivers post-change.
+//*********************************************************************************
+
+void IOService::ParentChangeNotifyInterestedDriversDidChange( void )
+{
+ notifyAll( kIOPM_ParentChangeTellCapabilityDidChange );
+}
+
+//*********************************************************************************
+// [private] ParentChangeTellCapabilityDidChange
+//
+// For root domain to notify capability power-change.
+//*********************************************************************************
+
+void IOService::ParentChangeTellCapabilityDidChange( void )
+{
+ if (!IS_ROOT_DOMAIN)
+ return ParentChangeAcknowledgePowerChange();
+
+ tellSystemCapabilityChange( kIOPM_ParentChangeAcknowledgePowerChange );
+}
+
+//*********************************************************************************
+// [private] ParentAcknowledgePowerChange
+//
+// Acknowledge our power parent that our power change is done.
+//*********************************************************************************
+
+void IOService::ParentChangeAcknowledgePowerChange( void )
+{
+ IORegistryEntry * nub;
+ IOService * parent;
+
+ nub = fHeadNoteParentConnection;
+ nub->retain();
+ all_done();
+ parent = (IOService *)nub->copyParentEntry(gIOPowerPlane);
+ if ( parent )
+ {
+ parent->acknowledgePowerChange((IOService *)nub);
+ parent->release();
+ }
+ nub->release();
+}
+
+// MARK: -
+// MARK: Ack and Settle timers
+
+//*********************************************************************************
+// [private] settleTimerExpired
+//
+// Power has settled after our last change. Notify interested parties that
+// there is a new power state.
+//*********************************************************************************
+
+void IOService::settleTimerExpired( void )
+{
+ fSettleTimeUS = 0;
+ gIOPMWorkQueue->signalWorkAvailable();
+}
+
+//*********************************************************************************
+// settle_timer_expired
+//
+// Holds a retain while the settle timer callout is in flight.
+//*********************************************************************************
+
+static void
+settle_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
+{
+ IOService * me = (IOService *) arg0;
+
+ if (gIOPMWorkLoop && gIOPMWorkQueue)
+ {
+ gIOPMWorkLoop->runAction(
+ OSMemberFunctionCast(IOWorkLoop::Action, me, &IOService::settleTimerExpired),
+ me);
+ }
+ me->release();
+}
+
+//*********************************************************************************
+// [private] startSettleTimer
+//
+// Calculate a power-settling delay in microseconds and start a timer.
+//*********************************************************************************
+
+void IOService::startSettleTimer( void )
+{
+#if NOT_USEFUL
+ // This function is broken and serves no useful purpose since it never
+ // updates fSettleTimeUS to a non-zero value to stall the state machine,
+ // yet it starts a delay timer. It appears no driver relies on a delay
+ // from settleUpTime and settleDownTime in the power state table.
+
+ AbsoluteTime deadline;
+ IOPMPowerStateIndex stateIndex;
+ IOPMPowerStateIndex currentOrder, newOrder, i;
+ uint32_t settleTime = 0;
+ boolean_t pending;
+
+ PM_ASSERT_IN_GATE();
+
+ currentOrder = StateOrder(fCurrentPowerState);
+ newOrder = StateOrder(fHeadNotePowerState);
+
+ i = currentOrder;
+
+ // lowering power
+ if ( newOrder < currentOrder )
+ {
+ while ( i > newOrder )
+ {
+ stateIndex = fPowerStates[i].stateOrderToIndex;
+ settleTime += (uint32_t) fPowerStates[stateIndex].settleDownTime;
+ i--;
+ }
+ }
+
+ // raising power
+ if ( newOrder > currentOrder )
+ {
+ while ( i < newOrder )
+ {
+ stateIndex = fPowerStates[i+1].stateOrderToIndex;
+ settleTime += (uint32_t) fPowerStates[stateIndex].settleUpTime;
+ i++;
+ }
+ }
+
+ if (settleTime)
+ {
+ retain();
+ clock_interval_to_deadline(settleTime, kMicrosecondScale, &deadline);
+ pending = thread_call_enter_delayed(fSettleTimer, deadline);
+ if (pending) release();
+ }
+#endif
+}
+
+//*********************************************************************************
+// [private] ackTimerTick
+//
+// The acknowledgement timeout periodic timer has ticked.
+// If we are awaiting acks for a power change notification,
+// we decrement the timer word of each interested driver which hasn't acked.
+// If a timer word becomes zero, we pretend the driver aknowledged.
+// If we are waiting for the controlling driver to change the power
+// state of the hardware, we decrement its timer word, and if it becomes
+// zero, we pretend the driver acknowledged.
+//
+// Returns true if the timer tick made it possible to advance to the next
+// machine state, false otherwise.
+//*********************************************************************************
+
+#ifndef __LP64__
+void IOService::ack_timer_ticked ( void )
+{
+ assert(false);
+}
+#endif /* !__LP64__ */
+
+bool IOService::ackTimerTick( void )
+{
+ IOPMinformee * nextObject;
+ bool done = false;
+
+ PM_ASSERT_IN_GATE();
+ switch (fMachineState) {
+ case kIOPM_OurChangeWaitForPowerSettle:
+ case kIOPM_ParentChangeWaitForPowerSettle:
+ // are we waiting for controlling driver to acknowledge?
+ if ( fDriverTimer > 0 )
+ {
+ // yes, decrement timer tick
+ fDriverTimer--;
+ if ( fDriverTimer == 0 )
+ {
+ // controlling driver is tardy
+ uint64_t nsec = computeTimeDeltaNS(&fDriverCallStartTime);
+ OUR_PMLog(kPMLogCtrlDriverTardy, 0, 0);
+ setProperty(kIOPMTardyAckSPSKey, kOSBooleanTrue);
+ PM_ERROR("%s::setPowerState(%p, %lu -> %lu) timed out after %d ms\n",
+ fName, OBFUSCATE(this), fCurrentPowerState, fHeadNotePowerState, NS_TO_MS(nsec));
+
+ if (gIOKitDebug & kIOLogDebugPower)
+ {
+ panic("%s::setPowerState(%p, %lu -> %lu) timed out after %d ms",
+ fName, this, fCurrentPowerState, fHeadNotePowerState, NS_TO_MS(nsec));
+ }
+ else
+ {
+ // Unblock state machine and pretend driver has acked.
+ done = true;
+ }
+ } else {
+ // still waiting, set timer again
+ start_ack_timer();
+ }
+ }
+ break;
+
+ case kIOPM_NotifyChildrenStart:
+ // are we waiting for interested parties to acknowledge?
+ if ( fHeadNotePendingAcks != 0 )
+ {
+ // yes, go through the list of interested drivers
+ nextObject = fInterestedDrivers->firstInList();
+ // and check each one
+ while ( nextObject != NULL )
+ {
+ if ( nextObject->timer > 0 )
+ {
+ nextObject->timer--;
+ // this one should have acked by now
+ if ( nextObject->timer == 0 )
+ {
+ uint64_t nsec = computeTimeDeltaNS(&nextObject->startTime);
+ OUR_PMLog(kPMLogIntDriverTardy, 0, 0);
+ nextObject->whatObject->setProperty(kIOPMTardyAckPSCKey, kOSBooleanTrue);
+ PM_ERROR("%s::powerState%sChangeTo(%p, %s, %lu -> %lu) timed out after %d ms\n",
+ nextObject->whatObject->getName(),
+ (fDriverCallReason == kDriverCallInformPreChange) ? "Will" : "Did",
+ OBFUSCATE(nextObject->whatObject), fName, fCurrentPowerState, fHeadNotePowerState,
+ NS_TO_MS(nsec));
+
+ // Pretend driver has acked.
+ fHeadNotePendingAcks--;
+ }
+ }
+ nextObject = fInterestedDrivers->nextInList(nextObject);
+ }
+
+ // is that the last?
+ if ( fHeadNotePendingAcks == 0 )
+ {
+ // yes, we can continue
+ done = true;
+ } else {
+ // no, set timer again
+ start_ack_timer();
+ }
+ }
+ break;
+
+ // TODO: aggreggate this
+ case kIOPM_OurChangeTellClientsPowerDown:
+ case kIOPM_OurChangeTellUserPMPolicyPowerDown:
+ case kIOPM_OurChangeTellPriorityClientsPowerDown:
+ case kIOPM_OurChangeNotifyInterestedDriversWillChange:
+ case kIOPM_ParentChangeTellPriorityClientsPowerDown:
+ case kIOPM_ParentChangeNotifyInterestedDriversWillChange:
+ case kIOPM_SyncTellClientsPowerDown:
+ case kIOPM_SyncTellPriorityClientsPowerDown:
+ case kIOPM_SyncNotifyWillChange:
+ case kIOPM_TellCapabilityChangeDone:
+ // apps didn't respond in time
+ cleanClientResponses(true);
+ OUR_PMLog(kPMLogClientTardy, 0, 1);
+ // tardy equates to approval
+ done = true;
+ break;
+
+ default:
+ PM_LOG1("%s: unexpected ack timer tick (state = %d)\n",
+ getName(), fMachineState);
+ break;
+ }
+ return done;
+}
+
+//*********************************************************************************
+// [private] start_watchdog_timer
+//*********************************************************************************
+void IOService::start_watchdog_timer( void )
+{
+ AbsoluteTime deadline;
+ boolean_t pending;
+ static int timeout = -1;
+
+ if (!fWatchdogTimer || (kIOSleepWakeWdogOff & gIOKitDebug))
+ return;
+
+ if (thread_call_isactive(fWatchdogTimer)) return;
+ if (timeout == -1) {
+ PE_parse_boot_argn("swd_timeout", &timeout, sizeof(timeout));
+ }
+ if (timeout < 60) {
+ timeout = WATCHDOG_TIMER_PERIOD;
+ }
+
+ clock_interval_to_deadline(timeout, kSecondScale, &deadline);
+
+ retain();
+ pending = thread_call_enter_delayed(fWatchdogTimer, deadline);
+ if (pending) release();
+
+}
+
+//*********************************************************************************
+// [private] stop_watchdog_timer
+// Returns true if watchdog was enabled and stopped now
+//*********************************************************************************
+
+bool IOService::stop_watchdog_timer( void )
+{
+ boolean_t pending;
+
+ if (!fWatchdogTimer || (kIOSleepWakeWdogOff & gIOKitDebug))
+ return false;
+
+ pending = thread_call_cancel(fWatchdogTimer);
+ if (pending) release();
+
+ return pending;
+}
+
+//*********************************************************************************
+// reset_watchdog_timer
+//*********************************************************************************
+
+void IOService::reset_watchdog_timer( void )
+{
+ if (stop_watchdog_timer())
+ start_watchdog_timer();
+}
+
+
+//*********************************************************************************
+// [static] watchdog_timer_expired
+//
+// Inside PM work loop's gate.
+//*********************************************************************************
+
+void
+IOService::watchdog_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
+{
+ IOService * me = (IOService *) arg0;
+
+
+ gIOPMWatchDogThread = current_thread();
+ getPMRootDomain()->sleepWakeDebugTrig(true);
+ gIOPMWatchDogThread = 0;
+ thread_call_free(me->fWatchdogTimer);
+ me->fWatchdogTimer = 0;
+
+ return ;
+}
+
+
+//*********************************************************************************
+// [private] start_ack_timer
+//*********************************************************************************
+
+void IOService::start_ack_timer( void )
+{
+ start_ack_timer( ACK_TIMER_PERIOD, kNanosecondScale );
+}
+
+void IOService::start_ack_timer ( UInt32 interval, UInt32 scale )
+{
+ AbsoluteTime deadline;
+ boolean_t pending;
+
+ clock_interval_to_deadline(interval, scale, &deadline);
+
+ retain();
+ pending = thread_call_enter_delayed(fAckTimer, deadline);
+ if (pending) release();
+
+ // Stop watchdog if ack is delayed by more than a sec
+ if (interval * scale > kSecondScale) {
+ stop_watchdog_timer();
+ }
+}
+
+//*********************************************************************************
+// [private] stop_ack_timer
+//*********************************************************************************
+
+void IOService::stop_ack_timer( void )
+{
+ boolean_t pending;
+
+ pending = thread_call_cancel(fAckTimer);
+ if (pending) release();
+
+ start_watchdog_timer();
+}
+
+//*********************************************************************************
+// [static] actionAckTimerExpired
+//
+// Inside PM work loop's gate.
+//*********************************************************************************
+
+IOReturn
+IOService::actionAckTimerExpired(
+ OSObject * target,
+ void * arg0, void * arg1,
+ void * arg2, void * arg3 )
+{
+ IOService * me = (IOService *) target;
+ bool done;
+
+ // done will be true if the timer tick unblocks the machine state,
+ // otherwise no need to signal the work loop.
+
+ done = me->ackTimerTick();
+ if (done && gIOPMWorkQueue)
+ {
+ gIOPMWorkQueue->signalWorkAvailable();
+ me->start_watchdog_timer();
+ }
+
+ return kIOReturnSuccess;
+}
+
+//*********************************************************************************
+// ack_timer_expired
+//
+// Thread call function. Holds a retain while the callout is in flight.
+//*********************************************************************************
+
+void
+IOService::ack_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
+{
+ IOService * me = (IOService *) arg0;
+
+ if (gIOPMWorkLoop)
+ {
+ gIOPMWorkLoop->runAction(&actionAckTimerExpired, me);
+ }
+ me->release();
+}
+
+//*********************************************************************************
+// [private] start_spindump_timer
+//*********************************************************************************
+
+void IOService::start_spindump_timer( const char * delay_type )
+{
+ AbsoluteTime deadline;
+ boolean_t pending;
+
+ if (!fSpinDumpTimer || !(kIOKextSpinDump & gIOKitDebug))
+ return;
+
+ if (gIOSpinDumpKextName[0] == '\0' &&
+ !(PE_parse_boot_argn("swd_kext_name", &gIOSpinDumpKextName,
+ sizeof(gIOSpinDumpKextName))))
+ {
+ return;
+ }
+
+ if (strncmp(gIOSpinDumpKextName, fName, sizeof(gIOSpinDumpKextName)) != 0)
+ return;
+
+ if (gIOSpinDumpDelayType[0] == '\0' &&
+ !(PE_parse_boot_argn("swd_delay_type", &gIOSpinDumpDelayType,
+ sizeof(gIOSpinDumpDelayType))))
+ {
+ strncpy(gIOSpinDumpDelayType, "SetState", sizeof(gIOSpinDumpDelayType));
+ }
+
+ if (strncmp(delay_type, gIOSpinDumpDelayType, sizeof(gIOSpinDumpDelayType)) != 0)
+ return;
+
+ if (gIOSpinDumpDelayDuration == 0 &&
+ !(PE_parse_boot_argn("swd_delay_duration", &gIOSpinDumpDelayDuration,
+ sizeof(gIOSpinDumpDelayDuration))))
+ {
+ gIOSpinDumpDelayDuration = 300;
+ }
+
+ clock_interval_to_deadline(gIOSpinDumpDelayDuration, kMillisecondScale, &deadline);
+
+ retain();
+ pending = thread_call_enter_delayed(fSpinDumpTimer, deadline);
+ if (pending) release();
+}
+
+//*********************************************************************************
+// [private] stop_spindump_timer
+//*********************************************************************************
+
+void IOService::stop_spindump_timer( void )
+{
+ boolean_t pending;
+
+ if (!fSpinDumpTimer || !(kIOKextSpinDump & gIOKitDebug))
+ return;
+
+ pending = thread_call_cancel(fSpinDumpTimer);
+ if (pending) release();
+}
+
+
+//*********************************************************************************
+// [static] actionSpinDumpTimerExpired
+//
+// Inside PM work loop's gate.
+//*********************************************************************************
+
+IOReturn
+IOService::actionSpinDumpTimerExpired(
+ OSObject * target,
+ void * arg0, void * arg1,
+ void * arg2, void * arg3 )
+{
+ getPMRootDomain()->takeStackshot(false, false, true);
+
+ return kIOReturnSuccess;
+}
+
+//*********************************************************************************
+// spindump_timer_expired
+//
+// Thread call function. Holds a retain while the callout is in flight.
+//*********************************************************************************
+
+void
+IOService::spindump_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
+{
+ IOService * me = (IOService *) arg0;
+
+ if (gIOPMWorkLoop)
+ {
+ gIOPMWorkLoop->runAction(&actionSpinDumpTimerExpired, me);
+ }
+ me->release();
+}
+
+// MARK: -
+// MARK: Client Messaging
+
+//*********************************************************************************
+// [private] tellSystemCapabilityChange
+//*********************************************************************************
+
+void IOService::tellSystemCapabilityChange( uint32_t nextMS )
+{
+ MS_PUSH( nextMS );
+ fMachineState = kIOPM_TellCapabilityChangeDone;
+ fOutOfBandMessage = kIOMessageSystemCapabilityChange;
+
+ if (fIsPreChange)
+ {
+ // Notify app first on pre-change.
+ fOutOfBandParameter = kNotifyCapabilityChangeApps;
+ }
+ else
+ {
+ // Notify kernel clients first on post-change.
+ fOutOfBandParameter = kNotifyCapabilityChangePriority;
+ }
+
+ tellClientsWithResponse( fOutOfBandMessage );
+}
+
+//*********************************************************************************
+// [public] askChangeDown
+//
+// Ask registered applications and kernel clients if we can change to a lower
+// power state.
+//
+// Subclass can override this to send a different message type. Parameter is
+// the destination state number.
+//
+// Return true if we don't have to wait for acknowledgements
+//*********************************************************************************
+
+bool IOService::askChangeDown( unsigned long stateNum )
+{
+ return tellClientsWithResponse( kIOMessageCanDevicePowerOff );
+}
+
+//*********************************************************************************
+// [private] tellChangeDown1
+//
+// Notify registered applications and kernel clients that we are definitely
+// dropping power.
+//
+// Return true if we don't have to wait for acknowledgements
+//*********************************************************************************
+
+bool IOService::tellChangeDown1( unsigned long stateNum )
+{
+ fOutOfBandParameter = kNotifyApps;
+ return tellChangeDown(stateNum);
+}
+
+//*********************************************************************************
+// [private] tellChangeDown2
+//
+// Notify priority clients that we are definitely dropping power.
+//
+// Return true if we don't have to wait for acknowledgements
+//*********************************************************************************
+
+bool IOService::tellChangeDown2( unsigned long stateNum )
+{
+ fOutOfBandParameter = kNotifyPriority;
+ return tellChangeDown(stateNum);
+}
+
+//*********************************************************************************
+// [public] tellChangeDown
+//
+// Notify registered applications and kernel clients that we are definitely
+// dropping power.
+//
+// Subclass can override this to send a different message type. Parameter is
+// the destination state number.
+//
+// Return true if we don't have to wait for acknowledgements
+//*********************************************************************************
+
+bool IOService::tellChangeDown( unsigned long stateNum )
+{
+ return tellClientsWithResponse( kIOMessageDeviceWillPowerOff );
+}
+
+//*********************************************************************************
+// cleanClientResponses
+//
+//*********************************************************************************
+
+static void logAppTimeouts( OSObject * object, void * arg )
+{
+ IOPMInterestContext * context = (IOPMInterestContext *) arg;
+ OSObject * flag;
+ unsigned int clientIndex;
+ int pid = -1;
+ char name[128];
+
+ if (OSDynamicCast(_IOServiceInterestNotifier, object))
+ {
+ // Discover the 'counter' value or index assigned to this client
+ // when it was notified, by searching for the array index of the
+ // client in an array holding the cached interested clients.
+
+ clientIndex = context->notifyClients->getNextIndexOfObject(object, 0);
+
+ if ((clientIndex != (unsigned int) -1) &&
+ (flag = context->responseArray->getObject(clientIndex)) &&
+ (flag != kOSBooleanTrue))
+ {
+ OSNumber *clientID = copyClientIDForNotification(object, context);
+
+ name[0] = '\0';
+ if (clientID) {
+ pid = clientID->unsigned32BitValue();
+ proc_name(pid, name, sizeof(name));
+ clientID->release();
+ }
+
+ PM_ERROR(context->errorLog, pid, name);
+
+ // TODO: record message type if possible
+ IOService::getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsApplicationResponseTimedOut,
+ name, 0, (30*1000), pid, object);
+
+ }
+ }
+}
+
+void IOService::cleanClientResponses( bool logErrors )
+{
+ if (logErrors && fResponseArray)
+ {
+ switch ( fOutOfBandParameter ) {
+ case kNotifyApps:
+ case kNotifyCapabilityChangeApps:
+ if (fNotifyClientArray)
+ {
+ IOPMInterestContext context;
+
+ context.responseArray = fResponseArray;
+ context.notifyClients = fNotifyClientArray;
+ context.serialNumber = fSerialNumber;
+ context.messageType = kIOMessageCopyClientID;
+ context.notifyType = kNotifyApps;
+ context.isPreChange = fIsPreChange;
+ context.enableTracing = false;
+ context.us = this;
+ context.maxTimeRequested = 0;
+ context.stateNumber = fHeadNotePowerState;
+ context.stateFlags = fHeadNotePowerArrayEntry->capabilityFlags;
+ context.changeFlags = fHeadNoteChangeFlags;
+ context.errorLog = "PM notification timeout (pid %d, %s)\n";
+
+ applyToInterested(gIOAppPowerStateInterest, logAppTimeouts, (void *) &context);
+ }
+ break;
+
+ default:
+ // kNotifyPriority, kNotifyCapabilityChangePriority
+ // TODO: identify the priority client that has not acked
+ PM_ERROR("PM priority notification timeout\n");
+ if (gIOKitDebug & kIOLogDebugPower)
+ {
+ panic("PM priority notification timeout");
+ }
+ break;
+ }
+ }
+
+ if (fResponseArray)
+ {
+ fResponseArray->release();
+ fResponseArray = NULL;
+ }
+ if (fNotifyClientArray)
+ {
+ fNotifyClientArray->release();
+ fNotifyClientArray = NULL;
+ }
+}
+
+//*********************************************************************************
+// [protected] tellClientsWithResponse
+//
+// Notify registered applications and kernel clients that we are definitely
+// dropping power.
+//
+// Return true if we don't have to wait for acknowledgements
+//*********************************************************************************
+
+bool IOService::tellClientsWithResponse( int messageType )
+{
+ IOPMInterestContext context;
+ bool isRootDomain = IS_ROOT_DOMAIN;
+ uint32_t maxTimeOut = kMaxTimeRequested;
+
+ PM_ASSERT_IN_GATE();
+ assert( fResponseArray == NULL );
+ assert( fNotifyClientArray == NULL );
+
+ if(messageType == (int)kIOPMMessageLastCallBeforeSleep)
+ RD_LOG("tellClientsWithResponse( kIOPMMessageLastCallBeforeSleep, %d )\n",
+ fOutOfBandParameter);
+ else
+ RD_LOG("tellClientsWithResponse( %s, %d )\n",
+ getIOMessageString(messageType), fOutOfBandParameter);
+
+ fResponseArray = OSArray::withCapacity( 1 );
+ if (!fResponseArray)
+ goto exit;
+
+ fResponseArray->setCapacityIncrement(8);
+ if (++fSerialNumber == 0)
+ fSerialNumber++;
+
+ context.responseArray = fResponseArray;
+ context.notifyClients = 0;
+ context.serialNumber = fSerialNumber;
+ context.messageType = messageType;
+ context.notifyType = fOutOfBandParameter;
+ context.isPreChange = fIsPreChange;
+ context.enableTracing = false;
+ context.us = this;
+ context.maxTimeRequested = 0;
+ context.stateNumber = fHeadNotePowerState;
+ context.stateFlags = fHeadNotePowerArrayEntry->capabilityFlags;
+ context.changeFlags = fHeadNoteChangeFlags;
+ context.messageFilter = (isRootDomain) ?
+ OSMemberFunctionCast(
+ IOPMMessageFilter,
+ this,
+ &IOPMrootDomain::systemMessageFilter) : 0;
+
+ switch ( fOutOfBandParameter ) {
+ case kNotifyApps:
+ applyToInterested( gIOAppPowerStateInterest,
+ pmTellAppWithResponse, (void *) &context );
+
+ if (isRootDomain &&
+ (fMachineState != kIOPM_OurChangeTellClientsPowerDown) &&
+ (fMachineState != kIOPM_SyncTellClientsPowerDown) &&
+ (context.messageType != kIOPMMessageLastCallBeforeSleep))
+ {
+ // Notify capability app for tellChangeDown1()
+ // but not for askChangeDown().
+ context.notifyType = kNotifyCapabilityChangeApps;
+ context.messageType = kIOMessageSystemCapabilityChange;
+ applyToInterested( gIOAppPowerStateInterest,
+ pmTellCapabilityAppWithResponse, (void *) &context );
+ context.notifyType = fOutOfBandParameter;
+ context.messageType = messageType;
+ }
+ if(context.messageType == kIOMessageCanSystemSleep)
+ {
+ maxTimeOut = kCanSleepMaxTimeReq;
+ if(gCanSleepTimeout)
+ {
+ maxTimeOut = (gCanSleepTimeout*us_per_s);
+ }
+ }
+ context.maxTimeRequested = maxTimeOut;
+ applyToInterested( gIOGeneralInterest,
+ pmTellClientWithResponse, (void *) &context );
+
+ fNotifyClientArray = context.notifyClients;
+ break;
+
+ case kNotifyPriority:
+ context.enableTracing = isRootDomain;
+ applyToInterested( gIOPriorityPowerStateInterest,
+ pmTellClientWithResponse, (void *) &context );
+
+ if (isRootDomain)
+ {
+ // Notify capability clients for tellChangeDown2().
+ context.notifyType = kNotifyCapabilityChangePriority;
+ context.messageType = kIOMessageSystemCapabilityChange;
+ applyToInterested( gIOPriorityPowerStateInterest,
+ pmTellCapabilityClientWithResponse, (void *) &context );
+ }
+ break;
+
+ case kNotifyCapabilityChangeApps:
+ applyToInterested( gIOAppPowerStateInterest,
+ pmTellCapabilityAppWithResponse, (void *) &context );
+ fNotifyClientArray = context.notifyClients;
+ if(context.messageType == kIOMessageCanSystemSleep)
+ {
+ maxTimeOut = kCanSleepMaxTimeReq;
+ if(gCanSleepTimeout)
+ {
+ maxTimeOut = (gCanSleepTimeout*us_per_s);
+ }
+ }
+ context.maxTimeRequested = maxTimeOut;
+ break;
+
+ case kNotifyCapabilityChangePriority:
+ applyToInterested( gIOPriorityPowerStateInterest,
+ pmTellCapabilityClientWithResponse, (void *) &context );
+ break;
+ }
+
+ // do we have to wait for somebody?
+ if ( !checkForDone() )
+ {
+ OUR_PMLog(kPMLogStartAckTimer, context.maxTimeRequested, 0);
+ if (context.enableTracing)
+ getPMRootDomain()->traceDetail( context.maxTimeRequested / 1000 );
+ start_ack_timer( context.maxTimeRequested / 1000, kMillisecondScale );
+ return false;
+ }
+
+exit:
+ // everybody responded
+ if (fResponseArray)
+ {
+ fResponseArray->release();
+ fResponseArray = NULL;
+ }
+ if (fNotifyClientArray)
+ {
+ fNotifyClientArray->release();
+ fNotifyClientArray = NULL;
+ }
+
+ return true;
+}
+
+//*********************************************************************************
+// [static private] pmTellAppWithResponse
+//
+// We send a message to an application, and we expect a response, so we compute a
+// cookie we can identify the response with.
+//*********************************************************************************
+
+void IOService::pmTellAppWithResponse( OSObject * object, void * arg )
+{
+ IOPMInterestContext * context = (IOPMInterestContext *) arg;
+ IOServicePM * pwrMgt = context->us->pwrMgt;
+ uint32_t msgIndex, msgRef, msgType;
+ OSNumber *clientID = NULL;
+ proc_t proc = NULL;
+ boolean_t proc_suspended = FALSE;
+ OSObject * waitForReply = kOSBooleanTrue;
+#if LOG_APP_RESPONSE_TIMES
+ AbsoluteTime now;
+#endif
+
+ if (!OSDynamicCast(_IOServiceInterestNotifier, object))
+ return;
+
+ if (context->us == getPMRootDomain())
+ {
+ if ((clientID = copyClientIDForNotification(object, context)))
+ {
+ uint32_t clientPID = clientID->unsigned32BitValue();
+ clientID->release();
+ proc = proc_find(clientPID);
+
+ if (proc)
+ {
+ proc_suspended = get_task_pidsuspended((task_t) proc->task);
+ proc_rele(proc);
+
+ if (proc_suspended)
+ {
+ logClientIDForNotification(object, context, "PMTellAppWithResponse - Suspended");
+ return;
+ }
+ }
+ }
+ }
+
+ if (context->messageFilter &&
+ !context->messageFilter(context->us, object, context, 0, &waitForReply))
+ {
+ if (kIOLogDebugPower & gIOKitDebug)
+ {
+ logClientIDForNotification(object, context, "DROP App");
+ }
+ return;
+ }
+
+ // Create client array (for tracking purposes) only if the service
+ // has app clients. Usually only root domain does.
+ if (0 == context->notifyClients)
+ context->notifyClients = OSArray::withCapacity( 32 );
+
+ msgType = context->messageType;
+ msgIndex = context->responseArray->getCount();
+ msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
+
+ OUR_PMLog(kPMLogAppNotify, msgType, msgRef);
+ if (kIOLogDebugPower & gIOKitDebug)
+ {
+ logClientIDForNotification(object, context, "MESG App");
+ }
+
+ if (waitForReply == kOSBooleanTrue)
+ {
+#if LOG_APP_RESPONSE_TIMES
+ OSNumber * num;
+ clock_get_uptime(&now);
+ num = OSNumber::withNumber(AbsoluteTime_to_scalar(&now), sizeof(uint64_t) * 8);
+ if (num)
+ {
+ context->responseArray->setObject(msgIndex, num);
+ num->release();
+ }
+ else
+#endif
+ context->responseArray->setObject(msgIndex, kOSBooleanFalse);
+ }
+ else
+ {
+ context->responseArray->setObject(msgIndex, kOSBooleanTrue);
+ if (kIOLogDebugPower & gIOKitDebug)
+ {
+ logClientIDForNotification(object, context, "App response ignored");
+ }
+ }
+
+ if (context->notifyClients)
+ context->notifyClients->setObject(msgIndex, object);
+
+ context->us->messageClient(msgType, object, (void *)(uintptr_t) msgRef);
+}
+
+//*********************************************************************************
+// [static private] pmTellClientWithResponse
+//
+// We send a message to an in-kernel client, and we expect a response,
+// so we compute a cookie we can identify the response with.
+//*********************************************************************************
+
+void IOService::pmTellClientWithResponse( OSObject * object, void * arg )
+{
+ IOPowerStateChangeNotification notify;
+ IOPMInterestContext * context = (IOPMInterestContext *) arg;
+ OSObject * replied = kOSBooleanTrue;
+ _IOServiceInterestNotifier * notifier;
+ uint32_t msgIndex, msgRef, msgType;
+ IOReturn retCode;
+
+ if (context->messageFilter &&
+ !context->messageFilter(context->us, object, context, 0, 0))
+ {
+ if ((kIOLogDebugPower & gIOKitDebug) &&
+ (OSDynamicCast(_IOServiceInterestNotifier, object)))
+ {
+ _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
+ PM_LOG("%s DROP Client %s, notifier %p, handler %p\n",
+ context->us->getName(),
+ getIOMessageString(context->messageType),
+ OBFUSCATE(object), OBFUSCATE(n->handler));
+ }
+ return;
+ }
+
+ notifier = OSDynamicCast(_IOServiceInterestNotifier, object);
+ msgType = context->messageType;
+ msgIndex = context->responseArray->getCount();
+ msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
+
+ IOServicePM * pwrMgt = context->us->pwrMgt;
+ if (gIOKitDebug & kIOLogPower) {
+ OUR_PMLog(kPMLogClientNotify, msgRef, msgType);
+ if (OSDynamicCast(IOService, object)) {
+ const char *who = ((IOService *) object)->getName();
+ gPlatform->PMLog(who, kPMLogClientNotify, (uintptr_t) object, 0);
+ }
+ else if (notifier) {
+ OUR_PMLog(kPMLogClientNotify, (uintptr_t) notifier->handler, 0);
+ }
+ }
+ if ((kIOLogDebugPower & gIOKitDebug) && notifier)
+ {
+ PM_LOG("%s MESG Client %s, notifier %p, handler %p\n",
+ context->us->getName(),
+ getIOMessageString(msgType),
+ OBFUSCATE(object), OBFUSCATE(notifier->handler));
+ }
+
+ notify.powerRef = (void *)(uintptr_t) msgRef;
+ notify.returnValue = 0;
+ notify.stateNumber = context->stateNumber;
+ notify.stateFlags = context->stateFlags;
+
+ if (context->enableTracing && (notifier != 0))
+ {
+ uint32_t detail = ((msgIndex & 0xff) << 24) |
+ ((msgType & 0xfff) << 12) |
+ (((uintptr_t) notifier->handler) & 0xfff);
+ getPMRootDomain()->traceDetail( detail );
+ }
+
+ retCode = context->us->messageClient(msgType, object, (void *) ¬ify, sizeof(notify));
+
+ if (kIOReturnSuccess == retCode)
+ {
+ if (0 == notify.returnValue) {
+ OUR_PMLog(kPMLogClientAcknowledge, msgRef, (uintptr_t) object);
+ } else {
+ replied = kOSBooleanFalse;
+ if ( notify.returnValue > context->maxTimeRequested )
+ {
+ if (notify.returnValue > kPriorityClientMaxWait)
+ {
+ context->maxTimeRequested = kPriorityClientMaxWait;
+ PM_ERROR("%s: client %p returned %llu for %s\n",
+ context->us->getName(),
+ notifier ? (void *) OBFUSCATE(notifier->handler) : OBFUSCATE(object),
+ (uint64_t) notify.returnValue,
+ getIOMessageString(msgType));
+ }
+ else
+ context->maxTimeRequested = notify.returnValue;
+ }
+ }
+ } else {
+ // not a client of ours
+ // so we won't be waiting for response
+ OUR_PMLog(kPMLogClientAcknowledge, msgRef, 0);
+ }
+
+ context->responseArray->setObject(msgIndex, replied);
+}
+
+//*********************************************************************************
+// [static private] pmTellCapabilityAppWithResponse
+//*********************************************************************************
+
+void IOService::pmTellCapabilityAppWithResponse( OSObject * object, void * arg )
+{
+ IOPMSystemCapabilityChangeParameters msgArg;
+ IOPMInterestContext * context = (IOPMInterestContext *) arg;
+ OSObject * replied = kOSBooleanTrue;
+ IOServicePM * pwrMgt = context->us->pwrMgt;
+ uint32_t msgIndex, msgRef, msgType;
+#if LOG_APP_RESPONSE_TIMES
+ AbsoluteTime now;
+#endif
+
+ if (!OSDynamicCast(_IOServiceInterestNotifier, object))
+ return;
+
+ memset(&msgArg, 0, sizeof(msgArg));
+ if (context->messageFilter &&
+ !context->messageFilter(context->us, object, context, &msgArg, &replied))
+ {
+ return;
+ }
+
+ // Create client array (for tracking purposes) only if the service
+ // has app clients. Usually only root domain does.
+ if (0 == context->notifyClients)
+ context->notifyClients = OSArray::withCapacity( 32 );
+
+ msgType = context->messageType;
+ msgIndex = context->responseArray->getCount();
+ msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
+
+ OUR_PMLog(kPMLogAppNotify, msgType, msgRef);
+ if (kIOLogDebugPower & gIOKitDebug)
+ {
+ // Log client pid/name and client array index.
+ OSNumber * clientID = NULL;
+ OSString * clientIDString = NULL;;
+ context->us->messageClient(kIOMessageCopyClientID, object, &clientID);
+ if (clientID) {
+ clientIDString = IOCopyLogNameForPID(clientID->unsigned32BitValue());
+ }
+
+ PM_LOG("%s MESG App(%u) %s, wait %u, %s\n",
+ context->us->getName(),
+ msgIndex, getIOMessageString(msgType),
+ (replied != kOSBooleanTrue),
+ clientIDString ? clientIDString->getCStringNoCopy() : "");
+ if (clientID) clientID->release();
+ if (clientIDString) clientIDString->release();
+ }
+
+ msgArg.notifyRef = msgRef;
+ msgArg.maxWaitForReply = 0;
+
+ if (replied == kOSBooleanTrue)
+ {
+ msgArg.notifyRef = 0;
+ context->responseArray->setObject(msgIndex, kOSBooleanTrue);
+ if (context->notifyClients)
+ context->notifyClients->setObject(msgIndex, kOSBooleanTrue);
+ }
+ else
+ {
+#if LOG_APP_RESPONSE_TIMES
+ OSNumber * num;
+ clock_get_uptime(&now);
+ num = OSNumber::withNumber(AbsoluteTime_to_scalar(&now), sizeof(uint64_t) * 8);
+ if (num)
+ {
+ context->responseArray->setObject(msgIndex, num);
+ num->release();
+ }
+ else
+#endif
+ context->responseArray->setObject(msgIndex, kOSBooleanFalse);
+
+ if (context->notifyClients)
+ context->notifyClients->setObject(msgIndex, object);
+ }
+
+ context->us->messageClient(msgType, object, (void *) &msgArg, sizeof(msgArg));
+}
+
+//*********************************************************************************
+// [static private] pmTellCapabilityClientWithResponse
+//*********************************************************************************
+
+void IOService::pmTellCapabilityClientWithResponse(
+ OSObject * object, void * arg )
+{
+ IOPMSystemCapabilityChangeParameters msgArg;
+ IOPMInterestContext * context = (IOPMInterestContext *) arg;
+ OSObject * replied = kOSBooleanTrue;
+ _IOServiceInterestNotifier * notifier;
+ uint32_t msgIndex, msgRef, msgType;
+ IOReturn retCode;
+
+ memset(&msgArg, 0, sizeof(msgArg));
+ if (context->messageFilter &&
+ !context->messageFilter(context->us, object, context, &msgArg, 0))
+ {
+ if ((kIOLogDebugPower & gIOKitDebug) &&
+ (OSDynamicCast(_IOServiceInterestNotifier, object)))
+ {
+ _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
+ PM_LOG("%s DROP Client %s, notifier %p, handler %p\n",
+ context->us->getName(),
+ getIOMessageString(context->messageType),
+ OBFUSCATE(object), OBFUSCATE(n->handler));
+ }
+ return;
+ }
+
+ notifier = OSDynamicCast(_IOServiceInterestNotifier, object);
+ msgType = context->messageType;
+ msgIndex = context->responseArray->getCount();
+ msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
+
+ IOServicePM * pwrMgt = context->us->pwrMgt;
+ if (gIOKitDebug & kIOLogPower) {
+ OUR_PMLog(kPMLogClientNotify, msgRef, msgType);
+ if (OSDynamicCast(IOService, object)) {
+ const char *who = ((IOService *) object)->getName();
+ gPlatform->PMLog(who, kPMLogClientNotify, (uintptr_t) object, 0);
+ }
+ else if (notifier) {
+ OUR_PMLog(kPMLogClientNotify, (uintptr_t) notifier->handler, 0);
+ }
+ }
+ if ((kIOLogDebugPower & gIOKitDebug) && notifier)
+ {
+ PM_LOG("%s MESG Client %s, notifier %p, handler %p\n",
+ context->us->getName(),
+ getIOMessageString(msgType),
+ OBFUSCATE(object), OBFUSCATE(notifier->handler));
+ }
+
+ msgArg.notifyRef = msgRef;
+ msgArg.maxWaitForReply = 0;
+
+ if (context->enableTracing && (notifier != 0))
+ {
+ uint32_t detail = ((msgIndex & 0xff) << 24) |
+ ((msgType & 0xfff) << 12) |
+ (((uintptr_t) notifier->handler) & 0xfff);
+ getPMRootDomain()->traceDetail( detail );
+ }
+
+ retCode = context->us->messageClient(
+ msgType, object, (void *) &msgArg, sizeof(msgArg));
+
+ if ( kIOReturnSuccess == retCode )
+ {
+ if ( 0 == msgArg.maxWaitForReply )
+ {
+ // client doesn't want time to respond
+ OUR_PMLog(kPMLogClientAcknowledge, msgRef, (uintptr_t) object);
+ }
+ else
+ {
+ replied = kOSBooleanFalse;
+ if ( msgArg.maxWaitForReply > context->maxTimeRequested )
+ {
+ if (msgArg.maxWaitForReply > kCapabilityClientMaxWait)
+ {
+ context->maxTimeRequested = kCapabilityClientMaxWait;
+ PM_ERROR("%s: client %p returned %u for %s\n",
+ context->us->getName(),
+ notifier ? (void *) OBFUSCATE(notifier->handler) : OBFUSCATE(object),
+ msgArg.maxWaitForReply,
+ getIOMessageString(msgType));
+ }
+ else
+ context->maxTimeRequested = msgArg.maxWaitForReply;
+ }
+ }
+ }
+ else
+ {
+ // not a client of ours
+ // so we won't be waiting for response
+ OUR_PMLog(kPMLogClientAcknowledge, msgRef, 0);
+ }
+
+ context->responseArray->setObject(msgIndex, replied);
+}
+
+//*********************************************************************************
+// [public] tellNoChangeDown
+//
+// Notify registered applications and kernel clients that we are not
+// dropping power.
+//
+// Subclass can override this to send a different message type. Parameter is
+// the aborted destination state number.
+//*********************************************************************************
+
+void IOService::tellNoChangeDown( unsigned long )
+{
+ return tellClients( kIOMessageDeviceWillNotPowerOff );
+}
+
+//*********************************************************************************
+// [public] tellChangeUp
+//
+// Notify registered applications and kernel clients that we are raising power.
+//
+// Subclass can override this to send a different message type. Parameter is
+// the aborted destination state number.
+//*********************************************************************************
+
+void IOService::tellChangeUp( unsigned long )
+{
+ return tellClients( kIOMessageDeviceHasPoweredOn );
+}
+
+//*********************************************************************************
+// [protected] tellClients
+//
+// Notify registered applications and kernel clients of something.
+//*********************************************************************************
+
+void IOService::tellClients( int messageType )
+{
+ IOPMInterestContext context;
+
+ RD_LOG("tellClients( %s )\n", getIOMessageString(messageType));
+
+ memset(&context, 0, sizeof(context));
+ context.messageType = messageType;
+ context.isPreChange = fIsPreChange;
+ context.us = this;
+ context.stateNumber = fHeadNotePowerState;
+ context.stateFlags = fHeadNotePowerArrayEntry->capabilityFlags;
+ context.changeFlags = fHeadNoteChangeFlags;
+ context.messageFilter = (IS_ROOT_DOMAIN) ?
+ OSMemberFunctionCast(
+ IOPMMessageFilter,
+ this,
+ &IOPMrootDomain::systemMessageFilter) : 0;
+
+ context.notifyType = kNotifyPriority;
+ applyToInterested( gIOPriorityPowerStateInterest,
+ tellKernelClientApplier, (void *) &context );
+
+ context.notifyType = kNotifyApps;
+ applyToInterested( gIOAppPowerStateInterest,
+ tellAppClientApplier, (void *) &context );
+
+ applyToInterested( gIOGeneralInterest,
+ tellKernelClientApplier, (void *) &context );
+}
+
+//*********************************************************************************
+// [private] tellKernelClientApplier
+//
+// Message a kernel client.
+//*********************************************************************************
+
+static void tellKernelClientApplier( OSObject * object, void * arg )
+{
+ IOPowerStateChangeNotification notify;
+ IOPMInterestContext * context = (IOPMInterestContext *) arg;
+
+ if (context->messageFilter &&
+ !context->messageFilter(context->us, object, context, 0, 0))
+ {
+ if ((kIOLogDebugPower & gIOKitDebug) &&
+ (OSDynamicCast(_IOServiceInterestNotifier, object)))
+ {
+ _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
+ PM_LOG("%s DROP Client %s, notifier %p, handler %p\n",
+ context->us->getName(),
+ IOService::getIOMessageString(context->messageType),
+ OBFUSCATE(object), OBFUSCATE(n->handler));
+ }
+ return;
+ }
+
+ notify.powerRef = (void *) 0;
+ notify.returnValue = 0;
+ notify.stateNumber = context->stateNumber;
+ notify.stateFlags = context->stateFlags;
+
+ context->us->messageClient(context->messageType, object, ¬ify, sizeof(notify));
+
+ if ((kIOLogDebugPower & gIOKitDebug) &&
+ (OSDynamicCast(_IOServiceInterestNotifier, object)))
+ {
+ _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
+ PM_LOG("%s MESG Client %s, notifier %p, handler %p\n",
+ context->us->getName(),
+ IOService::getIOMessageString(context->messageType),
+ OBFUSCATE(object), OBFUSCATE(n->handler));
+ }
+}
+
+static OSNumber * copyClientIDForNotification(
+ OSObject *object,
+ IOPMInterestContext *context)
+{
+ OSNumber *clientID = NULL;
+ context->us->messageClient(kIOMessageCopyClientID, object, &clientID);
+ return clientID;
+}
+
+static void logClientIDForNotification(
+ OSObject *object,
+ IOPMInterestContext *context,
+ const char *logString)
+{
+ OSString *logClientID = NULL;
+ OSNumber *clientID = copyClientIDForNotification(object, context);
+
+ if (logString)
+ {
+ if (clientID)
+ logClientID = IOCopyLogNameForPID(clientID->unsigned32BitValue());
+
+ PM_LOG("%s %s %s, %s\n",
+ context->us->getName(), logString,
+ IOService::getIOMessageString(context->messageType),
+ logClientID ? logClientID->getCStringNoCopy() : "");
+
+ if (logClientID)
+ logClientID->release();
+ }
+
+ if (clientID)
+ clientID->release();
+
+ return;
+}
+
+static void tellAppClientApplier( OSObject * object, void * arg )
+{
+ IOPMInterestContext * context = (IOPMInterestContext *) arg;
+ OSNumber * clientID = NULL;
+ proc_t proc = NULL;
+ boolean_t proc_suspended = FALSE;
+
+ if (context->us == IOService::getPMRootDomain())
+ {
+ if ((clientID = copyClientIDForNotification(object, context)))
+ {
+ uint32_t clientPID = clientID->unsigned32BitValue();
+ clientID->release();
+ proc = proc_find(clientPID);
+
+ if (proc)
+ {
+ proc_suspended = get_task_pidsuspended((task_t) proc->task);
+ proc_rele(proc);
+
+ if (proc_suspended)
+ {
+ logClientIDForNotification(object, context, "tellAppClientApplier - Suspended");
+ return;
+ }
+ }
+ }
+ }
+
+ if (context->messageFilter &&
+ !context->messageFilter(context->us, object, context, 0, 0))
+ {
+ if (kIOLogDebugPower & gIOKitDebug)
+ {
+ logClientIDForNotification(object, context, "DROP App");
+ }
+ return;
+ }
+
+ if (kIOLogDebugPower & gIOKitDebug)
+ {
+ logClientIDForNotification(object, context, "MESG App");
+ }
+
+ context->us->messageClient(context->messageType, object, 0);
+}
+
+//*********************************************************************************
+// [private] checkForDone
+//*********************************************************************************
+
+bool IOService::checkForDone( void )
+{
+ int i = 0;
+ OSObject * theFlag;
+
+ if (fResponseArray == NULL) {
+ return true;
+ }
+
+ for (i = 0; ; i++) {
+ theFlag = fResponseArray->getObject(i);
+
+ if (NULL == theFlag) {
+ break;
+ }
+
+ if (kOSBooleanTrue != theFlag) {
+ return false;
+ }
+ }
+ return true;
+}
+
+//*********************************************************************************
+// [public] responseValid
+//*********************************************************************************
+
+bool IOService::responseValid( uint32_t refcon, int pid )
+{
+ UInt16 serialComponent;
+ UInt16 ordinalComponent;
+ OSObject * theFlag;
+ OSObject *object = 0;
+
+ serialComponent = (refcon >> 16) & 0xFFFF;
+ ordinalComponent = (refcon & 0xFFFF);
+
+ if ( serialComponent != fSerialNumber )
+ {
+ return false;
+ }
+
+ if ( fResponseArray == NULL )
+ {
+ return false;
+ }
+
+ theFlag = fResponseArray->getObject(ordinalComponent);
+
+ if ( theFlag == 0 )
+ {
+ return false;
+ }
+
+ if (fNotifyClientArray)
+ object = fNotifyClientArray->getObject(ordinalComponent);
+
+ OSNumber * num;
+ if ((num = OSDynamicCast(OSNumber, theFlag)))
+ {
+#if LOG_APP_RESPONSE_TIMES
+ AbsoluteTime now;
+ AbsoluteTime start;
+ uint64_t nsec;
+ char name[128];
+
+ name[0] = '\0';
+ proc_name(pid, name, sizeof(name));
+ clock_get_uptime(&now);
+ AbsoluteTime_to_scalar(&start) = num->unsigned64BitValue();
+ SUB_ABSOLUTETIME(&now, &start);
+ absolutetime_to_nanoseconds(now, &nsec);
+
+ if (kIOLogDebugPower & gIOKitDebug)
+ {
+ PM_LOG("Ack(%u) %u ms\n",
+ (uint32_t) ordinalComponent,
+ NS_TO_MS(nsec));
+ }
+
+ // > 100 ms
+ if (nsec > LOG_APP_RESPONSE_TIMES)
+ {
+ IOLog("PM response took %d ms (%d, %s)\n", NS_TO_MS(nsec),
+ pid, name);
+ }
+
+ if (nsec > LOG_APP_RESPONSE_MSG_TRACER)
+ {
+ // TODO: populate the messageType argument
+ getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsApplicationResponseSlow,
+ name, 0, NS_TO_MS(nsec), pid, object);
+ }
+ else
+ {
+ getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsApplicationResponsePrompt,
+ name, 0, NS_TO_MS(nsec), pid, object);
+ }
+
+#endif
+ theFlag = kOSBooleanFalse;
+ }
+ else if (object) {
+ getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsApplicationResponsePrompt,
+ 0, 0, 0, pid, object);
+
+ }
+
+ if ( kOSBooleanFalse == theFlag )
+ {
+ fResponseArray->replaceObject(ordinalComponent, kOSBooleanTrue);
+ }
+
+ return true;
+}
+
+//*********************************************************************************
+// [public] allowPowerChange
+//
+// Our power state is about to lower, and we have notified applications
+// and kernel clients, and one of them has acknowledged. If this is the last to do
+// so, and all acknowledgements are positive, we continue with the power change.
+//*********************************************************************************
+
+IOReturn IOService::allowPowerChange( unsigned long refcon )
+{
+ IOPMRequest * request;
+
+ if ( !initialized )
+ {
+ // we're unloading
+ return kIOReturnSuccess;
+ }
+
+ request = acquirePMRequest( this, kIOPMRequestTypeAllowPowerChange );
+ if (!request)
+ return kIOReturnNoMemory;
+
+ request->fArg0 = (void *) refcon;
+ request->fArg1 = (void *)(uintptr_t) proc_selfpid();
+ request->fArg2 = (void *) 0;
+ submitPMRequest( request );
+
+ return kIOReturnSuccess;
+}
+
+#ifndef __LP64__
+IOReturn IOService::serializedAllowPowerChange2( unsigned long refcon )
+{
+ // [deprecated] public
+ return kIOReturnUnsupported;
+}
+#endif /* !__LP64__ */
+
+//*********************************************************************************
+// [public] cancelPowerChange
+//
+// Our power state is about to lower, and we have notified applications
+// and kernel clients, and one of them has vetoed the change. If this is the last
+// client to respond, we abandon the power change.
+//*********************************************************************************
+
+IOReturn IOService::cancelPowerChange( unsigned long refcon )
+{
+ IOPMRequest * request;
+ char name[128];
+ pid_t pid = proc_selfpid();
+
+ if ( !initialized )
+ {
+ // we're unloading
+ return kIOReturnSuccess;
+ }
+
+ name[0] = '\0';
+ proc_name(pid, name, sizeof(name));
+ PM_ERROR("PM notification cancel (pid %d, %s)\n", pid, name);
+
+ request = acquirePMRequest( this, kIOPMRequestTypeCancelPowerChange );
+ if (!request)
+ {
+ return kIOReturnNoMemory;
+ }
+
+ request->fArg0 = (void *) refcon;
+ request->fArg1 = (void *)(uintptr_t) proc_selfpid();
+ request->fArg2 = (void *) OSString::withCString(name);
+ submitPMRequest( request );
+
+ return kIOReturnSuccess;
+}
+
+#ifndef __LP64__
+IOReturn IOService::serializedCancelPowerChange2( unsigned long refcon )
+{
+ // [deprecated] public
+ return kIOReturnUnsupported;
+}
+
+//*********************************************************************************
+// PM_Clamp_Timer_Expired
+//
+// called when clamp timer expires...set power state to 0.
+//*********************************************************************************
+
+void IOService::PM_Clamp_Timer_Expired( void )
+{
+}
+
+//*********************************************************************************
+// clampPowerOn
+//
+// Set to highest available power state for a minimum of duration milliseconds
+//*********************************************************************************
+
+void IOService::clampPowerOn( unsigned long duration )
+{
+}
+#endif /* !__LP64__ */
+
+//*********************************************************************************
+// configurePowerStateReport
+//
+// Configures the IOStateReport for kPMPowerStateChannel
+//*********************************************************************************
+IOReturn IOService::configurePowerStatesReport( IOReportConfigureAction action, void *result )
+{
+
+ IOReturn rc = kIOReturnSuccess;
+ size_t reportSize;
+ unsigned long i;
+ uint64_t ts;
+
+ if (!pwrMgt)
+ return kIOReturnUnsupported;
+
+ if (!fNumberOfPowerStates)
+ return kIOReturnSuccess; // For drivers which are in power plane, but haven't called registerPowerDriver()
+ PM_LOCK();
+
+ switch (action)
+ {
+ case kIOReportEnable:
+ if (fReportBuf)
+ {
+ fReportClientCnt++;
+ break;
+ }
+ reportSize = STATEREPORT_BUFSIZE(fNumberOfPowerStates);
+ fReportBuf = IOMalloc(reportSize);
+ if (!fReportBuf) {
+ rc = kIOReturnNoMemory;
+ break;
+ }
+ memset(fReportBuf, 0, reportSize);
+
+ STATEREPORT_INIT(fNumberOfPowerStates, fReportBuf, reportSize,
+ getRegistryEntryID(), kPMPowerStatesChID, kIOReportCategoryPower);
+
+ for (i = 0; i < fNumberOfPowerStates; i++) {
+ unsigned bits = 0;
+
+ if (fPowerStates[i].capabilityFlags & kIOPMPowerOn)
+ bits |= kPMReportPowerOn;
+ if (fPowerStates[i].capabilityFlags & kIOPMDeviceUsable)
+ bits |= kPMReportDeviceUsable;
+ if (fPowerStates[i].capabilityFlags & kIOPMLowPower)
+ bits |= kPMReportLowPower;
+
+ STATEREPORT_SETSTATEID(fReportBuf, i, ((bits & 0xff) << 8) |
+ ((StateOrder(fMaxPowerState) & 0xf) << 4) | (StateOrder(i) & 0xf));
+ }
+ ts = mach_absolute_time();
+ STATEREPORT_SETSTATE(fReportBuf, fCurrentPowerState, ts);
+ break;
+
+ case kIOReportDisable:
+ if (fReportClientCnt == 0) {
+ rc = kIOReturnBadArgument;
+ break;
+ }
+ if (fReportClientCnt == 1)
+ {
+ IOFree(fReportBuf, STATEREPORT_BUFSIZE(fNumberOfPowerStates));
+ fReportBuf = NULL;
+ }
+ fReportClientCnt--;
+ break;
+
+ case kIOReportGetDimensions:
+ if (fReportBuf)
+ STATEREPORT_UPDATERES(fReportBuf, kIOReportGetDimensions, result);
+ break;
+ }
+
+ PM_UNLOCK();
+
+ return rc;
+}
+
+//*********************************************************************************
+// updatePowerStateReport
+//
+// Updates the IOStateReport for kPMPowerStateChannel
+//*********************************************************************************
+IOReturn IOService::updatePowerStatesReport( IOReportConfigureAction action, void *result, void *destination )
+{
+ uint32_t size2cpy;
+ void *data2cpy;
+ uint64_t ts;
+ IOReturn rc = kIOReturnSuccess;
+ IOBufferMemoryDescriptor *dest = OSDynamicCast(IOBufferMemoryDescriptor, (OSObject *)destination);
+
+
+ if (!pwrMgt)
+ return kIOReturnUnsupported;
+ if (!fNumberOfPowerStates)
+ return kIOReturnSuccess;
+
+ if ( !result || !dest ) return kIOReturnBadArgument;
+ PM_LOCK();
+
+ switch (action) {
+ case kIOReportCopyChannelData:
+ if ( !fReportBuf ) {
+ rc = kIOReturnNotOpen;
+ break;
+ }
+
+ ts = mach_absolute_time();
+ STATEREPORT_UPDATEPREP(fReportBuf, ts, data2cpy, size2cpy);
+ if (size2cpy > (dest->getCapacity() - dest->getLength()) ) {
+ rc = kIOReturnOverrun;
+ break;
+ }
+
+ STATEREPORT_UPDATERES(fReportBuf, kIOReportCopyChannelData, result);
+ dest->appendBytes(data2cpy, size2cpy);
+
+ default:
+ break;
+
+ }
+
+ PM_UNLOCK();
+
+ return rc;
+
+}
+
+//*********************************************************************************
+// configureSimplePowerReport
+//
+// Configures the IOSimpleReport for given channel id
+//*********************************************************************************
+IOReturn IOService::configureSimplePowerReport(IOReportConfigureAction action, void *result )
+{
+
+ IOReturn rc = kIOReturnSuccess;
+
+ if ( !pwrMgt )
+ return kIOReturnUnsupported;
+
+ if ( !fNumberOfPowerStates )
+ return rc;
+
+ switch (action)
+ {
+ case kIOReportEnable:
+ case kIOReportDisable:
+ break;
+
+ case kIOReportGetDimensions:
+ SIMPLEREPORT_UPDATERES(kIOReportGetDimensions, result);
+ break;
+ }
+
+
+ return rc;
+}
+
+//*********************************************************************************
+// updateSimplePowerReport
+//
+// Updates the IOSimpleReport for the given chanel id
+//*********************************************************************************
+IOReturn IOService::updateSimplePowerReport( IOReportConfigureAction action, void *result, void *destination )
+{
+ uint32_t size2cpy;
+ void *data2cpy;
+ uint64_t buf[SIMPLEREPORT_BUFSIZE/sizeof(uint64_t)+1]; // Force a 8-byte alignment
+ IOBufferMemoryDescriptor *dest = OSDynamicCast(IOBufferMemoryDescriptor, (OSObject *)destination);
+ IOReturn rc = kIOReturnSuccess;
+ unsigned bits = 0;
+
+
+ if ( !pwrMgt )
+ return kIOReturnUnsupported;
+ if ( !result || !dest ) return kIOReturnBadArgument;
+
+ if ( !fNumberOfPowerStates )
+ return rc;
+ PM_LOCK();
+
+ switch (action) {
+ case kIOReportCopyChannelData:
+
+ SIMPLEREPORT_INIT(buf, sizeof(buf), getRegistryEntryID(), kPMCurrStateChID, kIOReportCategoryPower);
+
+ if (fPowerStates[fCurrentPowerState].capabilityFlags & kIOPMPowerOn)
+ bits |= kPMReportPowerOn;
+ if (fPowerStates[fCurrentPowerState].capabilityFlags & kIOPMDeviceUsable)
+ bits |= kPMReportDeviceUsable;
+ if (fPowerStates[fCurrentPowerState].capabilityFlags & kIOPMLowPower)
+ bits |= kPMReportLowPower;
+
+
+ SIMPLEREPORT_SETVALUE(buf, ((bits & 0xff) << 8) | ((StateOrder(fMaxPowerState) & 0xf) << 4) |
+ (StateOrder(fCurrentPowerState) & 0xf));
+
+ SIMPLEREPORT_UPDATEPREP(buf, data2cpy, size2cpy);
+ if (size2cpy > (dest->getCapacity() - dest->getLength())) {
+ rc = kIOReturnOverrun;
+ break;
+ }
+
+ SIMPLEREPORT_UPDATERES(kIOReportCopyChannelData, result);
+ dest->appendBytes(data2cpy, size2cpy);
+
+ default:
+ break;
+
+ }
+
+ PM_UNLOCK();
+
+ return kIOReturnSuccess;
+
+}
+
+
+
+// MARK: -
+// MARK: Driver Overrides
+
+//*********************************************************************************
+// [public] setPowerState
+//
+// Does nothing here. This should be implemented in a subclass driver.
+//*********************************************************************************
+
+IOReturn IOService::setPowerState(
+ unsigned long powerStateOrdinal, IOService * whatDevice )
+{
+ return IOPMNoErr;
+}
+
+//*********************************************************************************
+// [public] maxCapabilityForDomainState
+//
+// Finds the highest power state in the array whose input power requirement
+// is equal to the input parameter. Where a more intelligent decision is
+// possible, override this in the subclassed driver.
+//*********************************************************************************
+
+IOPMPowerStateIndex IOService::getPowerStateForDomainFlags( IOPMPowerFlags flags )
+{
+ IOPMPowerStateIndex stateIndex;
+
+ if (!fNumberOfPowerStates)
+ return kPowerStateZero;
+
+ for ( int order = fNumberOfPowerStates - 1; order >= 0; order-- )
+ {
+ stateIndex = fPowerStates[order].stateOrderToIndex;
+
+ if ( (flags & fPowerStates[stateIndex].inputPowerFlags) ==
+ fPowerStates[stateIndex].inputPowerFlags )
+ {
+ return stateIndex;
+ }
+ }
+ return kPowerStateZero;
+}
+
+unsigned long IOService::maxCapabilityForDomainState( IOPMPowerFlags domainState )
+{
+ return getPowerStateForDomainFlags(domainState);
+}
+
+//*********************************************************************************
+// [public] initialPowerStateForDomainState
+//
+// Called to query the power state for the initial power transition.
+//*********************************************************************************
+
+unsigned long IOService::initialPowerStateForDomainState( IOPMPowerFlags domainState )
+{
+ if (fResetPowerStateOnWake && (domainState & kIOPMRootDomainState))
+ {
+ // Return lowest power state for any root power domain changes
+ return kPowerStateZero;
+ }
+
+ return getPowerStateForDomainFlags(domainState);
+}
+
+//*********************************************************************************
+// [public] powerStateForDomainState
+//
+// This method is not called from PM.
+//*********************************************************************************
+
+unsigned long IOService::powerStateForDomainState( IOPMPowerFlags domainState )
+{
+ return getPowerStateForDomainFlags(domainState);
+}
+
+#ifndef __LP64__
+//*********************************************************************************
+// [deprecated] didYouWakeSystem
+//
+// Does nothing here. This should be implemented in a subclass driver.
+//*********************************************************************************
+
+bool IOService::didYouWakeSystem( void )
+{
+ return false;
+}
+#endif /* !__LP64__ */
+
+//*********************************************************************************
+// [public] powerStateWillChangeTo
+//
+// Does nothing here. This should be implemented in a subclass driver.
+//*********************************************************************************
+
+IOReturn IOService::powerStateWillChangeTo( IOPMPowerFlags, unsigned long, IOService * )
+{
+ return kIOPMAckImplied;
+}
+
+//*********************************************************************************
+// [public] powerStateDidChangeTo
+//
+// Does nothing here. This should be implemented in a subclass driver.
+//*********************************************************************************
+
+IOReturn IOService::powerStateDidChangeTo( IOPMPowerFlags, unsigned long, IOService * )
+{
+ return kIOPMAckImplied;
+}
+
+//*********************************************************************************
+// [protected] powerChangeDone
+//
+// Called from PM work loop thread.
+// Does nothing here. This should be implemented in a subclass policy-maker.
+//*********************************************************************************
+
+void IOService::powerChangeDone( unsigned long )
+{
+}
+
+#ifndef __LP64__
+//*********************************************************************************
+// [deprecated] newTemperature
+//
+// Does nothing here. This should be implemented in a subclass driver.
+//*********************************************************************************
+
+IOReturn IOService::newTemperature( long currentTemp, IOService * whichZone )
+{
+ return IOPMNoErr;
+}
+#endif /* !__LP64__ */
+
+//*********************************************************************************
+// [public] systemWillShutdown
+//
+// System shutdown and restart notification.
+//*********************************************************************************
+
+void IOService::systemWillShutdown( IOOptionBits specifier )
+{
+ IOPMrootDomain * rootDomain = IOService::getPMRootDomain();
+ if (rootDomain)
+ rootDomain->acknowledgeSystemWillShutdown( this );
+}
+
+// MARK: -
+// MARK: PM State Machine
+
+//*********************************************************************************
+// [private static] acquirePMRequest
+//*********************************************************************************
+
+IOPMRequest *
+IOService::acquirePMRequest( IOService * target, IOOptionBits requestType,
+ IOPMRequest * active )
+{
+ IOPMRequest * request;
+
+ assert(target);
+
+ request = IOPMRequest::create();
+ if (request)
+ {
+ request->init( target, requestType );
+ if (active)
+ {
+ IOPMRequest * root = active->getRootRequest();
+ if (root) request->attachRootRequest(root);
+ }
+ }
+ else
+ {
+ PM_ERROR("%s: No memory for PM request type 0x%x\n",
+ target->getName(), (uint32_t) requestType);
+ }
+ return request;
+}
+
+//*********************************************************************************
+// [private static] releasePMRequest
+//*********************************************************************************
+
+void IOService::releasePMRequest( IOPMRequest * request )
+{
+ if (request)
+ {
+ request->reset();
+ request->release();
+ }
+}
+
+//*********************************************************************************
+// [private static] submitPMRequest
+//*********************************************************************************
+
+void IOService::submitPMRequest( IOPMRequest * request )
+{
+ assert( request );
+ assert( gIOPMReplyQueue );
+ assert( gIOPMRequestQueue );
+
+ PM_LOG1("[+ %02lx] %p [%p %s] %p %p %p\n",
+ (long)request->getType(), OBFUSCATE(request),
+ OBFUSCATE(request->getTarget()), request->getTarget()->getName(),
+ OBFUSCATE(request->fArg0),
+ OBFUSCATE(request->fArg1), OBFUSCATE(request->fArg2));
+
+ if (request->isReplyType())
+ gIOPMReplyQueue->queuePMRequest( request );
+ else
+ gIOPMRequestQueue->queuePMRequest( request );
+}
+
+void IOService::submitPMRequests( IOPMRequest ** requests, IOItemCount count )
+{
+ assert( requests );
+ assert( count > 0 );
+ assert( gIOPMRequestQueue );
+
+ for (IOItemCount i = 0; i < count; i++)
+ {
+ IOPMRequest * req = requests[i];
+ PM_LOG1("[+ %02lx] %p [%p %s] %p %p %p\n",
+ (long)req->getType(), OBFUSCATE(req),
+ OBFUSCATE(req->getTarget()), req->getTarget()->getName(),
+ OBFUSCATE(req->fArg0),
+ OBFUSCATE(req->fArg1), OBFUSCATE(req->fArg2));
+ }
+
+ gIOPMRequestQueue->queuePMRequestChain( requests, count );
+}
+
+//*********************************************************************************
+// [private] actionPMRequestQueue
+//
+// IOPMRequestQueue::checkForWork() passing a new request to the request target.
+//*********************************************************************************
+
+bool IOService::actionPMRequestQueue(
+ IOPMRequest * request,
+ IOPMRequestQueue * queue )
+{
+ bool more;
+
+ if (initialized)
+ {
+ // Work queue will immediately execute the request if the per-service
+ // request queue is empty. Note pwrMgt is the target's IOServicePM.
+
+ more = gIOPMWorkQueue->queuePMRequest(request, pwrMgt);
+ }
+ else
+ {
+ // Calling PM without PMinit() is not allowed, fail the request.
+ // Need to signal more when completing attached requests.
+
+ PM_LOG("%s: PM not initialized\n", getName());
+ PM_LOG1("[- %02x] %p [%p %s] !initialized\n",
+ request->getType(), OBFUSCATE(request),
+ OBFUSCATE(this), getName());
+
+ more = gIOPMCompletionQueue->queuePMRequest(request);
+ if (more) gIOPMWorkQueue->incrementProducerCount();
+ }
+
+ return more;
+}
+
+//*********************************************************************************
+// [private] actionPMCompletionQueue
+//
+// IOPMCompletionQueue::checkForWork() passing a completed request to the
+// request target.
+//*********************************************************************************
+
+bool IOService::actionPMCompletionQueue(
+ IOPMRequest * request,
+ IOPMCompletionQueue * queue )
+{
+ bool more = (request->getNextRequest() != 0);
+ IOPMRequest * root = request->getRootRequest();
+
+ if (root && (root != request))
+ more = true;
+ if (more)
+ gIOPMWorkQueue->incrementProducerCount();
+
+ releasePMRequest( request );
+ return more;
+}
+
+//*********************************************************************************
+// [private] actionPMWorkQueueRetire
+//
+// IOPMWorkQueue::checkForWork() passing a retired request to the request target.
+//*********************************************************************************
+
+bool IOService::actionPMWorkQueueRetire( IOPMRequest * request, IOPMWorkQueue * queue )
+{
+ assert(request && queue);
+
+ PM_LOG1("[- %02x] %p [%p %s] state %d, busy %d\n",
+ request->getType(), OBFUSCATE(request),
+ OBFUSCATE(this), getName(),
+ fMachineState, gIOPMBusyRequestCount);
+
+ // Catch requests created by idleTimerExpired()
+ if (request->getType() == kIOPMRequestTypeActivityTickle)
+ {
+ uint32_t tickleFlags = (uint32_t)(uintptr_t) request->fArg1;
+
+ if ((tickleFlags & kTickleTypePowerDrop) && fIdleTimerPeriod)
+ {
+ restartIdleTimer();
+ }
+ else if (tickleFlags == (kTickleTypeActivity | kTickleTypePowerRise))
+ {
+ // Invalidate any idle power drop that got queued while
+ // processing this request.
+ fIdleTimerGeneration++;
+ }
+ }
+
+ // When the completed request is linked, tell work queue there is
+ // more work pending.
+
+ return (gIOPMCompletionQueue->queuePMRequest( request ));
+}
+
+//*********************************************************************************
+// [private] isPMBlocked
+//
+// Check if machine state transition is blocked.
+//*********************************************************************************
+
+bool IOService::isPMBlocked( IOPMRequest * request, int count )
+{
+ int reason = 0;
+
+ do {
+ if (kIOPM_Finished == fMachineState)
+ break;
+
+ if (kIOPM_DriverThreadCallDone == fMachineState)
+ {
+ // 5 = kDriverCallInformPreChange
+ // 6 = kDriverCallInformPostChange
+ // 7 = kDriverCallSetPowerState
+ // 8 = kRootDomainInformPreChange
+ if (fDriverCallBusy)
+ reason = 5 + fDriverCallReason;
+ break;
+ }
+
+ // Waiting on driver's setPowerState() timeout.
+ if (fDriverTimer)
+ {
+ reason = 1; break;
+ }
+
+ // Child or interested driver acks pending.
+ if (fHeadNotePendingAcks)
+ {
+ reason = 2; break;
+ }
+
+ // Waiting on apps or priority power interest clients.
+ if (fResponseArray)
+ {
+ reason = 3; break;
+ }
+
+ // Waiting on settle timer expiration.
+ if (fSettleTimeUS)
+ {
+ reason = 4; break;
+ }
+ } while (false);
+
+ fWaitReason = reason;
+
+ if (reason)
+ {
+ if (count)
+ {
+ PM_LOG1("[B %02x] %p [%p %s] state %d, reason %d\n",
+ request->getType(), OBFUSCATE(request),
+ OBFUSCATE(this), getName(),
+ fMachineState, reason);
+ }
+
+ return true;
+ }
+
+ return false;
+}
+
+//*********************************************************************************
+// [private] actionPMWorkQueueInvoke
+//
+// IOPMWorkQueue::checkForWork() passing a request to the
+// request target for execution.
+//*********************************************************************************
+
+bool IOService::actionPMWorkQueueInvoke( IOPMRequest * request, IOPMWorkQueue * queue )
+{
+ bool done = false;
+ int loop = 0;
+
+ assert(request && queue);
+
+ while (isPMBlocked(request, loop++) == false)
+ {
+ PM_LOG1("[W %02x] %p [%p %s] state %d\n",
+ request->getType(), OBFUSCATE(request),
+ OBFUSCATE(this), getName(), fMachineState);
+
+ gIOPMRequest = request;
+ gIOPMWorkInvokeCount++;
+
+ // Every PM machine states must be handled in one of the cases below.
+
+ switch ( fMachineState )
+ {
+ case kIOPM_Finished:
+ start_watchdog_timer();
+
+ executePMRequest( request );
+ break;
+
+ case kIOPM_OurChangeTellClientsPowerDown:
+ // Root domain might self cancel due to assertions.
+ if (IS_ROOT_DOMAIN)
+ {
+ bool cancel = (bool) fDoNotPowerDown;
+ getPMRootDomain()->askChangeDownDone(
+ &fHeadNoteChangeFlags, &cancel);
+ fDoNotPowerDown = cancel;
+ }
+
+ // askChangeDown() done, was it vetoed?
+ if (!fDoNotPowerDown)
+ {
+ // no, we can continue
+ OurChangeTellClientsPowerDown();
+ }
+ else
+ {
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle cancel, state %u\n", fName, fMachineState);
+ // yes, rescind the warning
+ tellNoChangeDown(fHeadNotePowerState);
+ // mark the change note un-actioned
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ // and we're done
+ OurChangeFinish();
+ }
+ break;
+
+ case kIOPM_OurChangeTellUserPMPolicyPowerDown:
+ // PMRD: tellChangeDown/kNotifyApps done, was it cancelled?
+ if (fDoNotPowerDown)
+ {
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle cancel, state %u\n", fName, fMachineState);
+ // yes, rescind the warning
+ tellNoChangeDown(fHeadNotePowerState);
+ // mark the change note un-actioned
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ // and we're done
+ OurChangeFinish();
+ }
+ else
+ OurChangeTellUserPMPolicyPowerDown();
+ break;
+
+ case kIOPM_OurChangeTellPriorityClientsPowerDown:
+ // PMRD: LastCallBeforeSleep notify done
+ // Non-PMRD: tellChangeDown/kNotifyApps done
+ if (fDoNotPowerDown)
+ {
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle revert, state %u\n", fName, fMachineState);
+ // no, tell clients we're back in the old state
+ tellChangeUp(fCurrentPowerState);
+ // mark the change note un-actioned
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ // and we're done
+ OurChangeFinish();
+ }
+ else
+ {
+ // yes, we can continue
+ OurChangeTellPriorityClientsPowerDown();
+ }
+ break;
+
+ case kIOPM_OurChangeNotifyInterestedDriversWillChange:
+ OurChangeNotifyInterestedDriversWillChange();
+ break;
+
+ case kIOPM_OurChangeSetPowerState:
+ OurChangeSetPowerState();
+ break;
+
+ case kIOPM_OurChangeWaitForPowerSettle:
+ OurChangeWaitForPowerSettle();
+ break;
+
+ case kIOPM_OurChangeNotifyInterestedDriversDidChange:
+ OurChangeNotifyInterestedDriversDidChange();
+ break;
+
+ case kIOPM_OurChangeTellCapabilityDidChange:
+ OurChangeTellCapabilityDidChange();
+ break;
+
+ case kIOPM_OurChangeFinish:
+ OurChangeFinish();
+ break;
+
+ case kIOPM_ParentChangeTellPriorityClientsPowerDown:
+ ParentChangeTellPriorityClientsPowerDown();
+ break;
+
+ case kIOPM_ParentChangeNotifyInterestedDriversWillChange:
+ ParentChangeNotifyInterestedDriversWillChange();
+ break;
+
+ case kIOPM_ParentChangeSetPowerState:
+ ParentChangeSetPowerState();
+ break;
+
+ case kIOPM_ParentChangeWaitForPowerSettle:
+ ParentChangeWaitForPowerSettle();
+ break;
+
+ case kIOPM_ParentChangeNotifyInterestedDriversDidChange:
+ ParentChangeNotifyInterestedDriversDidChange();
+ break;
+
+ case kIOPM_ParentChangeTellCapabilityDidChange:
+ ParentChangeTellCapabilityDidChange();
+ break;
+
+ case kIOPM_ParentChangeAcknowledgePowerChange:
+ ParentChangeAcknowledgePowerChange();
+ break;
+
+ case kIOPM_DriverThreadCallDone:
+ switch (fDriverCallReason)
+ {
+ case kDriverCallInformPreChange:
+ case kDriverCallInformPostChange:
+ notifyInterestedDriversDone();
+ break;
+ case kDriverCallSetPowerState:
+ notifyControllingDriverDone();
+ break;
+ case kRootDomainInformPreChange:
+ notifyRootDomainDone();
+ break;
+ default:
+ panic("%s: bad call reason %x",
+ getName(), fDriverCallReason);
+ }
+ break;
+
+ case kIOPM_NotifyChildrenOrdered:
+ notifyChildrenOrdered();
+ break;
+
+ case kIOPM_NotifyChildrenDelayed:
+ notifyChildrenDelayed();
+ break;
+
+ case kIOPM_NotifyChildrenStart:
+ // pop notifyAll() state saved by notifyInterestedDriversDone()
+ MS_POP();
+ notifyRootDomain();
+ break;
+
+ case kIOPM_SyncTellClientsPowerDown:
+ // Root domain might self cancel due to assertions.
+ if (IS_ROOT_DOMAIN)
+ {
+ bool cancel = (bool) fDoNotPowerDown;
+ getPMRootDomain()->askChangeDownDone(
+ &fHeadNoteChangeFlags, &cancel);
+ fDoNotPowerDown = cancel;
+ }
+ if (!fDoNotPowerDown)
+ {
+ fMachineState = kIOPM_SyncTellPriorityClientsPowerDown;
+ fOutOfBandParameter = kNotifyApps;
+ tellChangeDown(fHeadNotePowerState);
+ }
+ else
+ {
+ // Cancelled by IOPMrootDomain::askChangeDownDone() or
+ // askChangeDown/kNotifyApps
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle cancel, state %u\n", fName, fMachineState);
+ tellNoChangeDown(fHeadNotePowerState);
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ OurChangeFinish();
+ }
+ break;
+
+ case kIOPM_SyncTellPriorityClientsPowerDown:
+ // PMRD: tellChangeDown/kNotifyApps done, was it cancelled?
+ if (!fDoNotPowerDown)
+ {
+ fMachineState = kIOPM_SyncNotifyWillChange;
+ fOutOfBandParameter = kNotifyPriority;
+ tellChangeDown(fHeadNotePowerState);
+ }
+ else
+ {
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle revert, state %u\n", fName, fMachineState);
+ tellChangeUp(fCurrentPowerState);
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ OurChangeFinish();
+ }
+ break;
+
+ case kIOPM_SyncNotifyWillChange:
+ if (kIOPMSyncNoChildNotify & fHeadNoteChangeFlags)
+ {
+ fMachineState = kIOPM_SyncFinish;
+ continue;
+ }
+ fMachineState = kIOPM_SyncNotifyDidChange;
+ fDriverCallReason = kDriverCallInformPreChange;
+ notifyChildren();
+ break;
+
+ case kIOPM_SyncNotifyDidChange:
+ fIsPreChange = false;
+
+ if (fHeadNoteChangeFlags & kIOPMParentInitiated)
+ {
+ fMachineState = kIOPM_SyncFinish;
+ }
+ else
+ {
+ assert(IS_ROOT_DOMAIN);
+ fMachineState = kIOPM_SyncTellCapabilityDidChange;
+ }
+
+ fDriverCallReason = kDriverCallInformPostChange;
+ notifyChildren();
+ break;
+
+ case kIOPM_SyncTellCapabilityDidChange:
+ tellSystemCapabilityChange( kIOPM_SyncFinish );
+ break;
+
+ case kIOPM_SyncFinish:
+ if (fHeadNoteChangeFlags & kIOPMParentInitiated)
+ ParentChangeAcknowledgePowerChange();
+ else
+ OurChangeFinish();
+ break;
+
+ case kIOPM_TellCapabilityChangeDone:
+ if (fIsPreChange)
+ {
+ if (fOutOfBandParameter == kNotifyCapabilityChangePriority)
+ {
+ MS_POP(); // tellSystemCapabilityChange()
+ continue;
+ }
+ fOutOfBandParameter = kNotifyCapabilityChangePriority;
+ }
+ else
+ {
+ if (fOutOfBandParameter == kNotifyCapabilityChangeApps)
+ {
+ MS_POP(); // tellSystemCapabilityChange()
+ continue;
+ }
+ fOutOfBandParameter = kNotifyCapabilityChangeApps;
+ }
+ tellClientsWithResponse( fOutOfBandMessage );
+ break;
+
+ default:
+ panic("PMWorkQueueInvoke: unknown machine state %x",
+ fMachineState);
+ }
+
+ gIOPMRequest = 0;
+
+ if (fMachineState == kIOPM_Finished)
+ {
+ stop_watchdog_timer();
+ done = true;
+ break;
+ }
+ }
+
+ return done;
+}
+
+//*********************************************************************************
+// [private] executePMRequest
+//*********************************************************************************
+
+void IOService::executePMRequest( IOPMRequest * request )
+{
+ assert( kIOPM_Finished == fMachineState );
+
+ switch (request->getType())
+ {
+ case kIOPMRequestTypePMStop:
+ handlePMstop( request );
+ break;
+
+ case kIOPMRequestTypeAddPowerChild1:
+ addPowerChild1( request );
+ break;
+
+ case kIOPMRequestTypeAddPowerChild2:
+ addPowerChild2( request );
+ break;
+
+ case kIOPMRequestTypeAddPowerChild3:
+ addPowerChild3( request );
+ break;
+
+ case kIOPMRequestTypeRegisterPowerDriver:
+ handleRegisterPowerDriver( request );
+ break;
+
+ case kIOPMRequestTypeAdjustPowerState:
+ fAdjustPowerScheduled = false;
+ adjustPowerState();
+ break;
+
+ case kIOPMRequestTypePowerDomainWillChange:
+ handlePowerDomainWillChangeTo( request );
+ break;
+
+ case kIOPMRequestTypePowerDomainDidChange:
+ handlePowerDomainDidChangeTo( request );
+ break;
+
+ case kIOPMRequestTypeRequestPowerState:
+ case kIOPMRequestTypeRequestPowerStateOverride:
+ handleRequestPowerState( request );
+ break;
+
+ case kIOPMRequestTypePowerOverrideOnPriv:
+ case kIOPMRequestTypePowerOverrideOffPriv:
+ handlePowerOverrideChanged( request );
+ break;
+
+ case kIOPMRequestTypeActivityTickle:
+ handleActivityTickle( request );
+ break;
+
+ case kIOPMRequestTypeSynchronizePowerTree:
+ handleSynchronizePowerTree( request );
+ break;
+
+ case kIOPMRequestTypeSetIdleTimerPeriod:
+ {
+ fIdleTimerPeriod = (uintptr_t) request->fArg0;
+ fNextIdleTimerPeriod = fIdleTimerPeriod;
+ if ((false == fLockedFlags.PMStop) && (fIdleTimerPeriod > 0))
+ restartIdleTimer();
+ }
+ break;
+
+ case kIOPMRequestTypeIgnoreIdleTimer:
+ fIdleTimerIgnored = request->fArg0 ? 1 : 0;
+ break;
+
+ case kIOPMRequestTypeQuiescePowerTree:
+ gIOPMWorkQueue->finishQuiesceRequest(request);
+ break;
+
+ default:
+ panic("executePMRequest: unknown request type %x", request->getType());
+ }
+}
+
+//*********************************************************************************
+// [private] actionPMReplyQueue
+//
+// IOPMRequestQueue::checkForWork() passing a reply-type request to the
+// request target.
+//*********************************************************************************
+
+bool IOService::actionPMReplyQueue( IOPMRequest * request, IOPMRequestQueue * queue )
+{
+ bool more = false;
+
+ assert( request && queue );
+ assert( request->isReplyType() );
+
+ PM_LOG1("[A %02x] %p [%p %s] state %d\n",
+ request->getType(), OBFUSCATE(request),
+ OBFUSCATE(this), getName(), fMachineState);
+
+ switch ( request->getType() )
+ {
+ case kIOPMRequestTypeAllowPowerChange:
+ case kIOPMRequestTypeCancelPowerChange:
+ // Check if we are expecting this response.
+ if (responseValid((uint32_t)(uintptr_t) request->fArg0,
+ (int)(uintptr_t) request->fArg1))
+ {
+ if (kIOPMRequestTypeCancelPowerChange == request->getType())
+ {
+ // Clients are not allowed to cancel when kIOPMSkipAskPowerDown
+ // flag is set. Only root domain will set this flag.
+ // However, there is one exception to this rule. User-space PM
+ // policy may choose to cancel sleep even after all clients have
+ // been notified that we will lower power.
+
+ if ((fMachineState == kIOPM_OurChangeTellUserPMPolicyPowerDown)
+ || (fMachineState == kIOPM_OurChangeTellPriorityClientsPowerDown)
+ || ((fHeadNoteChangeFlags & kIOPMSkipAskPowerDown) == 0))
+ {
+ fDoNotPowerDown = true;
+
+ OSString * name = (OSString *) request->fArg2;
+ getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsApplicationResponseCancel,
+ name ? name->getCStringNoCopy() : "", 0,
+ 0, (int)(uintptr_t) request->fArg1, 0);
+ }
+ }
+
+ if (checkForDone())
+ {
+ stop_ack_timer();
+ cleanClientResponses(false);
+ more = true;
+ }
+ }
+ // OSString containing app name in Arg2 must be released.
+ if (request->getType() == kIOPMRequestTypeCancelPowerChange)
+ {
+ OSObject * obj = (OSObject *) request->fArg2;
+ if (obj) obj->release();
+ }
+ break;
+
+ case kIOPMRequestTypeAckPowerChange:
+ more = handleAcknowledgePowerChange( request );
+ break;
+
+ case kIOPMRequestTypeAckSetPowerState:
+ if (fDriverTimer == -1)
+ {
+ // driver acked while setPowerState() call is in-flight.
+ // take this ack, return value from setPowerState() is irrelevant.
+ OUR_PMLog(kPMLogDriverAcknowledgeSet,
+ (uintptr_t) this, fDriverTimer);
+ fDriverTimer = 0;
+ }
+ else if (fDriverTimer > 0)
+ {
+ // expected ack, stop the timer
+ stop_ack_timer();
+
+#if LOG_SETPOWER_TIMES
+ uint64_t nsec = computeTimeDeltaNS(&fDriverCallStartTime);
+ if (nsec > LOG_SETPOWER_TIMES) {
+ getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsDriverPSChangeSlow,
+ fName, kDriverCallSetPowerState, NS_TO_MS(nsec), 0, NULL, fHeadNotePowerState);
+ }
+#endif
+ OUR_PMLog(kPMLogDriverAcknowledgeSet, (uintptr_t) this, fDriverTimer);
+ fDriverTimer = 0;
+ more = true;
+ }
+ else
+ {
+ // unexpected ack
+ OUR_PMLog(kPMLogAcknowledgeErr4, (uintptr_t) this, 0);
+ }
+ break;
+
+ case kIOPMRequestTypeInterestChanged:
+ handleInterestChanged( request );
+ more = true;
+ break;
+
+ case kIOPMRequestTypeIdleCancel:
+ if ((fMachineState == kIOPM_OurChangeTellClientsPowerDown)
+ || (fMachineState == kIOPM_OurChangeTellUserPMPolicyPowerDown)
+ || (fMachineState == kIOPM_OurChangeTellPriorityClientsPowerDown)
+ || (fMachineState == kIOPM_SyncTellClientsPowerDown)
+ || (fMachineState == kIOPM_SyncTellPriorityClientsPowerDown))
+ {
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_LOG2("%s: cancel from machine state %d\n",
+ getName(), fMachineState);
+ fDoNotPowerDown = true;
+ // Stop waiting for app replys.
+ if ((fMachineState == kIOPM_OurChangeTellPriorityClientsPowerDown) ||
+ (fMachineState == kIOPM_OurChangeTellUserPMPolicyPowerDown) ||
+ (fMachineState == kIOPM_SyncTellPriorityClientsPowerDown) ||
+ (fMachineState == kIOPM_SyncTellClientsPowerDown) )
+ cleanClientResponses(false);
+ more = true;
+ }
+ break;
+
+ case kIOPMRequestTypeChildNotifyDelayCancel:
+ if (fMachineState == kIOPM_NotifyChildrenDelayed)
+ {
+ PM_LOG2("%s: delay notify cancelled\n", getName());
+ notifyChildrenDelayed();
+ }
+ break;
+
+ default:
+ panic("PMReplyQueue: unknown reply type %x", request->getType());
+ }
+
+ more |= gIOPMCompletionQueue->queuePMRequest(request);
+ if (more)
+ gIOPMWorkQueue->incrementProducerCount();
+
+ return more;
+}
+
+//*********************************************************************************
+// [private] assertPMDriverCall / deassertPMDriverCall
+//*********************************************************************************
+
+bool IOService::assertPMDriverCall(
+ IOPMDriverCallEntry * entry,
+ IOOptionBits options,
+ IOPMinformee * inform )
+{
+ IOService * target = 0;
+ bool ok = false;
+
+ if (!initialized)
+ return false;
+
+ PM_LOCK();
+
+ if (fLockedFlags.PMStop)
+ {
+ goto fail;
+ }
+
+ if (((options & kIOPMADC_NoInactiveCheck) == 0) && isInactive())
+ {
+ goto fail;
+ }
+
+ if (inform)
+ {
+ if (!inform->active)
+ {
+ goto fail;
+ }
+ target = inform->whatObject;
+ if (target->isInactive())
+ {
+ goto fail;
+ }
+ }
+
+ entry->thread = current_thread();
+ entry->target = target;
+ queue_enter(&fPMDriverCallQueue, entry, IOPMDriverCallEntry *, link);
+ ok = true;
+
+fail:
+ PM_UNLOCK();
+
+ return ok;
+}
+
+void IOService::deassertPMDriverCall( IOPMDriverCallEntry * entry )
+{
+ bool wakeup = false;
+
+ PM_LOCK();
+
+ assert( !queue_empty(&fPMDriverCallQueue) );
+ queue_remove(&fPMDriverCallQueue, entry, IOPMDriverCallEntry *, link);
+ if (fLockedFlags.PMDriverCallWait)
+ {
+ wakeup = true;
+ }
+
+ PM_UNLOCK();
+
+ if (wakeup)
+ PM_LOCK_WAKEUP(&fPMDriverCallQueue);
+}
+
+void IOService::waitForPMDriverCall( IOService * target )
+{
+ const IOPMDriverCallEntry * entry;
+ thread_t thread = current_thread();
+ AbsoluteTime deadline;
+ int waitResult;
+ bool log = true;
+ bool wait;
+
+ do {
+ wait = false;
+ queue_iterate(&fPMDriverCallQueue, entry, const IOPMDriverCallEntry *, link)
+ {
+ // Target of interested driver call
+ if (target && (target != entry->target))
+ continue;
+
+ if (entry->thread == thread)
+ {
+ if (log)
+ {
+ PM_LOG("%s: %s(%s) on PM thread\n",
+ fName, __FUNCTION__, target ? target->getName() : "");
+ OSReportWithBacktrace("%s: %s(%s) on PM thread\n",
+ fName, __FUNCTION__, target ? target->getName() : "");
+ log = false;
+ }
+ continue;
+ }
+
+ wait = true;
+ break;
+ }
+
+ if (wait)
+ {
+ fLockedFlags.PMDriverCallWait = true;
+ clock_interval_to_deadline(15, kSecondScale, &deadline);
+ waitResult = PM_LOCK_SLEEP(&fPMDriverCallQueue, deadline);
+ fLockedFlags.PMDriverCallWait = false;
+ if (THREAD_TIMED_OUT == waitResult)
+ {
+ PM_ERROR("%s: waitForPMDriverCall timeout\n", fName);
+ wait = false;
+ }
+ }
+ } while (wait);
+}
+
+//*********************************************************************************
+// [private] Debug helpers
+//*********************************************************************************
+
+const char * IOService::getIOMessageString( uint32_t msg )
+{
+#define MSG_ENTRY(x) {(int) x, #x}
+
+ static const IONamedValue msgNames[] = {
+ MSG_ENTRY( kIOMessageCanDevicePowerOff ),
+ MSG_ENTRY( kIOMessageDeviceWillPowerOff ),
+ MSG_ENTRY( kIOMessageDeviceWillNotPowerOff ),
+ MSG_ENTRY( kIOMessageDeviceHasPoweredOn ),
+ MSG_ENTRY( kIOMessageCanSystemPowerOff ),
+ MSG_ENTRY( kIOMessageSystemWillPowerOff ),
+ MSG_ENTRY( kIOMessageSystemWillNotPowerOff ),
+ MSG_ENTRY( kIOMessageCanSystemSleep ),
+ MSG_ENTRY( kIOMessageSystemWillSleep ),
+ MSG_ENTRY( kIOMessageSystemWillNotSleep ),
+ MSG_ENTRY( kIOMessageSystemHasPoweredOn ),
+ MSG_ENTRY( kIOMessageSystemWillRestart ),
+ MSG_ENTRY( kIOMessageSystemWillPowerOn ),
+ MSG_ENTRY( kIOMessageSystemCapabilityChange ),
+ MSG_ENTRY( kIOPMMessageLastCallBeforeSleep )
+ };
+
+ return IOFindNameForValue(msg, msgNames);
+}
+
+
+// MARK: -
+// MARK: IOPMRequest
+
+//*********************************************************************************
+// IOPMRequest Class
+//
+// Requests from PM clients, and also used for inter-object messaging within PM.
+//*********************************************************************************
+
+OSDefineMetaClassAndStructors( IOPMRequest, IOCommand );
+
+IOPMRequest * IOPMRequest::create( void )
+{
+ IOPMRequest * me = OSTypeAlloc(IOPMRequest);
+ if (me && !me->init(0, kIOPMRequestTypeInvalid))
+ {
+ me->release();
+ me = 0;
+ }
+ return me;
+}
+
+bool IOPMRequest::init( IOService * target, IOOptionBits type )
+{
+ if (!IOCommand::init())
+ return false;
+
+ fRequestType = type;
+ fTarget = target;
+
+ if (fTarget)
+ fTarget->retain();
+
+ // Root node and root domain requests does not prevent the power tree from
+ // becoming quiescent.
+
+ fIsQuiesceBlocker = ((fTarget != gIOPMRootNode) &&
+ (fTarget != IOService::getPMRootDomain()));
+