+ UInt16 serialComponent;
+ UInt16 ordinalComponent;
+ OSObject * theFlag;
+
+ 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;
+ }
+
+ OSNumber * num;
+ if ((num = OSDynamicCast(OSNumber, theFlag)))
+ {
+#if LOG_APP_RESPONSE_TIMES
+ AbsoluteTime now;
+ AbsoluteTime start;
+ uint64_t nsec;
+ OSString *name = IOCopyLogNameForPID(pid);
+
+ clock_get_uptime(&now);
+ AbsoluteTime_to_scalar(&start) = num->unsigned64BitValue();
+ SUB_ABSOLUTETIME(&now, &start);
+ absolutetime_to_nanoseconds(now, &nsec);
+
+ PMEventDetails *details = PMEventDetails::eventDetails(
+ kIOPMEventTypeAppResponse, // type
+ name ? name->getCStringNoCopy() : "", // who
+ (uintptr_t)pid, // owner unique
+ NULL, // interest name
+ 0, // old
+ 0, // new
+ 0, // result
+ NS_TO_US(nsec)); // usec completion time
+
+ getPMRootDomain()->recordAndReleasePMEventGated( details );
+
+ 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)
+ {
+ PM_LOG("PM response took %d ms (%s)\n", NS_TO_MS(nsec),
+ name ? name->getCStringNoCopy() : "");
+
+ if (nsec > LOG_APP_RESPONSE_MSG_TRACER)
+ {
+ // TODO: populate the messageType argument
+ getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsApplicationResponseSlow,
+ name ? name->getCStringNoCopy() : "", 0,
+ NS_TO_MS(nsec), pid);
+ }
+ }
+
+ if (name)
+ name->release();
+#endif
+ theFlag = kOSBooleanFalse;
+ }
+
+ 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 *) 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;
+ OSString * name;
+
+ if ( !initialized )
+ {
+ // we're unloading
+ return kIOReturnSuccess;
+ }
+
+ name = IOCopyLogNameForPID(proc_selfpid());
+ PM_ERROR("PM notification cancel (%s)\n", name ? name->getCStringNoCopy() : "");
+
+ request = acquirePMRequest( this, kIOPMRequestTypeCancelPowerChange );
+ if (!request)
+ {
+ if (name)
+ name->release();
+ return kIOReturnNoMemory;
+ }
+
+ request->fArg0 = (void *) refcon;
+ request->fArg1 = (void *) proc_selfpid();
+ request->fArg2 = (void *) 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__ */
+
+// 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.
+//*********************************************************************************
+
+unsigned long IOService::maxCapabilityForDomainState ( IOPMPowerFlags domainState )
+{
+ int i;
+
+ if (fNumberOfPowerStates == 0 )
+ {
+ return 0;
+ }
+ for ( i = fNumberOfPowerStates - 1; i >= 0; i-- )
+ {
+ if ( (domainState & fPowerStates[i].inputPowerFlags) ==
+ fPowerStates[i].inputPowerFlags )
+ {
+ return i;
+ }
+ }
+ return 0;
+}
+
+//*********************************************************************************
+// [public] initialPowerStateForDomainState
+//
+// 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.
+//*********************************************************************************
+
+unsigned long IOService::initialPowerStateForDomainState ( IOPMPowerFlags domainState )
+{
+ int i;
+
+ if (fNumberOfPowerStates == 0 )
+ {
+ return 0;
+ }
+ for ( i = fNumberOfPowerStates - 1; i >= 0; i-- )
+ {
+ if ( (domainState & fPowerStates[i].inputPowerFlags) ==
+ fPowerStates[i].inputPowerFlags )
+ {
+ return i;
+ }
+ }
+ return 0;
+}
+
+//*********************************************************************************
+// [public] powerStateForDomainState
+//
+// 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.
+//*********************************************************************************
+
+unsigned long IOService::powerStateForDomainState ( IOPMPowerFlags domainState )
+{
+ int i;
+
+ if (fNumberOfPowerStates == 0 )
+ {
+ return 0;
+ }
+ for ( i = fNumberOfPowerStates - 1; i >= 0; i-- )
+ {
+ if ( (domainState & fPowerStates[i].inputPowerFlags) ==
+ fPowerStates[i].inputPowerFlags )
+ {
+ return i;
+ }
+ }
+ return 0;
+}
+
+#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] 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(), request,
+ request->getTarget(), request->getTarget()->getName(),
+ request->fArg0, request->fArg1, request->fArg2);
+
+ if (request->isReplyType())
+ gIOPMReplyQueue->queuePMRequest( request );
+ else
+ gIOPMRequestQueue->queuePMRequest( request );
+}
+
+void IOService::submitPMRequest( 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(), req,
+ req->getTarget(), req->getTarget()->getName(),
+ req->fArg0, req->fArg1, req->fArg2);
+ }
+
+ gIOPMRequestQueue->queuePMRequestChain( requests, count );
+}
+
+//*********************************************************************************
+// [private] servicePMRequestQueue
+//
+// Called from IOPMRequestQueue::checkForWork().
+//*********************************************************************************
+
+bool IOService::servicePMRequestQueue(
+ IOPMRequest * request,
+ IOPMRequestQueue * queue )
+{
+ bool more;
+
+ if (initialized)
+ {
+ // Work queue will immediately execute the queue'd request if possible.
+ // If execution blocks, the work queue will wait for a producer signal.
+ // Only need to signal more when completing attached requests.
+
+ more = gIOPMWorkQueue->queuePMRequest(request, pwrMgt);
+ return more;
+ }
+
+ // Calling PM without PMinit() is not allowed, fail the request.
+
+ PM_LOG("%s: PM not initialized\n", getName());
+ fAdjustPowerScheduled = false;
+ more = gIOPMFreeQueue->queuePMRequest(request);
+ if (more) gIOPMWorkQueue->incrementProducerCount();
+ return more;
+}
+
+//*********************************************************************************
+// [private] servicePMFreeQueue
+//
+// Called from IOPMCompletionQueue::checkForWork().
+//*********************************************************************************
+
+bool IOService::servicePMFreeQueue(
+ IOPMRequest * request,
+ IOPMCompletionQueue * queue )
+{
+ bool more = request->getNextRequest();
+ IOPMRequest * root = request->getRootRequest();
+
+ if (root && (root != request))
+ more = true;
+ if (more)
+ gIOPMWorkQueue->incrementProducerCount();
+
+ releasePMRequest( request );
+ return more;
+}
+
+//*********************************************************************************
+// [private] retirePMRequest
+//
+// Called by IOPMWorkQueue to retire a completed request.
+//*********************************************************************************
+
+bool IOService::retirePMRequest( IOPMRequest * request, IOPMWorkQueue * queue )
+{
+ assert(request && queue);
+
+ PM_LOG1("[- %02x] %p [%p %s] state %d, busy %d\n",
+ request->getType(), request, this, getName(),
+ fMachineState, gIOPMBusyCount);
+
+ // Catch requests created by idleTimerExpired().
+
+ if ((request->getType() == kIOPMRequestTypeActivityTickle) &&
+ (request->fArg1 == (void *) (uintptr_t) false))
+ {
+ // Idle timer power drop request completed.
+ // Restart the idle timer if deviceDesire can go lower, otherwise set
+ // a flag so we know to restart idle timer when deviceDesire goes up.
+
+ if (fDeviceDesire > 0)
+ {
+ fActivityTickleCount = 0;
+ clock_get_uptime(&fIdleTimerStartTime);
+ start_PM_idle_timer();
+ }
+ else
+ fIdleTimerStopped = true;
+ }
+
+ // If the request is linked, then Work queue has already incremented its
+ // producer count.
+
+ return (gIOPMFreeQueue->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
+ 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(), request, this, getName(),
+ fMachineState, reason);
+ }
+
+ return true;
+ }
+
+ return false;
+}
+
+//*********************************************************************************
+// [private] servicePMRequest
+//
+// Service a request from our work queue.
+//*********************************************************************************
+
+bool IOService::servicePMRequest( 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(), request, this, getName(), fMachineState);
+
+ gIOPMRequest = request;
+ gIOPMWorkCount++;
+
+ // Every PM machine states must be handled in one of the cases below.
+
+ switch ( fMachineState )
+ {
+ case kIOPM_Finished:
+ 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)
+ {
+ if (IS_ROOT_DOMAIN) {
+ PMEventDetails *details = PMEventDetails::eventDetails(
+ kIOPMEventTypeAppNotificationsFinished,
+ NULL,
+ 0,
+ 0);
+
+ getPMRootDomain()->recordAndReleasePMEventGated( details );
+ }
+
+ // no, we can continue
+ OurChangeTellClientsPowerDown();
+ }
+ else
+ {
+ if (IS_ROOT_DOMAIN) {
+ PMEventDetails *details = PMEventDetails::eventDetails(
+ kIOPMEventTypeSleepDone,
+ NULL,
+ 1, /* reason: 1 == Ask clients succeeded */
+ kIOReturnAborted); /* result */
+
+ getPMRootDomain()->recordAndReleasePMEventGated( details );
+ }
+
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle cancel\n", fName);
+ // yes, rescind the warning
+ tellNoChangeDown(fHeadNotePowerState);
+ // mark the change note un-actioned
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ // and we're done
+ OurChangeFinish();
+ }
+ break;
+
+ case kIOPM_OurChangeTellPriorityClientsPowerDown:
+ // tellChangeDown(kNotifyApps) done, was it cancelled?
+ if (fDoNotPowerDown)
+ {
+ if (IS_ROOT_DOMAIN) {
+ PMEventDetails *details = PMEventDetails::eventDetails(
+ kIOPMEventTypeSleepDone,
+ NULL,
+ 2, /* reason: 2 == Client cancelled wake */
+ kIOReturnAborted); /* result */
+
+ getPMRootDomain()->recordAndReleasePMEventGated( details );
+ }
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle revert\n", fName);
+ // 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
+ {
+ if (IS_ROOT_DOMAIN) {
+ PMEventDetails *details = PMEventDetails::eventDetails(
+ kIOPMEventTypeAppNotificationsFinished,
+ NULL,
+ 2, /* reason: 2 == TellPriorityClientsDone */
+ kIOReturnSuccess); /* result */
+
+ getPMRootDomain()->recordAndReleasePMEventGated( details );
+ }
+ // 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:
+ if (fDriverCallReason == kDriverCallSetPowerState)
+ notifyControllingDriverDone();
+ else
+ notifyInterestedDriversDone();
+ break;
+
+ case kIOPM_NotifyChildrenOrdered:
+ notifyChildrenOrdered();
+ break;
+
+ case kIOPM_NotifyChildrenDelayed:
+ notifyChildrenDelayed();
+ break;
+
+ case kIOPM_NotifyChildrenStart:
+ PM_LOG2("%s: kIOPM_NotifyChildrenStart done\n", getName());
+ MS_POP(); // from notifyInterestedDriversDone()
+ notifyChildren();
+ 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
+ {
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle cancel\n", fName);
+ tellNoChangeDown(fHeadNotePowerState);
+ fHeadNoteChangeFlags |= kIOPMNotDone;
+ OurChangeFinish();
+ }
+ break;
+
+ case kIOPM_SyncTellPriorityClientsPowerDown:
+ if (!fDoNotPowerDown)
+ {
+ fMachineState = kIOPM_SyncNotifyWillChange;
+ fOutOfBandParameter = kNotifyPriority;
+ tellChangeDown(fHeadNotePowerState);
+ }
+ else
+ {
+ OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
+ PM_ERROR("%s: idle revert\n", fName);
+ 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
+ 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("servicePMWorkQueue: unknown machine state %x",
+ fMachineState);
+ }
+
+ gIOPMRequest = 0;
+
+ if (fMachineState == kIOPM_Finished)
+ {
+ 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;
+ rebuildChildClampBits();
+ 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;
+
+ if ((false == fLockedFlags.PMStop) && (fIdleTimerPeriod > 0))
+ {
+ fActivityTickleCount = 0;
+ clock_get_uptime(&fIdleTimerStartTime);
+ start_PM_idle_timer();
+ }
+ }
+ break;
+
+ default:
+ panic("executePMRequest: unknown request type %x", request->getType());
+ }
+}
+
+//*********************************************************************************
+// [private] servicePMReplyQueue
+//*********************************************************************************
+
+bool IOService::servicePMReplyQueue( 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(), request, 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.
+
+ if ((fHeadNoteChangeFlags & kIOPMSkipAskPowerDown) == 0)
+ {
+ fDoNotPowerDown = true;
+
+ OSString * name = (OSString *) request->fArg2;
+ getPMRootDomain()->pmStatsRecordApplicationResponse(
+ gIOPMStatsApplicationResponseCancel,
+ name ? name->getCStringNoCopy() : "", 0,
+ 0, (int)(uintptr_t) request->fArg1);
+ }
+ }
+
+ 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)
+ PM_LOG("%s::setPowerState(%p, %lu -> %lu) async took %d ms\n",
+ fName, this, fCurrentPowerState, fHeadNotePowerState, NS_TO_MS(nsec));
+
+ PMEventDetails *details = PMEventDetails::eventDetails(
+ kIOPMEventTypeSetPowerStateDelayed, // type
+ fName, // who
+ (uintptr_t)this, // owner unique
+ NULL, // interest name
+ (uint8_t)getPowerState(), // old
+ (uint8_t)fHeadNotePowerState, // new
+ 0, // result
+ NS_TO_US(nsec)); // usec completion time
+
+ getPMRootDomain()->recordAndReleasePMEventGated( details );
+#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_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_SyncTellPriorityClientsPowerDown))
+ cleanClientResponses(false);
+ more = true;
+ }
+ break;
+
+ case kIOPMRequestTypeChildNotifyDelayCancel:
+ if (fMachineState == kIOPM_NotifyChildrenDelayed)
+ {
+ PM_LOG2("%s: delay notify cancelled\n", getName());
+ notifyChildrenDelayed();
+ }
+ break;
+
+ default:
+ panic("servicePMReplyQueue: unknown reply type %x",
+ request->getType());
+ }
+
+ more |= gIOPMFreeQueue->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;