]> git.saurik.com Git - apple/xnu.git/blame - iokit/Kernel/IOServicePM.cpp
xnu-3248.60.10.tar.gz
[apple/xnu.git] / iokit / Kernel / IOServicePM.cpp
CommitLineData
1c79356b 1/*
2d21ac55 2 * Copyright (c) 1998-2006 Apple Computer, Inc. All rights reserved.
1c79356b 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
8f6c56a5 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b 27 */
91447636
A
28
29#include <IOKit/assert.h>
91447636
A
30#include <IOKit/IOKitDebug.h>
31#include <IOKit/IOLib.h>
32#include <IOKit/IOMessage.h>
33#include <IOKit/IOPlatformExpert.h>
34#include <IOKit/IOService.h>
6d2010ae 35#include <IOKit/IOEventSource.h>
1c79356b 36#include <IOKit/IOWorkLoop.h>
2d21ac55 37#include <IOKit/IOCommand.h>
4b17d6b6 38#include <IOKit/IOTimeStamp.h>
39236c6e 39#include <IOKit/IOReportMacros.h>
1c79356b 40
2d21ac55 41#include <IOKit/pwr_mgt/IOPMlog.h>
91447636
A
42#include <IOKit/pwr_mgt/IOPMinformee.h>
43#include <IOKit/pwr_mgt/IOPMinformeeList.h>
91447636
A
44#include <IOKit/pwr_mgt/IOPowerConnection.h>
45#include <IOKit/pwr_mgt/RootDomain.h>
6d2010ae 46#include <IOKit/pwr_mgt/IOPMPrivate.h>
9bccf70c 47
2d21ac55 48#include <sys/proc.h>
316670eb 49#include <sys/proc_internal.h>
3e170ce0 50#include <sys/sysctl.h>
6d2010ae 51#include <libkern/OSDebug.h>
39236c6e 52#include <kern/thread.h>
0c530ab8 53
91447636
A
54// Required for notification instrumentation
55#include "IOServicePrivate.h"
2d21ac55
A
56#include "IOServicePMPrivate.h"
57#include "IOKitKernelInternal.h"
9bccf70c 58
39236c6e 59
2d21ac55 60static void settle_timer_expired(thread_call_param_t, thread_call_param_t);
6d2010ae 61static void idle_timer_expired(thread_call_param_t, thread_call_param_t);
b0d623f7
A
62static void tellKernelClientApplier(OSObject * object, void * arg);
63static void tellAppClientApplier(OSObject * object, void * arg);
9bccf70c 64
2d21ac55
A
65static uint64_t computeTimeDeltaNS( const AbsoluteTime * start )
66{
67 AbsoluteTime now;
68 uint64_t nsec;
9bccf70c 69
2d21ac55
A
70 clock_get_uptime(&now);
71 SUB_ABSOLUTETIME(&now, start);
72 absolutetime_to_nanoseconds(now, &nsec);
73 return nsec;
74}
1c79356b 75
b0d623f7 76#if PM_VARS_SUPPORT
2d21ac55 77OSDefineMetaClassAndStructors(IOPMprot, OSObject)
b0d623f7 78#endif
1c79356b 79
6d2010ae 80//******************************************************************************
2d21ac55 81// Globals
6d2010ae 82//******************************************************************************
1c79356b 83
bd504ef0 84static bool gIOPMInitialized = false;
3e170ce0
A
85static uint32_t gIOPMBusyRequestCount = 0;
86static uint32_t gIOPMWorkInvokeCount = 0;
bd504ef0
A
87static uint32_t gIOPMTickleGeneration = 0;
88static IOWorkLoop * gIOPMWorkLoop = 0;
89static IOPMRequestQueue * gIOPMRequestQueue = 0;
90static IOPMRequestQueue * gIOPMReplyQueue = 0;
91static IOPMWorkQueue * gIOPMWorkQueue = 0;
3e170ce0 92static IOPMCompletionQueue * gIOPMCompletionQueue = 0;
bd504ef0
A
93static IOPMRequest * gIOPMRequest = 0;
94static IOService * gIOPMRootNode = 0;
95static IOPlatformExpert * gPlatform = 0;
b0d623f7 96
3e170ce0
A
97static char gIOSpinDumpKextName[128];
98static char gIOSpinDumpDelayType[16];
99static uint32_t gIOSpinDumpDelayDuration = 0;
100
101static SYSCTL_STRING(_debug, OID_AUTO, swd_kext_name,
102 CTLFLAG_RW | CTLFLAG_KERN | CTLFLAG_LOCKED,
103 &gIOSpinDumpKextName, sizeof(gIOSpinDumpKextName), "");
104static SYSCTL_STRING(_debug, OID_AUTO, swd_delay_type,
105 CTLFLAG_RW | CTLFLAG_KERN | CTLFLAG_LOCKED,
106 &gIOSpinDumpDelayType, sizeof(gIOSpinDumpDelayType), "");
107static SYSCTL_INT(_debug, OID_AUTO, swd_delay_duration,
108 CTLFLAG_RW | CTLFLAG_KERN | CTLFLAG_LOCKED,
109 &gIOSpinDumpDelayDuration, 0, "");
110
39236c6e
A
111const OSSymbol * gIOPMPowerClientDevice = 0;
112const OSSymbol * gIOPMPowerClientDriver = 0;
113const OSSymbol * gIOPMPowerClientChildProxy = 0;
114const OSSymbol * gIOPMPowerClientChildren = 0;
115const OSSymbol * gIOPMPowerClientRootDomain = 0;
b0d623f7 116
db609669
A
117static const OSSymbol * gIOPMPowerClientAdvisoryTickle = 0;
118static bool gIOPMAdvisoryTickleEnabled = true;
39236c6e 119static thread_t gIOPMWatchDogThread = NULL;
3e170ce0 120uint32_t gCanSleepTimeout = 0;
db609669 121
b0d623f7
A
122static uint32_t getPMRequestType( void )
123{
124 uint32_t type = kIOPMRequestTypeInvalid;
fe8ab488 125 if (gIOPMRequest)
b0d623f7
A
126 type = gIOPMRequest->getType();
127 return type;
128}
1c79356b 129
39236c6e
A
130static IOPMRequestTag getPMRequestTag( void )
131{
132 IOPMRequestTag tag = 0;
133 if (gIOPMRequest &&
134 (gIOPMRequest->getType() == kIOPMRequestTypeRequestPowerStateOverride))
135 {
136 tag = gIOPMRequest->fRequestTag;
137 }
138 return tag;
139}
140
3e170ce0
A
141SYSCTL_UINT(_kern, OID_AUTO, pmtimeout, CTLFLAG_RW | CTLFLAG_LOCKED, &gCanSleepTimeout, 0, "Power Management Timeout");
142
6d2010ae 143//******************************************************************************
2d21ac55 144// Macros
6d2010ae 145//******************************************************************************
1c79356b 146
39236c6e 147#define PM_ERROR(x...) do { kprintf(x);IOLog(x); \
39236c6e 148 } while (false)
6d2010ae
A
149#define PM_LOG(x...) do { kprintf(x); } while (false)
150
151#define PM_LOG1(x...) do { \
152 if (kIOLogDebugPower & gIOKitDebug) \
153 kprintf(x); } while (false)
154
155#define PM_LOG2(x...) do { \
156 if (kIOLogDebugPower & gIOKitDebug) \
157 kprintf(x); } while (false)
55e303ae 158
6d2010ae
A
159#if 0
160#define PM_LOG3(x...) do { kprintf(x); } while (false)
161#else
162#define PM_LOG3(x...)
163#endif
164
165#define RD_LOG(x...) do { \
166 if ((kIOLogPMRootDomain & gIOKitDebug) && \
39236c6e
A
167 (getPMRootDomain() == this)) { \
168 kprintf("PMRD: " x); \
39236c6e 169 }} while (false)
2d21ac55
A
170#define PM_ASSERT_IN_GATE(x) \
171do { \
172 assert(gIOPMWorkLoop->inGate()); \
173} while(false)
1c79356b 174
b0d623f7
A
175#define PM_LOCK() IOLockLock(fPMLock)
176#define PM_UNLOCK() IOLockUnlock(fPMLock)
6d2010ae 177#define PM_LOCK_SLEEP(event, dl) IOLockSleepDeadline(fPMLock, event, dl, THREAD_UNINT)
b0d623f7 178#define PM_LOCK_WAKEUP(event) IOLockWakeup(fPMLock, event, false)
2d21ac55 179
3e170ce0 180#define us_per_s 1000000
b0d623f7 181#define ns_per_us 1000
3e170ce0
A
182#define k30Seconds (30*us_per_s)
183#define k5Seconds ( 5*us_per_s)
184#define kCanSleepMaxTimeReq k30Seconds
185#define kMaxTimeRequested k30Seconds
b0d623f7
A
186#define kMinAckTimeoutTicks (10*1000000)
187#define kIOPMTardyAckSPSKey "IOPMTardyAckSetPowerState"
188#define kIOPMTardyAckPSCKey "IOPMTardyAckPowerStateChange"
189#define kPwrMgtKey "IOPowerManagement"
2d21ac55 190
4b17d6b6
A
191#define OUR_PMLog(t, a, b) do { \
192 if (gIOKitDebug & kIOLogPower) \
193 pwrMgt->pmPrint(t, a, b); \
194 if (gIOKitTrace & kIOTracePowerMgmt) \
195 pwrMgt->pmTrace(t, a, b); \
196 } while(0)
2d21ac55 197
b0d623f7 198#define NS_TO_MS(nsec) ((int)((nsec) / 1000000ULL))
6d2010ae 199#define NS_TO_US(nsec) ((int)((nsec) / 1000ULL))
2d21ac55 200
b0d623f7 201#define SUPPORT_IDLE_CANCEL 1
593a1d5f 202
39236c6e
A
203#define kIOPMPowerStateMax 0xFFFFFFFF
204#define kInvalidTicklePowerState kIOPMPowerStateMax
db609669
A
205
206#define kNoTickleCancelWindow (60ULL * 1000ULL * 1000ULL * 1000ULL)
b0d623f7 207
6d2010ae
A
208#define IS_PM_ROOT (this == gIOPMRootNode)
209#define IS_ROOT_DOMAIN (getPMRootDomain() == this)
39236c6e
A
210#define IS_POWER_DROP (StateOrder(fHeadNotePowerState) < StateOrder(fCurrentPowerState))
211#define IS_POWER_RISE (StateOrder(fHeadNotePowerState) > StateOrder(fCurrentPowerState))
7e4a7d39
A
212
213// log setPowerStates longer than (ns):
fe8ab488
A
214#if defined(__i386__) || defined(__x86_64__)
215#define LOG_SETPOWER_TIMES (300ULL * 1000ULL * 1000ULL)
216#else
7e4a7d39 217#define LOG_SETPOWER_TIMES (50ULL * 1000ULL * 1000ULL)
fe8ab488 218#endif
7e4a7d39
A
219// log app responses longer than (ns):
220#define LOG_APP_RESPONSE_TIMES (100ULL * 1000ULL * 1000ULL)
221// use message tracer to log messages longer than (ns):
222#define LOG_APP_RESPONSE_MSG_TRACER (3 * 1000ULL * 1000ULL * 1000ULL)
223
7e4a7d39
A
224enum {
225 kReserveDomainPower = 1
226};
b0d623f7 227
6d2010ae
A
228#define MS_PUSH(n) \
229 do { assert(kIOPM_BadMachineState == fSavedMachineState); \
230 assert(kIOPM_BadMachineState != n); \
231 fSavedMachineState = n; } while (false)
232
233#define MS_POP() \
234 do { assert(kIOPM_BadMachineState != fSavedMachineState); \
235 fMachineState = fSavedMachineState; \
236 fSavedMachineState = kIOPM_BadMachineState; } while (false)
237
238#define PM_ACTION_0(a) \
239 do { if (fPMActions.a) { \
240 (fPMActions.a)(fPMActions.target, this, &fPMActions); } \
241 } while (false)
242
243#define PM_ACTION_2(a, x, y) \
244 do { if (fPMActions.a) { \
39236c6e
A
245 (fPMActions.a)(fPMActions.target, this, &fPMActions, x, y, \
246 getPMRequestTag()); } \
247 } while (false)
248
249#define PM_ACTION_3(a, x, y, z) \
250 do { if (fPMActions.a) { \
251 (fPMActions.a)(fPMActions.target, this, &fPMActions, x, y, z); } \
6d2010ae 252 } while (false)
39236c6e 253
316670eb 254static OSNumber * copyClientIDForNotification(
fe8ab488 255 OSObject *object,
316670eb
A
256 IOPMInterestContext *context);
257
258static void logClientIDForNotification(
259 OSObject *object,
fe8ab488 260 IOPMInterestContext *context,
316670eb 261 const char *logString);
6d2010ae 262
2d21ac55
A
263//*********************************************************************************
264// PM machine states
6d2010ae
A
265//
266// Check kgmacros after modifying machine states.
2d21ac55 267//*********************************************************************************
1c79356b 268
2d21ac55 269enum {
6d2010ae
A
270 kIOPM_Finished = 0,
271
2d21ac55 272 kIOPM_OurChangeTellClientsPowerDown = 1,
39236c6e
A
273 kIOPM_OurChangeTellUserPMPolicyPowerDown = 2,
274 kIOPM_OurChangeTellPriorityClientsPowerDown = 3,
275 kIOPM_OurChangeNotifyInterestedDriversWillChange = 4,
276 kIOPM_OurChangeSetPowerState = 5,
277 kIOPM_OurChangeWaitForPowerSettle = 6,
278 kIOPM_OurChangeNotifyInterestedDriversDidChange = 7,
279 kIOPM_OurChangeTellCapabilityDidChange = 8,
280 kIOPM_OurChangeFinish = 9,
6d2010ae
A
281
282 kIOPM_ParentChangeTellPriorityClientsPowerDown = 10,
283 kIOPM_ParentChangeNotifyInterestedDriversWillChange = 11,
284 kIOPM_ParentChangeSetPowerState = 12,
285 kIOPM_ParentChangeWaitForPowerSettle = 13,
286 kIOPM_ParentChangeNotifyInterestedDriversDidChange = 14,
287 kIOPM_ParentChangeTellCapabilityDidChange = 15,
288 kIOPM_ParentChangeAcknowledgePowerChange = 16,
289
290 kIOPM_NotifyChildrenStart = 17,
291 kIOPM_NotifyChildrenOrdered = 18,
292 kIOPM_NotifyChildrenDelayed = 19,
293 kIOPM_SyncTellClientsPowerDown = 20,
294 kIOPM_SyncTellPriorityClientsPowerDown = 21,
295 kIOPM_SyncNotifyWillChange = 22,
b0d623f7 296 kIOPM_SyncNotifyDidChange = 23,
6d2010ae
A
297 kIOPM_SyncTellCapabilityDidChange = 24,
298 kIOPM_SyncFinish = 25,
299 kIOPM_TellCapabilityChangeDone = 26,
300 kIOPM_DriverThreadCallDone = 27,
301
302 kIOPM_BadMachineState = 0xFFFFFFFF
2d21ac55
A
303};
304
2d21ac55 305//*********************************************************************************
b0d623f7 306// [public] PMinit
2d21ac55
A
307//
308// Initialize power management.
309//*********************************************************************************
1c79356b 310
39236c6e 311void IOService::PMinit( void )
1c79356b 312{
2d21ac55 313 if ( !initialized )
fe8ab488
A
314 {
315 if ( !gIOPMInitialized )
316 {
b0d623f7 317 gPlatform = getPlatform();
6d2010ae
A
318 gIOPMWorkLoop = IOWorkLoop::workLoop();
319 if (gIOPMWorkLoop)
320 {
321 gIOPMRequestQueue = IOPMRequestQueue::create(
322 this, OSMemberFunctionCast(IOPMRequestQueue::Action,
3e170ce0 323 this, &IOService::actionPMRequestQueue));
6d2010ae
A
324
325 gIOPMReplyQueue = IOPMRequestQueue::create(
326 this, OSMemberFunctionCast(IOPMRequestQueue::Action,
3e170ce0 327 this, &IOService::actionPMReplyQueue));
6d2010ae 328
3e170ce0 329 gIOPMWorkQueue = IOPMWorkQueue::create(this,
6d2010ae 330 OSMemberFunctionCast(IOPMWorkQueue::Action, this,
3e170ce0 331 &IOService::actionPMWorkQueueInvoke),
6d2010ae 332 OSMemberFunctionCast(IOPMWorkQueue::Action, this,
3e170ce0 333 &IOService::actionPMWorkQueueRetire));
6d2010ae 334
3e170ce0 335 gIOPMCompletionQueue = IOPMCompletionQueue::create(
6d2010ae 336 this, OSMemberFunctionCast(IOPMCompletionQueue::Action,
3e170ce0 337 this, &IOService::actionPMCompletionQueue));
6d2010ae
A
338
339 if (gIOPMWorkLoop->addEventSource(gIOPMRequestQueue) !=
340 kIOReturnSuccess)
341 {
342 gIOPMRequestQueue->release();
343 gIOPMRequestQueue = 0;
344 }
2d21ac55 345
6d2010ae
A
346 if (gIOPMWorkLoop->addEventSource(gIOPMReplyQueue) !=
347 kIOReturnSuccess)
348 {
349 gIOPMReplyQueue->release();
350 gIOPMReplyQueue = 0;
351 }
352
353 if (gIOPMWorkLoop->addEventSource(gIOPMWorkQueue) !=
354 kIOReturnSuccess)
355 {
356 gIOPMWorkQueue->release();
357 gIOPMWorkQueue = 0;
358 }
2d21ac55 359
3e170ce0
A
360 // Must be added after the work queue, which pushes request
361 // to the completion queue without signaling the work loop.
362 if (gIOPMWorkLoop->addEventSource(gIOPMCompletionQueue) !=
6d2010ae
A
363 kIOReturnSuccess)
364 {
3e170ce0
A
365 gIOPMCompletionQueue->release();
366 gIOPMCompletionQueue = 0;
6d2010ae 367 }
2d21ac55 368
6d2010ae
A
369 gIOPMPowerClientDevice =
370 OSSymbol::withCStringNoCopy( "DevicePowerState" );
2d21ac55 371
6d2010ae
A
372 gIOPMPowerClientDriver =
373 OSSymbol::withCStringNoCopy( "DriverPowerState" );
2d21ac55 374
6d2010ae
A
375 gIOPMPowerClientChildProxy =
376 OSSymbol::withCStringNoCopy( "ChildProxyPowerState" );
b0d623f7 377
6d2010ae
A
378 gIOPMPowerClientChildren =
379 OSSymbol::withCStringNoCopy( "ChildrenPowerState" );
db609669
A
380
381 gIOPMPowerClientAdvisoryTickle =
382 OSSymbol::withCStringNoCopy( "AdvisoryTicklePowerState" );
39236c6e
A
383
384 gIOPMPowerClientRootDomain =
385 OSSymbol::withCStringNoCopy( "RootDomainPower" );
3e170ce0
A
386
387 gIOSpinDumpKextName[0] = '\0';
388 gIOSpinDumpDelayType[0] = '\0';
6d2010ae 389 }
2d21ac55 390
3e170ce0 391 if (gIOPMRequestQueue && gIOPMReplyQueue && gIOPMCompletionQueue)
6d2010ae
A
392 gIOPMInitialized = true;
393 }
394 if (!gIOPMInitialized)
395 return;
2d21ac55
A
396
397 pwrMgt = new IOServicePM;
398 pwrMgt->init();
399 setProperty(kPwrMgtKey, pwrMgt);
400
6d2010ae
A
401 queue_init(&pwrMgt->WorkChain);
402 queue_init(&pwrMgt->RequestHead);
403 queue_init(&pwrMgt->PMDriverCallQueue);
404
405 fOwner = this;
2d21ac55
A
406 fPMLock = IOLockAlloc();
407 fInterestedDrivers = new IOPMinformeeList;
408 fInterestedDrivers->initialize();
39236c6e
A
409 fDesiredPowerState = kPowerStateZero;
410 fDeviceDesire = kPowerStateZero;
6d2010ae
A
411 fInitialPowerChange = true;
412 fInitialSetPowerState = true;
413 fPreviousRequestPowerFlags = 0;
414 fDeviceOverrideEnabled = false;
2d21ac55 415 fMachineState = kIOPM_Finished;
6d2010ae 416 fSavedMachineState = kIOPM_BadMachineState;
39236c6e 417 fIdleTimerMinPowerState = kPowerStateZero;
2d21ac55 418 fActivityLock = IOLockAlloc();
2d21ac55 419 fStrictTreeOrder = false;
db609669
A
420 fActivityTicklePowerState = kInvalidTicklePowerState;
421 fAdvisoryTicklePowerState = kInvalidTicklePowerState;
2d21ac55
A
422 fControllingDriver = NULL;
423 fPowerStates = NULL;
424 fNumberOfPowerStates = 0;
39236c6e 425 fCurrentPowerState = kPowerStateZero;
2d21ac55 426 fParentsCurrentPowerFlags = 0;
39236c6e 427 fMaxPowerState = kPowerStateZero;
2d21ac55 428 fName = getName();
2d21ac55
A
429 fParentsKnowState = false;
430 fSerialNumber = 0;
431 fResponseArray = NULL;
b0d623f7 432 fNotifyClientArray = NULL;
2d21ac55 433 fCurrentPowerConsumption = kIOPMUnknown;
b0d623f7 434 fOverrideMaxPowerState = kIOPMPowerStateMax;
2d21ac55 435
b0d623f7 436 if (!gIOPMRootNode && (getParentEntry(gIOPowerPlane) == getRegistryRoot()))
55e303ae 437 {
b0d623f7
A
438 gIOPMRootNode = this;
439 fParentsKnowState = true;
1c79356b 440 }
bd504ef0
A
441 else if (getProperty(kIOPMResetPowerStateOnWakeKey) == kOSBooleanTrue)
442 {
443 fResetPowerStateOnWake = true;
444 }
2d21ac55 445
39236c6e
A
446 if (IS_ROOT_DOMAIN)
447 {
448 fWatchdogTimer = thread_call_allocate(
449 &IOService::watchdog_timer_expired, (thread_call_param_t)this);
450 }
451
2d21ac55 452 fAckTimer = thread_call_allocate(
fe8ab488 453 &IOService::ack_timer_expired, (thread_call_param_t)this);
2d21ac55 454 fSettleTimer = thread_call_allocate(
fe8ab488 455 &settle_timer_expired, (thread_call_param_t)this);
6d2010ae
A
456 fIdleTimer = thread_call_allocate(
457 &idle_timer_expired, (thread_call_param_t)this);
458 fDriverCallEntry = thread_call_allocate(
fe8ab488 459 (thread_call_func_t) &IOService::pmDriverCallout, this);
6d2010ae 460 assert(fDriverCallEntry);
3e170ce0
A
461 if (kIOKextSpinDump & gIOKitDebug)
462 {
463 fSpinDumpTimer = thread_call_allocate(
464 &IOService::spindump_timer_expired, (thread_call_param_t)this);
465 }
6d2010ae
A
466
467 // Check for powerChangeDone override.
468 if (OSMemberFunctionCast(void (*)(void),
fe8ab488
A
469 getResourceService(), &IOService::powerChangeDone) !=
470 OSMemberFunctionCast(void (*)(void),
471 this, &IOService::powerChangeDone))
6d2010ae
A
472 {
473 fPCDFunctionOverride = true;
474 }
2d21ac55
A
475
476#if PM_VARS_SUPPORT
477 IOPMprot * prot = new IOPMprot;
478 if (prot)
479 {
480 prot->init();
481 prot->ourName = fName;
b0d623f7 482 prot->thePlatform = gPlatform;
2d21ac55
A
483 fPMVars = prot;
484 pm_vars = prot;
fe8ab488 485 }
2d21ac55 486#else
6d2010ae 487 pm_vars = (void *) (uintptr_t) true;
2d21ac55
A
488#endif
489
1c79356b
A
490 initialized = true;
491 }
492}
493
0b4e3aa0 494//*********************************************************************************
b0d623f7 495// [private] PMfree
0b4e3aa0 496//
7e4a7d39 497// Free the data created by PMinit. Only called from IOService::free().
0b4e3aa0 498//*********************************************************************************
2d21ac55 499
39236c6e 500void IOService::PMfree( void )
0b4e3aa0 501{
6d2010ae 502 initialized = false;
2d21ac55
A
503 pm_vars = 0;
504
505 if ( pwrMgt )
6d2010ae
A
506 {
507 assert(fMachineState == kIOPM_Finished);
508 assert(fInsertInterestSet == NULL);
509 assert(fRemoveInterestSet == NULL);
2d21ac55 510 assert(fNotifyChildArray == NULL);
6d2010ae
A
511 assert(queue_empty(&pwrMgt->RequestHead));
512 assert(queue_empty(&fPMDriverCallQueue));
2d21ac55 513
39236c6e
A
514 if (fWatchdogTimer) {
515 thread_call_cancel(fWatchdogTimer);
516 thread_call_free(fWatchdogTimer);
517 fWatchdogTimer = NULL;
518 }
519
2d21ac55
A
520 if ( fSettleTimer ) {
521 thread_call_cancel(fSettleTimer);
522 thread_call_free(fSettleTimer);
523 fSettleTimer = NULL;
0b4e3aa0 524 }
2d21ac55
A
525 if ( fAckTimer ) {
526 thread_call_cancel(fAckTimer);
527 thread_call_free(fAckTimer);
528 fAckTimer = NULL;
0b4e3aa0 529 }
6d2010ae
A
530 if ( fIdleTimer ) {
531 thread_call_cancel(fIdleTimer);
532 thread_call_free(fIdleTimer);
533 fIdleTimer = NULL;
534 }
2d21ac55
A
535 if ( fDriverCallEntry ) {
536 thread_call_free(fDriverCallEntry);
537 fDriverCallEntry = NULL;
0b4e3aa0 538 }
3e170ce0
A
539 if ( fSpinDumpTimer ) {
540 thread_call_cancel(fSpinDumpTimer);
541 thread_call_free(fSpinDumpTimer);
542 fSpinDumpTimer = NULL;
543 }
2d21ac55
A
544 if ( fPMLock ) {
545 IOLockFree(fPMLock);
546 fPMLock = NULL;
0b4e3aa0 547 }
2d21ac55
A
548 if ( fActivityLock ) {
549 IOLockFree(fActivityLock);
550 fActivityLock = NULL;
0b4e3aa0 551 }
6d2010ae
A
552 if ( fInterestedDrivers ) {
553 fInterestedDrivers->release();
554 fInterestedDrivers = NULL;
555 }
556 if (fDriverCallParamSlots && fDriverCallParamPtr) {
557 IODelete(fDriverCallParamPtr, DriverCallParam, fDriverCallParamSlots);
558 fDriverCallParamPtr = 0;
559 fDriverCallParamSlots = 0;
560 }
2d21ac55
A
561 if ( fResponseArray ) {
562 fResponseArray->release();
563 fResponseArray = NULL;
0b4e3aa0 564 }
b0d623f7
A
565 if ( fNotifyClientArray ) {
566 fNotifyClientArray->release();
567 fNotifyClientArray = NULL;
568 }
2d21ac55 569 if (fPowerStates && fNumberOfPowerStates) {
6d2010ae 570 IODelete(fPowerStates, IOPMPSEntry, fNumberOfPowerStates);
2d21ac55
A
571 fNumberOfPowerStates = 0;
572 fPowerStates = NULL;
0b4e3aa0 573 }
6d2010ae
A
574 if (fPowerClients) {
575 fPowerClients->release();
576 fPowerClients = 0;
577 }
2d21ac55
A
578
579#if PM_VARS_SUPPORT
6d2010ae
A
580 if (fPMVars)
581 {
582 fPMVars->release();
583 fPMVars = 0;
584 }
2d21ac55
A
585#endif
586
587 pwrMgt->release();
6d2010ae 588 pwrMgt = 0;
0b4e3aa0
A
589 }
590}
591
4b17d6b6
A
592void IOService::PMDebug( uint32_t event, uintptr_t param1, uintptr_t param2 )
593{
594 OUR_PMLog(event, param1, param2);
595}
596
2d21ac55 597//*********************************************************************************
b0d623f7 598// [public] joinPMtree
2d21ac55
A
599//
600// A policy-maker calls its nub here when initializing, to be attached into
601// the power management hierarchy. The default function is to call the
602// platform expert, which knows how to do it. This method is overridden
603// by a nub subclass which may either know how to do it, or may need to
604// take other action.
605//
606// This may be the only "power management" method used in a nub,
607// meaning it may not be initialized for power management.
608//*********************************************************************************
609
39236c6e 610void IOService::joinPMtree( IOService * driver )
2d21ac55 611{
b0d623f7 612 IOPlatformExpert * platform;
2d21ac55
A
613
614 platform = getPlatform();
615 assert(platform != 0);
616 platform->PMRegisterDevice(this, driver);
617}
0b4e3aa0 618
b0d623f7 619#ifndef __LP64__
1c79356b 620//*********************************************************************************
b0d623f7 621// [deprecated] youAreRoot
1c79356b 622//
2d21ac55 623// Power Managment is informing us that we are the root power domain.
2d21ac55
A
624//*********************************************************************************
625
39236c6e 626IOReturn IOService::youAreRoot( void )
2d21ac55 627{
2d21ac55
A
628 return IOPMNoErr;
629}
b0d623f7 630#endif /* !__LP64__ */
2d21ac55
A
631
632//*********************************************************************************
b0d623f7 633// [public] PMstop
2d21ac55
A
634//
635// Immediately stop driver callouts. Schedule an async stop request to detach
636// from power plane.
1c79356b 637//*********************************************************************************
2d21ac55 638
39236c6e 639void IOService::PMstop( void )
1c79356b 640{
6d2010ae 641 IOPMRequest * request;
2d21ac55 642
6d2010ae
A
643 if (!initialized)
644 return;
2d21ac55 645
6d2010ae 646 PM_LOCK();
2d21ac55 647
6d2010ae 648 if (fLockedFlags.PMStop)
b0d623f7 649 {
6d2010ae
A
650 PM_LOG2("%s: PMstop() already stopped\n", fName);
651 PM_UNLOCK();
652 return;
b0d623f7 653 }
6d2010ae
A
654
655 // Inhibit future driver calls.
656 fLockedFlags.PMStop = true;
657
658 // Wait for all prior driver calls to finish.
659 waitForPMDriverCall();
660
2d21ac55
A
661 PM_UNLOCK();
662
6d2010ae
A
663 // The rest of the work is performed async.
664 request = acquirePMRequest( this, kIOPMRequestTypePMStop );
665 if (request)
666 {
39236c6e 667 PM_LOG2("%s: %p PMstop\n", getName(), OBFUSCATE(this));
6d2010ae
A
668 submitPMRequest( request );
669 }
2d21ac55
A
670}
671
672//*********************************************************************************
b0d623f7 673// [private] handlePMstop
2d21ac55 674//
b0d623f7 675// Disconnect the node from all parents and children in the power plane.
2d21ac55
A
676//*********************************************************************************
677
39236c6e 678void IOService::handlePMstop( IOPMRequest * request )
2d21ac55 679{
6d2010ae 680 OSIterator * iter;
fe8ab488
A
681 OSObject * next;
682 IOPowerConnection * connection;
683 IOService * theChild;
684 IOService * theParent;
1c79356b 685
fe8ab488
A
686 PM_ASSERT_IN_GATE();
687 PM_LOG2("%s: %p %s start\n", getName(), OBFUSCATE(this), __FUNCTION__);
1c79356b 688
316670eb
A
689 // remove driver from prevent system sleep lists
690 getPMRootDomain()->updatePreventIdleSleepList(this, false);
691 getPMRootDomain()->updatePreventSystemSleepList(this, false);
692
2d21ac55 693 // remove the property
fe8ab488 694 removeProperty(kPwrMgtKey);
2d21ac55
A
695
696 // detach parents
697 iter = getParentIterator(gIOPowerPlane);
698 if ( iter )
55e303ae 699 {
2d21ac55 700 while ( (next = iter->getNextObject()) )
55e303ae 701 {
2d21ac55 702 if ( (connection = OSDynamicCast(IOPowerConnection, next)) )
55e303ae 703 {
0b4e3aa0 704 theParent = (IOService *)connection->copyParentEntry(gIOPowerPlane);
2d21ac55 705 if ( theParent )
55e303ae 706 {
0b4e3aa0
A
707 theParent->removePowerChild(connection);
708 theParent->release();
709 }
1c79356b
A
710 }
711 }
712 iter->release();
713 }
55e303ae 714
2d21ac55
A
715 // detach IOConnections
716 detachAbove( gIOPowerPlane );
fe8ab488 717
2d21ac55
A
718 // no more power state changes
719 fParentsKnowState = false;
1c79356b 720
2d21ac55
A
721 // detach children
722 iter = getChildIterator(gIOPowerPlane);
723 if ( iter )
55e303ae 724 {
2d21ac55 725 while ( (next = iter->getNextObject()) )
55e303ae 726 {
2d21ac55 727 if ( (connection = OSDynamicCast(IOPowerConnection, next)) )
55e303ae 728 {
0b4e3aa0 729 theChild = ((IOService *)(connection->copyChildEntry(gIOPowerPlane)));
2d21ac55 730 if ( theChild )
55e303ae
A
731 {
732 // detach nub from child
2d21ac55 733 connection->detachFromChild(theChild, gIOPowerPlane);
0b4e3aa0
A
734 theChild->release();
735 }
55e303ae 736 // detach us from nub
2d21ac55 737 detachFromChild(connection, gIOPowerPlane);
1c79356b
A
738 }
739 }
740 iter->release();
741 }
1c79356b 742
0b4e3aa0
A
743 // Remove all interested drivers from the list, including the power
744 // controlling driver.
745 //
746 // Usually, the controlling driver and the policy-maker functionality
747 // are implemented by the same object, and without the deregistration,
748 // the object will be holding an extra retain on itself, and cannot
749 // be freed.
750
2d21ac55 751 if ( fInterestedDrivers )
0b4e3aa0 752 {
fe8ab488
A
753 IOPMinformeeList * list = fInterestedDrivers;
754 IOPMinformee * item;
1c79356b 755
6d2010ae
A
756 PM_LOCK();
757 while ((item = list->firstInList()))
758 {
759 list->removeFromList(item->whatObject);
760 }
761 PM_UNLOCK();
762 }
2d21ac55 763
bd504ef0
A
764 // Clear idle period to prevent idleTimerExpired() from servicing
765 // idle timer expirations.
766
6d2010ae
A
767 fIdleTimerPeriod = 0;
768 if (fIdleTimer && thread_call_cancel(fIdleTimer))
769 release();
1c79356b 770
39236c6e 771 PM_LOG2("%s: %p %s done\n", getName(), OBFUSCATE(this), __FUNCTION__);
2d21ac55 772}
1c79356b
A
773
774//*********************************************************************************
b0d623f7 775// [public] addPowerChild
1c79356b 776//
2d21ac55 777// Power Management is informing us who our children are.
1c79356b 778//*********************************************************************************
2d21ac55 779
39236c6e 780IOReturn IOService::addPowerChild( IOService * child )
1c79356b 781{
fe8ab488
A
782 IOPowerConnection * connection = 0;
783 IOPMRequest * requests[3] = {0, 0, 0};
784 OSIterator * iter;
785 bool ok = true;
2d21ac55 786
fe8ab488
A
787 if (!child)
788 return kIOReturnBadArgument;
2d21ac55
A
789
790 if (!initialized || !child->initialized)
fe8ab488 791 return IOPMNotYetInitialized;
2d21ac55 792
b0d623f7 793 OUR_PMLog( kPMLogAddChild, (uintptr_t) child, 0 );
2d21ac55 794
fe8ab488
A
795 do {
796 // Is this child already one of our children?
797
798 iter = child->getParentIterator( gIOPowerPlane );
799 if ( iter )
800 {
801 IORegistryEntry * entry;
802 OSObject * next;
803
804 while ((next = iter->getNextObject()))
805 {
806 if ((entry = OSDynamicCast(IORegistryEntry, next)) &&
807 isChild(entry, gIOPowerPlane))
808 {
809 ok = false;
810 break;
811 }
812 }
813 iter->release();
814 }
815 if (!ok)
816 {
817 PM_LOG("%s: %s (%p) is already a child\n",
818 getName(), child->getName(), OBFUSCATE(child));
819 break;
820 }
821
822 // Add the child to the power plane immediately, but the
823 // joining connection is marked as not ready.
824 // We want the child to appear in the power plane before
825 // returning to the caller, but don't want the caller to
826 // block on the PM work loop.
827
828 connection = new IOPowerConnection;
829 if (!connection)
830 break;
831
832 // Create a chain of PM requests to perform the bottom-half
833 // work from the PM work loop.
834
835 requests[0] = acquirePMRequest(
836 /* target */ this,
837 /* type */ kIOPMRequestTypeAddPowerChild1 );
838
839 requests[1] = acquirePMRequest(
840 /* target */ child,
841 /* type */ kIOPMRequestTypeAddPowerChild2 );
842
843 requests[2] = acquirePMRequest(
844 /* target */ this,
845 /* type */ kIOPMRequestTypeAddPowerChild3 );
846
847 if (!requests[0] || !requests[1] || !requests[2])
848 break;
849
850 requests[0]->attachNextRequest( requests[1] );
851 requests[1]->attachNextRequest( requests[2] );
852
853 connection->init();
854 connection->start(this);
855 connection->setAwaitingAck(false);
856 connection->setReadyFlag(false);
857
858 attachToChild( connection, gIOPowerPlane );
859 connection->attachToChild( child, gIOPowerPlane );
860
861 // connection needs to be released
862 requests[0]->fArg0 = connection;
863 requests[1]->fArg0 = connection;
864 requests[2]->fArg0 = connection;
865
3e170ce0 866 submitPMRequests( requests, 3 );
fe8ab488
A
867 return kIOReturnSuccess;
868 }
869 while (false);
870
871 if (connection) connection->release();
872 if (requests[0]) releasePMRequest(requests[0]);
873 if (requests[1]) releasePMRequest(requests[1]);
874 if (requests[2]) releasePMRequest(requests[2]);
875
876 // Silent failure, to prevent platform drivers from adding the child
877 // to the root domain.
878
879 return kIOReturnSuccess;
2d21ac55 880}
1c79356b
A
881
882//*********************************************************************************
2d21ac55 883// [private] addPowerChild1
1c79356b 884//
b0d623f7 885// Step 1/3 of adding a power child. Called on the power parent.
1c79356b 886//*********************************************************************************
1c79356b 887
39236c6e 888void IOService::addPowerChild1( IOPMRequest * request )
2d21ac55 889{
fe8ab488 890 IOPMPowerStateIndex tempDesire = kPowerStateZero;
2d21ac55 891
fe8ab488 892 // Make us temporary usable before adding the child.
2d21ac55 893
fe8ab488 894 PM_ASSERT_IN_GATE();
b0d623f7 895 OUR_PMLog( kPMLogMakeUsable, kPMLogMakeUsable, 0 );
2d21ac55 896
fe8ab488
A
897 if (fControllingDriver && inPlane(gIOPowerPlane) && fParentsKnowState)
898 {
899 tempDesire = fHighestPowerState;
900 }
2d21ac55 901
fe8ab488 902 if ((tempDesire != kPowerStateZero) &&
39236c6e 903 (IS_PM_ROOT || (StateOrder(fMaxPowerState) >= StateOrder(tempDesire))))
fe8ab488
A
904 {
905 adjustPowerState(tempDesire);
906 }
2d21ac55 907}
1c79356b
A
908
909//*********************************************************************************
2d21ac55 910// [private] addPowerChild2
1c79356b 911//
b0d623f7
A
912// Step 2/3 of adding a power child. Called on the joining child.
913// Execution blocked behind addPowerChild1.
1c79356b 914//*********************************************************************************
2d21ac55 915
39236c6e 916void IOService::addPowerChild2( IOPMRequest * request )
1c79356b 917{
fe8ab488
A
918 IOPowerConnection * connection = (IOPowerConnection *) request->fArg0;
919 IOService * parent;
920 IOPMPowerFlags powerFlags;
921 bool knowsState;
922 unsigned long powerState;
923 unsigned long tempDesire;
2d21ac55 924
fe8ab488
A
925 PM_ASSERT_IN_GATE();
926 parent = (IOService *) connection->getParentEntry(gIOPowerPlane);
2d21ac55 927
fe8ab488
A
928 if (!parent || !inPlane(gIOPowerPlane))
929 {
930 PM_LOG("%s: addPowerChild2 not in power plane\n", getName());
931 return;
932 }
1c79356b 933
fe8ab488
A
934 // Parent will be waiting for us to complete this stage.
935 // It is safe to directly access parent's vars.
0b4e3aa0 936
fe8ab488
A
937 knowsState = (parent->fPowerStates) && (parent->fParentsKnowState);
938 powerState = parent->fCurrentPowerState;
1c79356b 939
fe8ab488
A
940 if (knowsState)
941 powerFlags = parent->fPowerStates[powerState].outputPowerFlags;
942 else
943 powerFlags = 0;
1c79356b 944
fe8ab488 945 // Set our power parent.
2d21ac55
A
946
947 OUR_PMLog(kPMLogSetParent, knowsState, powerFlags);
948
fe8ab488 949 setParentInfo( powerFlags, connection, knowsState );
2d21ac55 950
fe8ab488 951 connection->setReadyFlag(true);
2d21ac55
A
952
953 if ( fControllingDriver && fParentsKnowState )
55e303ae 954 {
6d2010ae 955 fMaxPowerState = fControllingDriver->maxCapabilityForDomainState(fParentsCurrentPowerFlags);
55e303ae 956 // initially change into the state we are already in
2d21ac55 957 tempDesire = fControllingDriver->initialPowerStateForDomainState(fParentsCurrentPowerFlags);
6d2010ae 958 fPreviousRequestPowerFlags = (IOPMPowerFlags)(-1);
b0d623f7 959 adjustPowerState(tempDesire);
1c79356b 960 }
b0d623f7 961
6d2010ae 962 getPMRootDomain()->tagPowerPlaneService(this, &fPMActions);
1c79356b
A
963}
964
1c79356b 965//*********************************************************************************
2d21ac55 966// [private] addPowerChild3
1c79356b 967//
b0d623f7
A
968// Step 3/3 of adding a power child. Called on the parent.
969// Execution blocked behind addPowerChild2.
1c79356b 970//*********************************************************************************
1c79356b 971
39236c6e 972void IOService::addPowerChild3( IOPMRequest * request )
2d21ac55 973{
fe8ab488
A
974 IOPowerConnection * connection = (IOPowerConnection *) request->fArg0;
975 IOService * child;
b0d623f7 976 IOPMrootDomain * rootDomain = getPMRootDomain();
2d21ac55 977
fe8ab488
A
978 PM_ASSERT_IN_GATE();
979 child = (IOService *) connection->getChildEntry(gIOPowerPlane);
2d21ac55 980
fe8ab488
A
981 if (child && inPlane(gIOPowerPlane))
982 {
983 if ((this != rootDomain) && child->getProperty("IOPMStrictTreeOrder"))
984 {
985 PM_LOG1("%s: strict PM order enforced\n", getName());
986 fStrictTreeOrder = true;
987 }
2d21ac55 988
b0d623f7
A
989 if (rootDomain)
990 rootDomain->joinAggressiveness( child );
fe8ab488
A
991 }
992 else
993 {
994 PM_LOG("%s: addPowerChild3 not in power plane\n", getName());
995 }
1c79356b 996
fe8ab488 997 connection->release();
2d21ac55 998}
1c79356b 999
b0d623f7 1000#ifndef __LP64__
2d21ac55 1001//*********************************************************************************
b0d623f7 1002// [deprecated] setPowerParent
2d21ac55
A
1003//
1004// Power Management is informing us who our parent is.
1005// If we have a controlling driver, find out, given our newly-informed
1006// power domain state, what state it would be in, and then tell it
1007// to assume that state.
1008//*********************************************************************************
1c79356b 1009
39236c6e 1010IOReturn IOService::setPowerParent(
fe8ab488 1011 IOPowerConnection * theParent, bool stateKnown, IOPMPowerFlags powerFlags )
2d21ac55 1012{
fe8ab488 1013 return kIOReturnUnsupported;
1c79356b 1014}
b0d623f7 1015#endif /* !__LP64__ */
1c79356b 1016
2d21ac55 1017//*********************************************************************************
b0d623f7 1018// [public] removePowerChild
1c79356b 1019//
2d21ac55
A
1020// Called on a parent whose child is being removed by PMstop().
1021//*********************************************************************************
1022
39236c6e 1023IOReturn IOService::removePowerChild( IOPowerConnection * theNub )
0b4e3aa0 1024{
fe8ab488 1025 IORegistryEntry * theChild;
0b4e3aa0 1026
fe8ab488 1027 PM_ASSERT_IN_GATE();
2d21ac55 1028 OUR_PMLog( kPMLogRemoveChild, 0, 0 );
1c79356b 1029
0b4e3aa0 1030 theNub->retain();
b0d623f7 1031
55e303ae 1032 // detach nub from child
fe8ab488 1033 theChild = theNub->copyChildEntry(gIOPowerPlane);
2d21ac55 1034 if ( theChild )
55e303ae 1035 {
0b4e3aa0
A
1036 theNub->detachFromChild(theChild, gIOPowerPlane);
1037 theChild->release();
1038 }
55e303ae 1039 // detach from the nub
2d21ac55
A
1040 detachFromChild(theNub, gIOPowerPlane);
1041
1042 // Are we awaiting an ack from this child?
1043 if ( theNub->getAwaitingAck() )
fe8ab488
A
1044 {
1045 // yes, pretend we got one
1046 theNub->setAwaitingAck(false);
1047 if (fHeadNotePendingAcks != 0 )
1048 {
1049 // that's one fewer ack to worry about
1050 fHeadNotePendingAcks--;
1051
1052 // is that the last?
1053 if ( fHeadNotePendingAcks == 0 )
1054 {
1055 stop_ack_timer();
1056
3e170ce0
A
1057 // This parent may have a request in the work queue that is
1058 // blocked on fHeadNotePendingAcks=0. And removePowerChild()
1059 // is called while executing the child's PMstop request so they
1060 // can occur simultaneously. IOPMWorkQueue::checkForWork() must
1061 // restart and check all request queues again.
1062
fe8ab488
A
1063 gIOPMWorkQueue->incrementProducerCount();
1064 }
1065 }
1066 }
1067
1068 theNub->release();
1069
1070 // A child has gone away, re-scan children desires and clamp bits.
1071 // The fPendingAdjustPowerRequest helps to reduce redundant parent work.
1072
1073 if (!fAdjustPowerScheduled)
1074 {
1075 IOPMRequest * request;
1076 request = acquirePMRequest( this, kIOPMRequestTypeAdjustPowerState );
1077 if (request)
1078 {
1079 submitPMRequest( request );
1080 fAdjustPowerScheduled = true;
1081 }
1082 }
1c79356b
A
1083
1084 return IOPMNoErr;
1085}
1086
1c79356b 1087//*********************************************************************************
b0d623f7 1088// [public] registerPowerDriver
1c79356b
A
1089//
1090// A driver has called us volunteering to control power to our device.
1c79356b
A
1091//*********************************************************************************
1092
39236c6e 1093IOReturn IOService::registerPowerDriver(
fe8ab488
A
1094 IOService * powerDriver,
1095 IOPMPowerState * powerStates,
1096 unsigned long numberOfStates )
1c79356b 1097{
fe8ab488
A
1098 IOPMRequest * request;
1099 IOPMPSEntry * powerStatesCopy = 0;
39236c6e
A
1100 IOPMPowerStateIndex stateOrder;
1101 IOReturn error = kIOReturnSuccess;
55e303ae 1102
2d21ac55 1103 if (!initialized)
fe8ab488
A
1104 return IOPMNotYetInitialized;
1105
1106 if (!powerStates || (numberOfStates < 2))
1107 {
1108 OUR_PMLog(kPMLogControllingDriverErr5, numberOfStates, 0);
1109 return kIOReturnBadArgument;
1110 }
1111
1112 if (!powerDriver || !powerDriver->initialized)
1113 {
1114 OUR_PMLog(kPMLogControllingDriverErr4, 0, 0);
1115 return kIOReturnBadArgument;
1116 }
1117
1118 if (powerStates[0].version > kIOPMPowerStateVersion2)
1119 {
1120 OUR_PMLog(kPMLogControllingDriverErr1, powerStates[0].version, 0);
1121 return kIOReturnBadArgument;
1122 }
1123
1124 do {
1125 // Make a copy of the supplied power state array.
1126 powerStatesCopy = IONew(IOPMPSEntry, numberOfStates);
1127 if (!powerStatesCopy)
39236c6e
A
1128 {
1129 error = kIOReturnNoMemory;
fe8ab488 1130 break;
39236c6e
A
1131 }
1132
1133 // Initialize to bogus values
1134 for (IOPMPowerStateIndex i = 0; i < numberOfStates; i++)
1135 powerStatesCopy[i].stateOrderToIndex = kIOPMPowerStateMax;
2d21ac55 1136
6d2010ae
A
1137 for (uint32_t i = 0; i < numberOfStates; i++)
1138 {
1139 powerStatesCopy[i].capabilityFlags = powerStates[i].capabilityFlags;
1140 powerStatesCopy[i].outputPowerFlags = powerStates[i].outputPowerCharacter;
1141 powerStatesCopy[i].inputPowerFlags = powerStates[i].inputPowerRequirement;
1142 powerStatesCopy[i].staticPower = powerStates[i].staticPower;
1143 powerStatesCopy[i].settleUpTime = powerStates[i].settleUpTime;
1144 powerStatesCopy[i].settleDownTime = powerStates[i].settleDownTime;
39236c6e
A
1145 if (powerStates[i].version >= kIOPMPowerStateVersion2)
1146 stateOrder = powerStates[i].stateOrder;
1147 else
1148 stateOrder = i;
1149
1150 if (stateOrder < numberOfStates)
1151 {
1152 powerStatesCopy[i].stateOrder = stateOrder;
1153 powerStatesCopy[stateOrder].stateOrderToIndex = i;
1154 }
6d2010ae 1155 }
2d21ac55 1156
39236c6e
A
1157 for (IOPMPowerStateIndex i = 0; i < numberOfStates; i++)
1158 {
1159 if (powerStatesCopy[i].stateOrderToIndex == kIOPMPowerStateMax)
1160 {
1161 // power state order missing
1162 error = kIOReturnBadArgument;
1163 break;
1164 }
1165 }
1166 if (kIOReturnSuccess != error)
1167 break;
1168
fe8ab488
A
1169 request = acquirePMRequest( this, kIOPMRequestTypeRegisterPowerDriver );
1170 if (!request)
39236c6e
A
1171 {
1172 error = kIOReturnNoMemory;
fe8ab488 1173 break;
39236c6e 1174 }
2d21ac55 1175
fe8ab488
A
1176 powerDriver->retain();
1177 request->fArg0 = (void *) powerDriver;
1178 request->fArg1 = (void *) powerStatesCopy;
1179 request->fArg2 = (void *) numberOfStates;
2d21ac55 1180
fe8ab488 1181 submitPMRequest( request );
39236c6e 1182 return kIOReturnSuccess;
fe8ab488
A
1183 }
1184 while (false);
2d21ac55 1185
fe8ab488
A
1186 if (powerStatesCopy)
1187 IODelete(powerStatesCopy, IOPMPSEntry, numberOfStates);
39236c6e 1188
fe8ab488 1189 return error;
1c79356b
A
1190}
1191
1192//*********************************************************************************
2d21ac55
A
1193// [private] handleRegisterPowerDriver
1194//*********************************************************************************
1195
39236c6e 1196void IOService::handleRegisterPowerDriver( IOPMRequest * request )
2d21ac55 1197{
fe8ab488
A
1198 IOService * powerDriver = (IOService *) request->fArg0;
1199 IOPMPSEntry * powerStates = (IOPMPSEntry *) request->fArg1;
1200 unsigned long numberOfStates = (unsigned long) request->fArg2;
39236c6e
A
1201 unsigned long i, stateIndex;
1202 unsigned long lowestPowerState;
fe8ab488
A
1203 IOService * root;
1204 OSIterator * iter;
2d21ac55 1205
fe8ab488
A
1206 PM_ASSERT_IN_GATE();
1207 assert(powerStates);
1208 assert(powerDriver);
1209 assert(numberOfStates > 1);
2d21ac55
A
1210
1211 if ( !fNumberOfPowerStates )
1212 {
fe8ab488
A
1213 OUR_PMLog(kPMLogControllingDriver,
1214 (unsigned long) numberOfStates,
1215 (unsigned long) kIOPMPowerStateVersion1);
2d21ac55
A
1216
1217 fPowerStates = powerStates;
fe8ab488
A
1218 fNumberOfPowerStates = numberOfStates;
1219 fControllingDriver = powerDriver;
2d21ac55
A
1220 fCurrentCapabilityFlags = fPowerStates[0].capabilityFlags;
1221
39236c6e
A
1222 lowestPowerState = fPowerStates[0].stateOrderToIndex;
1223 fHighestPowerState = fPowerStates[numberOfStates - 1].stateOrderToIndex;
1224
fe8ab488
A
1225 // OR'in all the output power flags
1226 fMergedOutputPowerFlags = 0;
39236c6e 1227 fDeviceUsablePowerState = lowestPowerState;
fe8ab488 1228 for ( i = 0; i < numberOfStates; i++ )
39236c6e 1229 {
fe8ab488 1230 fMergedOutputPowerFlags |= fPowerStates[i].outputPowerFlags;
39236c6e
A
1231
1232 stateIndex = fPowerStates[i].stateOrderToIndex;
1233 assert(stateIndex < numberOfStates);
1234 if ((fDeviceUsablePowerState == lowestPowerState) &&
1235 (fPowerStates[stateIndex].capabilityFlags & IOPMDeviceUsable))
db609669
A
1236 {
1237 // The minimum power state that the device is usable
39236c6e 1238 fDeviceUsablePowerState = stateIndex;
db609669 1239 }
fe8ab488
A
1240 }
1241
1242 // Register powerDriver as interested, unless already done.
1243 // We don't want to register the default implementation since
1244 // it does nothing. One ramification of not always registering
1245 // is the one fewer retain count held.
1246
1247 root = getPlatform()->getProvider();
1248 assert(root);
1249 if (!root ||
1250 ((OSMemberFunctionCast(void (*)(void),
1251 root, &IOService::powerStateDidChangeTo)) !=
1252 ((OSMemberFunctionCast(void (*)(void),
1253 this, &IOService::powerStateDidChangeTo)))) ||
1254 ((OSMemberFunctionCast(void (*)(void),
1255 root, &IOService::powerStateWillChangeTo)) !=
1256 ((OSMemberFunctionCast(void (*)(void),
1257 this, &IOService::powerStateWillChangeTo)))))
1258 {
1259 if (fInterestedDrivers->findItem(powerDriver) == NULL)
1260 {
1261 PM_LOCK();
1262 fInterestedDrivers->appendNewInformee(powerDriver);
1263 PM_UNLOCK();
1264 }
1265 }
1266
1267 // Examine all existing power clients and perform limit check.
b0d623f7 1268
39236c6e
A
1269 if (fPowerClients &&
1270 (iter = OSCollectionIterator::withCollection(fPowerClients)))
b0d623f7 1271 {
39236c6e
A
1272 const OSSymbol * client;
1273 while ((client = (const OSSymbol *) iter->getNextObject()))
b0d623f7 1274 {
39236c6e
A
1275 IOPMPowerStateIndex powerState = getPowerStateForClient(client);
1276 if (powerState >= numberOfStates)
b0d623f7 1277 {
39236c6e 1278 updatePowerClient(client, fHighestPowerState);
b0d623f7 1279 }
b0d623f7 1280 }
39236c6e 1281 iter->release();
b0d623f7 1282 }
2d21ac55 1283
fe8ab488
A
1284 if ( inPlane(gIOPowerPlane) && fParentsKnowState )
1285 {
1286 IOPMPowerStateIndex tempDesire;
1287 fMaxPowerState = fControllingDriver->maxCapabilityForDomainState(fParentsCurrentPowerFlags);
1288 // initially change into the state we are already in
1289 tempDesire = fControllingDriver->initialPowerStateForDomainState(fParentsCurrentPowerFlags);
1290 adjustPowerState(tempDesire);
1291 }
1292 }
1293 else
1294 {
1295 OUR_PMLog(kPMLogControllingDriverErr2, numberOfStates, 0);
6d2010ae 1296 IODelete(powerStates, IOPMPSEntry, numberOfStates);
fe8ab488 1297 }
2d21ac55 1298
fe8ab488 1299 powerDriver->release();
2d21ac55
A
1300}
1301
1302//*********************************************************************************
b0d623f7 1303// [public] registerInterestedDriver
1c79356b
A
1304//
1305// Add the caller to our list of interested drivers and return our current
1306// power state. If we don't have a power-controlling driver yet, we will
1307// call this interested driver again later when we do get a driver and find
1308// out what the current power state of the device is.
1309//*********************************************************************************
1310
39236c6e 1311IOPMPowerFlags IOService::registerInterestedDriver( IOService * driver )
1c79356b 1312{
fe8ab488
A
1313 IOPMRequest * request;
1314 bool signal;
2d21ac55 1315
6d2010ae
A
1316 if (!driver || !initialized || !fInterestedDrivers)
1317 return 0;
2d21ac55 1318
6d2010ae
A
1319 PM_LOCK();
1320 signal = (!fInsertInterestSet && !fRemoveInterestSet);
1321 if (fInsertInterestSet == NULL)
1322 fInsertInterestSet = OSSet::withCapacity(4);
1323 if (fInsertInterestSet)
1324 {
1325 fInsertInterestSet->setObject(driver);
1326 if (fRemoveInterestSet)
1327 fRemoveInterestSet->removeObject(driver);
1328 }
1329 PM_UNLOCK();
2d21ac55 1330
6d2010ae
A
1331 if (signal)
1332 {
1333 request = acquirePMRequest( this, kIOPMRequestTypeInterestChanged );
1334 if (request)
1335 submitPMRequest( request );
1336 }
1c79356b 1337
6d2010ae
A
1338 // This return value cannot be trusted, but return a value
1339 // for those clients that care.
1c79356b 1340
2d21ac55 1341 OUR_PMLog(kPMLogInterestedDriver, kIOPMDeviceUsable, 2);
fe8ab488 1342 return kIOPMDeviceUsable;
2d21ac55 1343}
1c79356b 1344
2d21ac55 1345//*********************************************************************************
b0d623f7 1346// [public] deRegisterInterestedDriver
2d21ac55 1347//*********************************************************************************
1c79356b 1348
39236c6e 1349IOReturn IOService::deRegisterInterestedDriver( IOService * driver )
2d21ac55 1350{
fe8ab488 1351 IOPMinformee * item;
6d2010ae
A
1352 IOPMRequest * request;
1353 bool signal;
2d21ac55 1354
6d2010ae
A
1355 if (!driver)
1356 return kIOReturnBadArgument;
1357 if (!initialized || !fInterestedDrivers)
1358 return IOPMNotPowerManaged;
2d21ac55 1359
6d2010ae 1360 PM_LOCK();
3e170ce0
A
1361 if (fInsertInterestSet)
1362 {
1363 fInsertInterestSet->removeObject(driver);
1364 }
1365
1366 item = fInterestedDrivers->findItem(driver);
1367 if (!item)
1368 {
1369 PM_UNLOCK();
1370 return kIOReturnNotFound;
1371 }
1372
6d2010ae
A
1373 signal = (!fRemoveInterestSet && !fInsertInterestSet);
1374 if (fRemoveInterestSet == NULL)
1375 fRemoveInterestSet = OSSet::withCapacity(4);
1376 if (fRemoveInterestSet)
1377 {
1378 fRemoveInterestSet->setObject(driver);
3e170ce0 1379 if (item->active)
6d2010ae
A
1380 {
1381 item->active = false;
1382 waitForPMDriverCall( driver );
1383 }
1384 }
1385 PM_UNLOCK();
1c79356b 1386
6d2010ae
A
1387 if (signal)
1388 {
1389 request = acquirePMRequest( this, kIOPMRequestTypeInterestChanged );
1390 if (request)
1391 submitPMRequest( request );
1392 }
55e303ae 1393
6d2010ae 1394 return IOPMNoErr;
1c79356b
A
1395}
1396
1c79356b 1397//*********************************************************************************
2d21ac55 1398// [private] handleInterestChanged
1c79356b 1399//
2d21ac55 1400// Handle interest added or removed.
1c79356b 1401//*********************************************************************************
2d21ac55
A
1402
1403void IOService::handleInterestChanged( IOPMRequest * request )
1c79356b 1404{
fe8ab488
A
1405 IOService * driver;
1406 IOPMinformee * informee;
1407 IOPMinformeeList * list = fInterestedDrivers;
2d21ac55 1408
6d2010ae 1409 PM_LOCK();
2d21ac55 1410
6d2010ae
A
1411 if (fInsertInterestSet)
1412 {
1413 while ((driver = (IOService *) fInsertInterestSet->getAnyObject()))
1414 {
1415 if (list->findItem(driver) == NULL)
1416 {
1417 informee = list->appendNewInformee(driver);
1418 }
1419 fInsertInterestSet->removeObject(driver);
1420 }
1421 fInsertInterestSet->release();
1422 fInsertInterestSet = 0;
1423 }
1c79356b 1424
6d2010ae
A
1425 if (fRemoveInterestSet)
1426 {
1427 while ((driver = (IOService *) fRemoveInterestSet->getAnyObject()))
1428 {
1429 informee = list->findItem(driver);
1430 if (informee)
1431 {
1432 // Clean-up async interest acknowledgement
1433 if (fHeadNotePendingAcks && informee->timer)
1434 {
1435 informee->timer = 0;
1436 fHeadNotePendingAcks--;
1437 }
1438 list->removeFromList(driver);
1439 }
1440 fRemoveInterestSet->removeObject(driver);
1441 }
1442 fRemoveInterestSet->release();
1443 fRemoveInterestSet = 0;
1444 }
1c79356b 1445
6d2010ae 1446 PM_UNLOCK();
1c79356b
A
1447}
1448
1c79356b 1449//*********************************************************************************
b0d623f7 1450// [public] acknowledgePowerChange
1c79356b
A
1451//
1452// After we notified one of the interested drivers or a power-domain child
1453// of an impending change in power, it has called to say it is now
1454// prepared for the change. If this object is the last to
1455// acknowledge this change, we take whatever action we have been waiting
1456// for.
1457// That may include acknowledging to our parent. In this case, we do it
1458// last of all to insure that this doesn't cause the parent to call us some-
1459// where else and alter data we are relying on here (like the very existance
1460// of a "current change note".)
1461//*********************************************************************************
1462
39236c6e 1463IOReturn IOService::acknowledgePowerChange( IOService * whichObject )
1c79356b 1464{
fe8ab488 1465 IOPMRequest * request;
2d21ac55
A
1466
1467 if (!initialized)
fe8ab488
A
1468 return IOPMNotYetInitialized;
1469 if (!whichObject)
1470 return kIOReturnBadArgument;
2d21ac55 1471
fe8ab488
A
1472 request = acquirePMRequest( this, kIOPMRequestTypeAckPowerChange );
1473 if (!request)
1474 return kIOReturnNoMemory;
2d21ac55 1475
fe8ab488
A
1476 whichObject->retain();
1477 request->fArg0 = whichObject;
2d21ac55 1478
fe8ab488 1479 submitPMRequest( request );
2d21ac55
A
1480 return IOPMNoErr;
1481}
1482
1483//*********************************************************************************
1484// [private] handleAcknowledgePowerChange
1485//*********************************************************************************
1486
39236c6e 1487bool IOService::handleAcknowledgePowerChange( IOPMRequest * request )
2d21ac55 1488{
fe8ab488
A
1489 IOPMinformee * informee;
1490 unsigned long childPower = kIOPMUnknown;
1491 IOService * theChild;
1492 IOService * whichObject;
1493 bool all_acked = false;
2d21ac55 1494
fe8ab488
A
1495 PM_ASSERT_IN_GATE();
1496 whichObject = (IOService *) request->fArg0;
1497 assert(whichObject);
1c79356b 1498
55e303ae 1499 // one of our interested drivers?
fe8ab488 1500 informee = fInterestedDrivers->findItem( whichObject );
2d21ac55 1501 if ( informee == NULL )
55e303ae 1502 {
2d21ac55 1503 if ( !isChild(whichObject, gIOPowerPlane) )
55e303ae 1504 {
fe8ab488
A
1505 OUR_PMLog(kPMLogAcknowledgeErr1, 0, 0);
1506 goto no_err;
55e303ae 1507 } else {
2d21ac55 1508 OUR_PMLog(kPMLogChildAcknowledge, fHeadNotePendingAcks, 0);
55e303ae
A
1509 }
1510 } else {
2d21ac55 1511 OUR_PMLog(kPMLogDriverAcknowledge, fHeadNotePendingAcks, 0);
55e303ae 1512 }
2d21ac55
A
1513
1514 if ( fHeadNotePendingAcks != 0 )
55e303ae 1515 {
2d21ac55
A
1516 assert(fPowerStates != NULL);
1517
55e303ae 1518 // yes, make sure we're expecting acks
2d21ac55 1519 if ( informee != NULL )
55e303ae
A
1520 {
1521 // it's an interested driver
1522 // make sure we're expecting this ack
2d21ac55 1523 if ( informee->timer != 0 )
55e303ae 1524 {
2d21ac55
A
1525#if LOG_SETPOWER_TIMES
1526 if (informee->timer > 0)
55e303ae 1527 {
2d21ac55 1528 uint64_t nsec = computeTimeDeltaNS(&informee->startTime);
fe8ab488
A
1529 if (nsec > LOG_SETPOWER_TIMES) {
1530 getPMRootDomain()->pmStatsRecordApplicationResponse(
1531 gIOPMStatsDriverPSChangeSlow, informee->whatObject->getName(),
1532 fDriverCallReason, NS_TO_MS(nsec), 0, NULL, fHeadNotePowerState);
1533 }
55e303ae 1534 }
2d21ac55
A
1535#endif
1536 // mark it acked
1537 informee->timer = 0;
1538 // that's one fewer to worry about
1539 fHeadNotePendingAcks--;
55e303ae
A
1540 } else {
1541 // this driver has already acked
2d21ac55 1542 OUR_PMLog(kPMLogAcknowledgeErr2, 0, 0);
55e303ae
A
1543 }
1544 } else {
1545 // it's a child
1546 // make sure we're expecting this ack
2d21ac55 1547 if ( ((IOPowerConnection *)whichObject)->getAwaitingAck() )
55e303ae
A
1548 {
1549 // that's one fewer to worry about
2d21ac55 1550 fHeadNotePendingAcks--;
0b4e3aa0
A
1551 ((IOPowerConnection *)whichObject)->setAwaitingAck(false);
1552 theChild = (IOService *)whichObject->copyChildEntry(gIOPowerPlane);
2d21ac55 1553 if ( theChild )
55e303ae 1554 {
0b4e3aa0
A
1555 childPower = theChild->currentPowerConsumption();
1556 theChild->release();
1557 }
2d21ac55 1558 if ( childPower == kIOPMUnknown )
55e303ae 1559 {
b0d623f7 1560 fHeadNotePowerArrayEntry->staticPower = kIOPMUnknown;
55e303ae 1561 } else {
b0d623f7 1562 if (fHeadNotePowerArrayEntry->staticPower != kIOPMUnknown)
55e303ae 1563 {
b0d623f7 1564 fHeadNotePowerArrayEntry->staticPower += childPower;
0b4e3aa0
A
1565 }
1566 }
0b4e3aa0 1567 }
fe8ab488
A
1568 }
1569
1570 if ( fHeadNotePendingAcks == 0 ) {
1571 // yes, stop the timer
1572 stop_ack_timer();
1573 // and now we can continue
1574 all_acked = true;
1575 }
55e303ae 1576 } else {
fe8ab488 1577 OUR_PMLog(kPMLogAcknowledgeErr3, 0, 0); // not expecting anybody to ack
1c79356b 1578 }
2d21ac55
A
1579
1580no_err:
fe8ab488
A
1581 if (whichObject)
1582 whichObject->release();
2d21ac55
A
1583
1584 return all_acked;
1c79356b
A
1585}
1586
1587//*********************************************************************************
b0d623f7 1588// [public] acknowledgeSetPowerState
1c79356b
A
1589//
1590// After we instructed our controlling driver to change power states,
1591// it has called to say it has finished doing so.
1592// We continue to process the power state change.
1593//*********************************************************************************
1594
39236c6e 1595IOReturn IOService::acknowledgeSetPowerState( void )
1c79356b 1596{
fe8ab488 1597 IOPMRequest * request;
9bccf70c 1598
2d21ac55 1599 if (!initialized)
fe8ab488 1600 return IOPMNotYetInitialized;
91447636 1601
fe8ab488
A
1602 request = acquirePMRequest( this, kIOPMRequestTypeAckSetPowerState );
1603 if (!request)
1604 return kIOReturnNoMemory;
1c79356b 1605
fe8ab488
A
1606 submitPMRequest( request );
1607 return kIOReturnSuccess;
2d21ac55 1608}
1c79356b
A
1609
1610//*********************************************************************************
2d21ac55 1611// [private] adjustPowerState
1c79356b
A
1612//*********************************************************************************
1613
39236c6e 1614void IOService::adjustPowerState( uint32_t clamp )
1c79356b 1615{
fe8ab488
A
1616 PM_ASSERT_IN_GATE();
1617 computeDesiredState(clamp, false);
1618 if (fControllingDriver && fParentsKnowState && inPlane(gIOPowerPlane))
1619 {
6d2010ae
A
1620 IOPMPowerChangeFlags changeFlags = kIOPMSelfInitiated;
1621
bd504ef0 1622 // Indicate that children desires must be ignored, and do not ask
6d2010ae
A
1623 // apps for permission to drop power. This is used by root domain
1624 // for demand sleep.
1625
1626 if (getPMRequestType() == kIOPMRequestTypeRequestPowerStateOverride)
1627 changeFlags |= (kIOPMIgnoreChildren | kIOPMSkipAskPowerDown);
1628
fe8ab488
A
1629 startPowerChange(
1630 /* flags */ changeFlags,
1631 /* power state */ fDesiredPowerState,
1632 /* domain flags */ 0,
1633 /* connection */ 0,
1634 /* parent flags */ 0);
1635 }
b0d623f7
A
1636}
1637
1638//*********************************************************************************
1639// [public] synchronizePowerTree
1640//*********************************************************************************
1641
39236c6e 1642IOReturn IOService::synchronizePowerTree(
6d2010ae
A
1643 IOOptionBits options,
1644 IOService * notifyRoot )
b0d623f7 1645{
fe8ab488 1646 IOPMRequest * request_c = 0;
b0d623f7
A
1647 IOPMRequest * request_s;
1648
1649 if (this != getPMRootDomain())
1650 return kIOReturnBadArgument;
fe8ab488
A
1651 if (!initialized)
1652 return kIOPMNotYetInitialized;
b0d623f7 1653
39236c6e
A
1654 OUR_PMLog(kPMLogCSynchronizePowerTree, options, (notifyRoot != 0));
1655
6d2010ae
A
1656 if (notifyRoot)
1657 {
1658 IOPMRequest * nr;
b0d623f7 1659
6d2010ae
A
1660 // Cancels don't need to be synchronized.
1661 nr = acquirePMRequest(notifyRoot, kIOPMRequestTypeChildNotifyDelayCancel);
fe8ab488 1662 if (nr) submitPMRequest(nr);
6d2010ae
A
1663 nr = acquirePMRequest(getPMRootDomain(), kIOPMRequestTypeChildNotifyDelayCancel);
1664 if (nr) submitPMRequest(nr);
1665 }
b0d623f7 1666
6d2010ae
A
1667 request_s = acquirePMRequest( this, kIOPMRequestTypeSynchronizePowerTree );
1668 if (!request_s)
1669 goto error_no_memory;
b0d623f7 1670
6d2010ae
A
1671 if (options & kIOPMSyncCancelPowerDown)
1672 request_c = acquirePMRequest( this, kIOPMRequestTypeIdleCancel );
1673 if (request_c)
1674 {
1675 request_c->attachNextRequest( request_s );
1676 submitPMRequest(request_c);
1677 }
fe8ab488 1678
6d2010ae 1679 request_s->fArg0 = (void *)(uintptr_t) options;
b0d623f7
A
1680 submitPMRequest(request_s);
1681
1682 return kIOReturnSuccess;
1683
1684error_no_memory:
fe8ab488
A
1685 if (request_c) releasePMRequest(request_c);
1686 if (request_s) releasePMRequest(request_s);
b0d623f7
A
1687 return kIOReturnNoMemory;
1688}
1689
1690//*********************************************************************************
1691// [private] handleSynchronizePowerTree
1692//*********************************************************************************
1693
39236c6e 1694void IOService::handleSynchronizePowerTree( IOPMRequest * request )
b0d623f7 1695{
fe8ab488
A
1696 PM_ASSERT_IN_GATE();
1697 if (fControllingDriver && fParentsKnowState && inPlane(gIOPowerPlane) &&
39236c6e 1698 (fCurrentPowerState == fHighestPowerState))
fe8ab488 1699 {
6d2010ae
A
1700 IOOptionBits options = (uintptr_t) request->fArg0;
1701
fe8ab488
A
1702 startPowerChange(
1703 /* flags */ kIOPMSelfInitiated | kIOPMSynchronize |
6d2010ae 1704 (options & kIOPMSyncNoChildNotify),
fe8ab488
A
1705 /* power state */ fCurrentPowerState,
1706 /* domain flags */ 0,
1707 /* connection */ 0,
1708 /* parent flags */ 0);
1709 }
1c79356b
A
1710}
1711
b0d623f7 1712#ifndef __LP64__
1c79356b 1713//*********************************************************************************
b0d623f7 1714// [deprecated] powerDomainWillChangeTo
1c79356b
A
1715//
1716// Called by the power-hierarchy parent notifying of a new power state
1717// in the power domain.
1718// We enqueue a parent power-change to our queue of power changes.
1719// This may or may not cause us to change power, depending on what
1720// kind of change is occuring in the domain.
1721//*********************************************************************************
1722
39236c6e 1723IOReturn IOService::powerDomainWillChangeTo(
fe8ab488
A
1724 IOPMPowerFlags newPowerFlags,
1725 IOPowerConnection * whichParent )
1c79356b 1726{
fe8ab488
A
1727 assert(false);
1728 return kIOReturnUnsupported;
2d21ac55 1729}
b0d623f7 1730#endif /* !__LP64__ */
1c79356b 1731
2d21ac55
A
1732//*********************************************************************************
1733// [private] handlePowerDomainWillChangeTo
1734//*********************************************************************************
1c79356b 1735
39236c6e 1736void IOService::handlePowerDomainWillChangeTo( IOPMRequest * request )
2d21ac55 1737{
fe8ab488
A
1738 IOPMPowerFlags parentPowerFlags = (IOPMPowerFlags) request->fArg0;
1739 IOPowerConnection * whichParent = (IOPowerConnection *) request->fArg1;
6d2010ae
A
1740 IOPMPowerChangeFlags parentChangeFlags = (IOPMPowerChangeFlags)(uintptr_t) request->fArg2;
1741 IOPMPowerChangeFlags myChangeFlags;
fe8ab488
A
1742 OSIterator * iter;
1743 OSObject * next;
1744 IOPowerConnection * connection;
bd504ef0 1745 IOPMPowerStateIndex maxPowerState;
fe8ab488
A
1746 IOPMPowerFlags combinedPowerFlags;
1747 bool savedParentsKnowState;
1748 IOReturn result = IOPMAckImplied;
2d21ac55 1749
fe8ab488 1750 PM_ASSERT_IN_GATE();
b0d623f7 1751 OUR_PMLog(kPMLogWillChange, parentPowerFlags, 0);
2d21ac55 1752
fe8ab488
A
1753 if (!inPlane(gIOPowerPlane) || !whichParent || !whichParent->getAwaitingAck())
1754 {
1755 PM_LOG("%s::%s not in power tree\n", getName(), __FUNCTION__);
cf7d32b8 1756 goto exit_no_ack;
fe8ab488 1757 }
1c79356b 1758
fe8ab488 1759 savedParentsKnowState = fParentsKnowState;
0b4e3aa0 1760
b0d623f7
A
1761 // Combine parents' output power flags.
1762
fe8ab488 1763 combinedPowerFlags = 0;
1c79356b 1764
2d21ac55
A
1765 iter = getParentIterator(gIOPowerPlane);
1766 if ( iter )
55e303ae 1767 {
2d21ac55 1768 while ( (next = iter->getNextObject()) )
55e303ae 1769 {
2d21ac55 1770 if ( (connection = OSDynamicCast(IOPowerConnection, next)) )
55e303ae 1771 {
2d21ac55 1772 if ( connection == whichParent )
b0d623f7 1773 combinedPowerFlags |= parentPowerFlags;
2d21ac55 1774 else
1c79356b 1775 combinedPowerFlags |= connection->parentCurrentPowerFlags();
1c79356b
A
1776 }
1777 }
1778 iter->release();
1779 }
2d21ac55 1780
b0d623f7
A
1781 // If our initial change has yet to occur, then defer the power change
1782 // until after the power domain has completed its power transition.
1783
6d2010ae 1784 if ( fControllingDriver && !fInitialPowerChange )
55e303ae 1785 {
fe8ab488
A
1786 maxPowerState = fControllingDriver->maxCapabilityForDomainState(
1787 combinedPowerFlags);
2d21ac55 1788
3e170ce0
A
1789 if (parentChangeFlags & kIOPMDomainPowerDrop)
1790 {
1791 // fMaxPowerState set a limit on self-initiated power changes.
1792 // Update it before a parent power drop.
1793 fMaxPowerState = maxPowerState;
1794 }
1795
bd504ef0
A
1796 // Use kIOPMSynchronize below instead of kIOPMRootBroadcastFlags
1797 // to avoid propagating the root change flags if any service must
1798 // change power state due to root's will-change notification.
1799 // Root does not change power state for kIOPMSynchronize.
fe8ab488 1800
b0d623f7
A
1801 myChangeFlags = kIOPMParentInitiated | kIOPMDomainWillChange |
1802 (parentChangeFlags & kIOPMSynchronize);
1803
fe8ab488
A
1804 result = startPowerChange(
1805 /* flags */ myChangeFlags,
1806 /* power state */ maxPowerState,
1807 /* domain flags */ combinedPowerFlags,
1808 /* connection */ whichParent,
1809 /* parent flags */ parentPowerFlags);
1810 }
1811
1812 // If parent is dropping power, immediately update the parent's
1813 // capability flags. Any future merging of parent(s) combined
1814 // power flags should account for this power drop.
1815
1816 if (parentChangeFlags & kIOPMDomainPowerDrop)
1817 {
1818 setParentInfo(parentPowerFlags, whichParent, true);
1819 }
1820
1821 // Parent is expecting an ACK from us. If we did not embark on a state
1822 // transition, i.e. startPowerChange() returned IOPMAckImplied. We are
1823 // still required to issue an ACK to our parent.
1824
1825 if (IOPMAckImplied == result)
1826 {
1827 IOService * parent;
1828 parent = (IOService *) whichParent->copyParentEntry(gIOPowerPlane);
1829 assert(parent);
1830 if ( parent )
1831 {
1832 parent->acknowledgePowerChange( whichParent );
1833 parent->release();
1834 }
1835 }
2d21ac55 1836
cf7d32b8
A
1837exit_no_ack:
1838 // Drop the retain from notifyChild().
1839 if (whichParent) whichParent->release();
2d21ac55 1840}
1c79356b 1841
b0d623f7 1842#ifndef __LP64__
1c79356b 1843//*********************************************************************************
b0d623f7 1844// [deprecated] powerDomainDidChangeTo
1c79356b
A
1845//
1846// Called by the power-hierarchy parent after the power state of the power domain
1847// has settled at a new level.
1848// We enqueue a parent power-change to our queue of power changes.
1849// This may or may not cause us to change power, depending on what
1850// kind of change is occuring in the domain.
1851//*********************************************************************************
1852
39236c6e 1853IOReturn IOService::powerDomainDidChangeTo(
fe8ab488
A
1854 IOPMPowerFlags newPowerFlags,
1855 IOPowerConnection * whichParent )
1c79356b 1856{
fe8ab488
A
1857 assert(false);
1858 return kIOReturnUnsupported;
2d21ac55 1859}
b0d623f7 1860#endif /* !__LP64__ */
1c79356b 1861
2d21ac55
A
1862//*********************************************************************************
1863// [private] handlePowerDomainDidChangeTo
1864//*********************************************************************************
1c79356b 1865
39236c6e 1866void IOService::handlePowerDomainDidChangeTo( IOPMRequest * request )
2d21ac55 1867{
fe8ab488
A
1868 IOPMPowerFlags parentPowerFlags = (IOPMPowerFlags) request->fArg0;
1869 IOPowerConnection * whichParent = (IOPowerConnection *) request->fArg1;
6d2010ae
A
1870 IOPMPowerChangeFlags parentChangeFlags = (IOPMPowerChangeFlags)(uintptr_t) request->fArg2;
1871 IOPMPowerChangeFlags myChangeFlags;
bd504ef0 1872 IOPMPowerStateIndex maxPowerState;
39236c6e 1873 IOPMPowerStateIndex initialDesire = kPowerStateZero;
bd504ef0
A
1874 bool computeDesire = false;
1875 bool desireChanged = false;
fe8ab488
A
1876 bool savedParentsKnowState;
1877 IOReturn result = IOPMAckImplied;
2d21ac55 1878
fe8ab488 1879 PM_ASSERT_IN_GATE();
b0d623f7 1880 OUR_PMLog(kPMLogDidChange, parentPowerFlags, 0);
2d21ac55 1881
fe8ab488
A
1882 if (!inPlane(gIOPowerPlane) || !whichParent || !whichParent->getAwaitingAck())
1883 {
1884 PM_LOG("%s::%s not in power tree\n", getName(), __FUNCTION__);
cf7d32b8 1885 goto exit_no_ack;
fe8ab488 1886 }
0b4e3aa0 1887
fe8ab488 1888 savedParentsKnowState = fParentsKnowState;
0b4e3aa0 1889
b0d623f7 1890 setParentInfo(parentPowerFlags, whichParent, true);
2d21ac55
A
1891
1892 if ( fControllingDriver )
fe8ab488
A
1893 {
1894 maxPowerState = fControllingDriver->maxCapabilityForDomainState(
1895 fParentsCurrentPowerFlags);
2d21ac55 1896
3e170ce0
A
1897 if ((parentChangeFlags & kIOPMDomainPowerDrop) == 0)
1898 {
1899 // fMaxPowerState set a limit on self-initiated power changes.
1900 // Update it after a parent power rise.
1901 fMaxPowerState = maxPowerState;
1902 }
1903
6d2010ae 1904 if (fInitialPowerChange)
b0d623f7 1905 {
bd504ef0 1906 computeDesire = true;
b0d623f7 1907 initialDesire = fControllingDriver->initialPowerStateForDomainState(
bd504ef0 1908 fParentsCurrentPowerFlags);
b0d623f7 1909 }
bd504ef0 1910 else if (parentChangeFlags & kIOPMRootChangeUp)
db609669 1911 {
bd504ef0
A
1912 if (fAdvisoryTickleUsed)
1913 {
1914 // On system wake, re-compute the desired power state since
1915 // gIOPMAdvisoryTickleEnabled will change for a full wake,
1916 // which is an input to computeDesiredState(). This is not
1917 // necessary for a dark wake because powerChangeDone() will
1918 // handle the dark to full wake case, but it does no harm.
1919
1920 desireChanged = true;
1921 }
1922
1923 if (fResetPowerStateOnWake)
1924 {
1925 // Query the driver for the desired power state on system wake.
1926 // Default implementation returns the lowest power state.
1927
1928 IOPMPowerStateIndex wakePowerState =
1929 fControllingDriver->initialPowerStateForDomainState(
1930 kIOPMRootDomainState | kIOPMPowerOn );
1931
1932 // fDesiredPowerState was adjusted before going to sleep
1933 // with fDeviceDesire at min.
1934
39236c6e 1935 if (StateOrder(wakePowerState) > StateOrder(fDesiredPowerState))
bd504ef0
A
1936 {
1937 // Must schedule a power adjustment if we changed the
1938 // device desire. That will update the desired domain
1939 // power on the parent power connection and ping the
1940 // power parent if necessary.
1941
1942 updatePowerClient(gIOPMPowerClientDevice, wakePowerState);
1943 desireChanged = true;
1944 }
1945 }
db609669 1946 }
b0d623f7 1947
bd504ef0
A
1948 if (computeDesire || desireChanged)
1949 computeDesiredState(initialDesire, false);
1950
1951 // Absorb and propagate parent's broadcast flags
b0d623f7 1952 myChangeFlags = kIOPMParentInitiated | kIOPMDomainDidChange |
bd504ef0 1953 (parentChangeFlags & kIOPMRootBroadcastFlags);
b0d623f7 1954
fe8ab488
A
1955 result = startPowerChange(
1956 /* flags */ myChangeFlags,
1957 /* power state */ maxPowerState,
1958 /* domain flags */ fParentsCurrentPowerFlags,
1959 /* connection */ whichParent,
1960 /* parent flags */ 0);
1961 }
1962
1963 // Parent is expecting an ACK from us. If we did not embark on a state
1964 // transition, i.e. startPowerChange() returned IOPMAckImplied. We are
1965 // still required to issue an ACK to our parent.
1966
1967 if (IOPMAckImplied == result)
1968 {
1969 IOService * parent;
1970 parent = (IOService *) whichParent->copyParentEntry(gIOPowerPlane);
1971 assert(parent);
1972 if ( parent )
1973 {
1974 parent->acknowledgePowerChange( whichParent );
1975 parent->release();
1976 }
1977 }
1978
1979 // If the parent registers its power driver late, then this is the
1980 // first opportunity to tell our parent about our desire. Or if the
bd504ef0 1981 // child's desire changed during a parent change notify.
2d21ac55 1982
fe8ab488
A
1983 if (fControllingDriver &&
1984 ((!savedParentsKnowState && fParentsKnowState) || desireChanged))
1985 {
1986 PM_LOG1("%s::powerDomainDidChangeTo parentsKnowState %d\n",
1987 getName(), fParentsKnowState);
1988 requestDomainPower( fDesiredPowerState );
1989 }
cf7d32b8
A
1990
1991exit_no_ack:
1992 // Drop the retain from notifyChild().
1993 if (whichParent) whichParent->release();
2d21ac55 1994}
0b4e3aa0
A
1995
1996//*********************************************************************************
2d21ac55 1997// [private] setParentInfo
0b4e3aa0
A
1998//
1999// Set our connection data for one specific parent, and then combine all the parent
2000// data together.
2001//*********************************************************************************
fe8ab488 2002
39236c6e 2003void IOService::setParentInfo(
fe8ab488
A
2004 IOPMPowerFlags newPowerFlags,
2005 IOPowerConnection * whichParent,
2006 bool knowsState )
0b4e3aa0 2007{
fe8ab488
A
2008 OSIterator * iter;
2009 OSObject * next;
2010 IOPowerConnection * conn;
1c79356b 2011
fe8ab488 2012 PM_ASSERT_IN_GATE();
2d21ac55
A
2013
2014 // set our connection data
2015 whichParent->setParentCurrentPowerFlags(newPowerFlags);
2016 whichParent->setParentKnowsState(knowsState);
fe8ab488 2017
55e303ae 2018 // recompute our parent info
2d21ac55
A
2019 fParentsCurrentPowerFlags = 0;
2020 fParentsKnowState = true;
1c79356b
A
2021
2022 iter = getParentIterator(gIOPowerPlane);
2d21ac55 2023 if ( iter )
55e303ae 2024 {
2d21ac55 2025 while ( (next = iter->getNextObject()) )
55e303ae 2026 {
2d21ac55 2027 if ( (conn = OSDynamicCast(IOPowerConnection, next)) )
55e303ae 2028 {
2d21ac55
A
2029 fParentsKnowState &= conn->parentKnowsState();
2030 fParentsCurrentPowerFlags |= conn->parentCurrentPowerFlags();
1c79356b
A
2031 }
2032 }
2033 iter->release();
2034 }
1c79356b
A
2035}
2036
316670eb
A
2037//******************************************************************************
2038// [private] trackSystemSleepPreventers
2039//******************************************************************************
90556fb8 2040
316670eb
A
2041void IOService::trackSystemSleepPreventers(
2042 IOPMPowerStateIndex oldPowerState,
2043 IOPMPowerStateIndex newPowerState,
2044 IOPMPowerChangeFlags changeFlags __unused )
90556fb8 2045{
316670eb 2046 IOPMPowerFlags oldCapability, newCapability;
2d21ac55 2047
316670eb
A
2048 oldCapability = fPowerStates[oldPowerState].capabilityFlags &
2049 (kIOPMPreventIdleSleep | kIOPMPreventSystemSleep);
2050 newCapability = fPowerStates[newPowerState].capabilityFlags &
2051 (kIOPMPreventIdleSleep | kIOPMPreventSystemSleep);
b0d623f7 2052
316670eb
A
2053 if (fHeadNoteChangeFlags & kIOPMInitialPowerChange)
2054 oldCapability = 0;
2055 if (oldCapability == newCapability)
2056 return;
90556fb8 2057
316670eb 2058 if ((oldCapability ^ newCapability) & kIOPMPreventIdleSleep)
90556fb8 2059 {
fe8ab488
A
2060 bool enablePrevention = ((oldCapability & kIOPMPreventIdleSleep) == 0);
2061 bool idleCancelAllowed = getPMRootDomain()->updatePreventIdleSleepList(
2062 this, enablePrevention);
316670eb 2063#if SUPPORT_IDLE_CANCEL
fe8ab488 2064 if (idleCancelAllowed && enablePrevention)
90556fb8 2065 {
316670eb 2066 IOPMRequest * cancelRequest;
2d21ac55 2067
bd504ef0 2068 cancelRequest = acquirePMRequest( getPMRootDomain(), kIOPMRequestTypeIdleCancel );
316670eb
A
2069 if (cancelRequest)
2070 {
bd504ef0 2071 submitPMRequest( cancelRequest );
90556fb8
A
2072 }
2073 }
316670eb 2074#endif
316670eb
A
2075 }
2076
2077 if ((oldCapability ^ newCapability) & kIOPMPreventSystemSleep)
2078 {
316670eb
A
2079 getPMRootDomain()->updatePreventSystemSleepList(this,
2080 ((oldCapability & kIOPMPreventSystemSleep) == 0));
90556fb8 2081 }
90556fb8
A
2082}
2083
1c79356b 2084//*********************************************************************************
b0d623f7 2085// [public] requestPowerDomainState
1c79356b 2086//
7e4a7d39 2087// Called on a power parent when a child's power requirement changes.
1c79356b 2088//*********************************************************************************
2d21ac55 2089
7e4a7d39
A
2090IOReturn IOService::requestPowerDomainState(
2091 IOPMPowerFlags childRequestPowerFlags,
2092 IOPowerConnection * childConnection,
fe8ab488 2093 unsigned long specification )
1c79356b 2094{
39236c6e 2095 IOPMPowerStateIndex order, powerState;
fe8ab488 2096 IOPMPowerFlags outputPowerFlags;
7e4a7d39 2097 IOService * child;
fe8ab488 2098 IOPMRequest * subRequest;
7e4a7d39 2099 bool adjustPower = false;
2d21ac55
A
2100
2101 if (!initialized)
fe8ab488 2102 return IOPMNotYetInitialized;
2d21ac55 2103
fe8ab488
A
2104 if (gIOPMWorkLoop->onThread() == false)
2105 {
2106 PM_LOG("%s::requestPowerDomainState\n", getName());
2107 return kIOReturnSuccess;
2108 }
1c79356b 2109
7e4a7d39 2110 OUR_PMLog(kPMLogRequestDomain, childRequestPowerFlags, specification);
1c79356b 2111
fe8ab488
A
2112 if (!isChild(childConnection, gIOPowerPlane))
2113 return kIOReturnNotAttached;
2d21ac55 2114
7e4a7d39 2115 if (!fControllingDriver || !fNumberOfPowerStates)
6d2010ae 2116 return kIOReturnNotReady;
2d21ac55 2117
fe8ab488
A
2118 child = (IOService *) childConnection->getChildEntry(gIOPowerPlane);
2119 assert(child);
1c79356b 2120
39236c6e
A
2121 // Remove flags from child request which we can't possibly supply
2122 childRequestPowerFlags &= fMergedOutputPowerFlags;
2123
7e4a7d39 2124 // Merge in the power flags contributed by this power parent
fe8ab488 2125 // at its current or impending power state.
1c79356b 2126
6d2010ae 2127 outputPowerFlags = fPowerStates[fCurrentPowerState].outputPowerFlags;
fe8ab488
A
2128 if (fMachineState != kIOPM_Finished)
2129 {
2130 if (IS_POWER_DROP && !IS_ROOT_DOMAIN)
2131 {
39236c6e
A
2132 // Use the lower power state when dropping power.
2133 // Must be careful since a power drop can be cancelled
2134 // from the following states:
2135 // - kIOPM_OurChangeTellClientsPowerDown
2136 // - kIOPM_OurChangeTellPriorityClientsPowerDown
2137 //
2138 // The child must not wait for this parent to raise power
2139 // if the power drop was cancelled. The solution is to cancel
2140 // the power drop if possible, then schedule an adjustment to
2141 // re-evaluate the parent's power state.
2142 //
2143 // Root domain is excluded to avoid idle sleep issues. And allow
2144 // root domain children to pop up when system is going to sleep.
2145
2146 if ((fMachineState == kIOPM_OurChangeTellClientsPowerDown) ||
2147 (fMachineState == kIOPM_OurChangeTellPriorityClientsPowerDown))
2148 {
2149 fDoNotPowerDown = true; // cancel power drop
2150 adjustPower = true; // schedule an adjustment
2151 PM_LOG1("%s: power drop cancelled in state %u by %s\n",
2152 getName(), fMachineState, child->getName());
2153 }
fe8ab488
A
2154 else
2155 {
2156 // Beyond cancellation point, report the impending state.
2157 outputPowerFlags =
2158 fPowerStates[fHeadNotePowerState].outputPowerFlags;
2159 }
2160 }
2161 else if (IS_POWER_RISE)
2162 {
2163 // When raising power, must report the output power flags from
2164 // child's perspective. A child power request may arrive while
2165 // parent is transitioning upwards. If a request arrives after
2166 // setParentInfo() has already recorded the output power flags
2167 // for the next power state, then using the power supplied by
2168 // fCurrentPowerState is incorrect, and might cause the child
2169 // to wait when it should not.
2170
2171 outputPowerFlags = childConnection->parentCurrentPowerFlags();
2172 }
7e4a7d39
A
2173 }
2174 child->fHeadNoteDomainTargetFlags |= outputPowerFlags;
1c79356b 2175
7e4a7d39 2176 // Map child's requested power flags to one of our power state.
1c79356b 2177
39236c6e 2178 for (order = 0; order < fNumberOfPowerStates; order++)
7e4a7d39 2179 {
39236c6e
A
2180 powerState = fPowerStates[order].stateOrderToIndex;
2181 if ((fPowerStates[powerState].outputPowerFlags & childRequestPowerFlags)
2182 == childRequestPowerFlags)
7e4a7d39
A
2183 break;
2184 }
39236c6e 2185 if (order >= fNumberOfPowerStates)
7e4a7d39 2186 {
39236c6e 2187 powerState = kPowerStateZero;
1c79356b
A
2188 }
2189
7e4a7d39
A
2190 // Conditions that warrants a power adjustment on this parent.
2191 // Adjust power will also propagate any changes to the child's
2192 // prevent idle/sleep flags towards the root domain.
2193
2194 if (!childConnection->childHasRequestedPower() ||
39236c6e 2195 (powerState != childConnection->getDesiredDomainState()))
7e4a7d39
A
2196 adjustPower = true;
2197
2198#if ENABLE_DEBUG_LOGS
2199 if (adjustPower)
2200 {
6d2010ae 2201 PM_LOG("requestPowerDomainState[%s]: %s, init %d, %u->%u\n",
7e4a7d39
A
2202 getName(), child->getName(),
2203 !childConnection->childHasRequestedPower(),
2204 (uint32_t) childConnection->getDesiredDomainState(),
39236c6e 2205 (uint32_t) powerState);
7e4a7d39
A
2206 }
2207#endif
0b4e3aa0 2208
fe8ab488
A
2209 // Record the child's desires on the connection.
2210 childConnection->setChildHasRequestedPower();
2211 childConnection->setDesiredDomainState( powerState );
2d21ac55 2212
fe8ab488
A
2213 // Schedule a request to re-evaluate all children desires and
2214 // adjust power state. Submit a request if one wasn't pending,
2215 // or if the current request is part of a call tree.
2d21ac55 2216
6d2010ae 2217 if (adjustPower && !fDeviceOverrideEnabled &&
7e4a7d39 2218 (!fAdjustPowerScheduled || gIOPMRequest->getRootRequest()))
b0d623f7 2219 {
fe8ab488 2220 subRequest = acquirePMRequest(
7e4a7d39 2221 this, kIOPMRequestTypeAdjustPowerState, gIOPMRequest );
fe8ab488
A
2222 if (subRequest)
2223 {
2224 submitPMRequest( subRequest );
2225 fAdjustPowerScheduled = true;
2226 }
7e4a7d39
A
2227 }
2228
7e4a7d39 2229 return kIOReturnSuccess;
2d21ac55 2230}
1c79356b
A
2231
2232//*********************************************************************************
b0d623f7 2233// [public] temporaryPowerClampOn
1c79356b
A
2234//
2235// A power domain wants to clamp its power on till it has children which
2236// will thendetermine the power domain state.
2237//
2238// We enter the highest state until addPowerChild is called.
2239//*********************************************************************************
2240
39236c6e 2241IOReturn IOService::temporaryPowerClampOn( void )
1c79356b 2242{
b0d623f7 2243 return requestPowerState( gIOPMPowerClientChildProxy, kIOPMPowerStateMax );
1c79356b
A
2244}
2245
1c79356b 2246//*********************************************************************************
b0d623f7 2247// [public] makeUsable
1c79356b
A
2248//
2249// Some client of our device is asking that we become usable. Although
2250// this has not come from a subclassed device object, treat it exactly
2251// as if it had. In this way, subsequent requests for lower power from
2252// a subclassed device object will pre-empt this request.
2253//
2254// We treat this as a subclass object request to switch to the
2255// highest power state.
2256//*********************************************************************************
2257
39236c6e 2258IOReturn IOService::makeUsable( void )
1c79356b 2259{
2d21ac55 2260 OUR_PMLog(kPMLogMakeUsable, 0, 0);
b0d623f7
A
2261 return requestPowerState( gIOPMPowerClientDevice, kIOPMPowerStateMax );
2262}
2d21ac55 2263
b0d623f7
A
2264//*********************************************************************************
2265// [public] currentCapability
2266//*********************************************************************************
2d21ac55 2267
39236c6e 2268IOPMPowerFlags IOService::currentCapability( void )
b0d623f7 2269{
fe8ab488
A
2270 if (!initialized)
2271 return IOPMNotPowerManaged;
b0d623f7
A
2272
2273 return fCurrentCapabilityFlags;
1c79356b
A
2274}
2275
2d21ac55 2276//*********************************************************************************
b0d623f7 2277// [public] changePowerStateTo
0c530ab8 2278//
b0d623f7
A
2279// Called by our power-controlling driver to change power state. The new desired
2280// power state is computed and compared against the current power state. If those
2281// power states differ, then a power state change is initiated.
2d21ac55 2282//*********************************************************************************
0c530ab8 2283
39236c6e 2284IOReturn IOService::changePowerStateTo( unsigned long ordinal )
0c530ab8 2285{
b0d623f7
A
2286 OUR_PMLog(kPMLogChangeStateTo, ordinal, 0);
2287 return requestPowerState( gIOPMPowerClientDriver, ordinal );
0c530ab8
A
2288}
2289
1c79356b 2290//*********************************************************************************
b0d623f7
A
2291// [protected] changePowerStateToPriv
2292//
2293// Called by our driver subclass to change power state. The new desired power
2294// state is computed and compared against the current power state. If those
2295// power states differ, then a power state change is initiated.
1c79356b
A
2296//*********************************************************************************
2297
39236c6e 2298IOReturn IOService::changePowerStateToPriv( unsigned long ordinal )
1c79356b 2299{
b0d623f7
A
2300 OUR_PMLog(kPMLogChangeStateToPriv, ordinal, 0);
2301 return requestPowerState( gIOPMPowerClientDevice, ordinal );
2d21ac55 2302}
1c79356b
A
2303
2304//*********************************************************************************
39236c6e 2305// [public] changePowerStateWithOverrideTo
1c79356b 2306//
b0d623f7
A
2307// Called by our driver subclass to change power state. The new desired power
2308// state is computed and compared against the current power state. If those
2309// power states differ, then a power state change is initiated.
2310// Override enforced - Children and Driver desires are ignored.
1c79356b
A
2311//*********************************************************************************
2312
39236c6e
A
2313IOReturn IOService::changePowerStateWithOverrideTo( IOPMPowerStateIndex ordinal,
2314 IOPMRequestTag tag )
1c79356b 2315{
fe8ab488 2316 IOPMRequest * request;
1c79356b 2317
fe8ab488
A
2318 if (!initialized)
2319 return kIOPMNotYetInitialized;
2d21ac55 2320
b0d623f7 2321 OUR_PMLog(kPMLogChangeStateToPriv, ordinal, 0);
2d21ac55 2322
fe8ab488
A
2323 request = acquirePMRequest( this, kIOPMRequestTypeRequestPowerStateOverride );
2324 if (!request)
2325 return kIOReturnNoMemory;
2d21ac55 2326
b0d623f7 2327 gIOPMPowerClientDevice->retain();
39236c6e 2328 request->fRequestTag = tag;
b0d623f7
A
2329 request->fArg0 = (void *) ordinal;
2330 request->fArg1 = (void *) gIOPMPowerClientDevice;
2331 request->fArg2 = 0;
2332#if NOT_READY
2333 if (action)
2334 request->installCompletionAction( action, target, param );
2335#endif
1c79356b 2336
fe8ab488
A
2337 // Prevent needless downwards power transitions by clamping power
2338 // until the scheduled request is executed.
2d21ac55 2339
fe8ab488
A
2340 if (gIOPMWorkLoop->inGate() && (ordinal < fNumberOfPowerStates))
2341 {
2342 fTempClampPowerState = StateMax(fTempClampPowerState, ordinal);
2343 fTempClampCount++;
2344 fOverrideMaxPowerState = ordinal;
2345 request->fArg2 = (void *) (uintptr_t) true;
2346 }
2d21ac55 2347
fe8ab488 2348 submitPMRequest( request );
1c79356b
A
2349 return IOPMNoErr;
2350}
2351
39236c6e
A
2352//*********************************************************************************
2353// [public] changePowerStateForRootDomain
2354//
2355// Adjust the root domain's power desire on the target
2356//*********************************************************************************
2357
2358IOReturn IOService::changePowerStateForRootDomain( IOPMPowerStateIndex ordinal )
2359{
2360 OUR_PMLog(kPMLogChangeStateForRootDomain, ordinal, 0);
2361 return requestPowerState( gIOPMPowerClientRootDomain, ordinal );
2362}
2363
3e170ce0
A
2364//*********************************************************************************
2365// [public for PMRD] quiescePowerTree
2366//
2367// For root domain to issue a request to quiesce the power tree.
2368// Supplied callback invoked upon completion.
2369//*********************************************************************************
2370
2371IOReturn IOService::quiescePowerTree(
2372 void * target, IOPMCompletionAction action, void * param )
2373{
2374 IOPMRequest * request;
2375
2376 if (!initialized)
2377 return kIOPMNotYetInitialized;
2378 if (!target || !action)
2379 return kIOReturnBadArgument;
2380
2381 OUR_PMLog(kPMLogQuiescePowerTree, 0, 0);
2382
2383 // Target the root node instead of root domain. This is to avoid blocking
2384 // the quiesce request behind an existing root domain request in the work
2385 // queue. Root parent and root domain requests in the work queue must not
2386 // block the completion of the quiesce request.
2387
2388 request = acquirePMRequest(gIOPMRootNode, kIOPMRequestTypeQuiescePowerTree);
2389 if (!request)
2390 return kIOReturnNoMemory;
2391
2392 request->installCompletionAction(target, action, param);
2393
2394 // Submit through the normal request flow. This will make sure any request
2395 // already in the request queue will get pushed over to the work queue for
2396 // execution. Any request submitted after this request may not be serviced.
2397
2398 submitPMRequest( request );
2399 return kIOReturnSuccess;
2400}
2401
1c79356b 2402//*********************************************************************************
b0d623f7 2403// [private] requestPowerState
1c79356b
A
2404//*********************************************************************************
2405
39236c6e 2406IOReturn IOService::requestPowerState(
b0d623f7
A
2407 const OSSymbol * client,
2408 uint32_t state )
1c79356b 2409{
fe8ab488 2410 IOPMRequest * request;
1c79356b 2411
b0d623f7
A
2412 if (!client)
2413 return kIOReturnBadArgument;
fe8ab488
A
2414 if (!initialized)
2415 return kIOPMNotYetInitialized;
2d21ac55 2416
fe8ab488
A
2417 request = acquirePMRequest( this, kIOPMRequestTypeRequestPowerState );
2418 if (!request)
2419 return kIOReturnNoMemory;
2d21ac55 2420
b0d623f7 2421 client->retain();
39236c6e
A
2422 request->fArg0 = (void *)(uintptr_t) state;
2423 request->fArg1 = (void *) client;
b0d623f7
A
2424 request->fArg2 = 0;
2425#if NOT_READY
2426 if (action)
2427 request->installCompletionAction( action, target, param );
2428#endif
2d21ac55 2429
fe8ab488
A
2430 // Prevent needless downwards power transitions by clamping power
2431 // until the scheduled request is executed.
2d21ac55 2432
fe8ab488
A
2433 if (gIOPMWorkLoop->inGate() && (state < fNumberOfPowerStates))
2434 {
2435 fTempClampPowerState = StateMax(fTempClampPowerState, state);
2436 fTempClampCount++;
2437 request->fArg2 = (void *) (uintptr_t) true;
2438 }
1c79356b 2439
fe8ab488 2440 submitPMRequest( request );
1c79356b
A
2441 return IOPMNoErr;
2442}
2443
2d21ac55 2444//*********************************************************************************
b0d623f7 2445// [private] handleRequestPowerState
2d21ac55
A
2446//*********************************************************************************
2447
39236c6e 2448void IOService::handleRequestPowerState( IOPMRequest * request )
2d21ac55 2449{
b0d623f7
A
2450 const OSSymbol * client = (const OSSymbol *) request->fArg1;
2451 uint32_t state = (uint32_t)(uintptr_t) request->fArg0;
2d21ac55 2452
fe8ab488
A
2453 PM_ASSERT_IN_GATE();
2454 if (request->fArg2)
2455 {
2456 assert(fTempClampCount != 0);
2457 if (fTempClampCount) fTempClampCount--;
2458 if (!fTempClampCount) fTempClampPowerState = kPowerStateZero;
2459 }
2d21ac55 2460
fe8ab488
A
2461 if (fNumberOfPowerStates && (state >= fNumberOfPowerStates))
2462 state = fHighestPowerState;
b0d623f7 2463
6d2010ae
A
2464 // The power suppression due to changePowerStateWithOverrideTo() expires
2465 // upon the next "device" power request - changePowerStateToPriv().
b0d623f7
A
2466
2467 if ((getPMRequestType() != kIOPMRequestTypeRequestPowerStateOverride) &&
2468 (client == gIOPMPowerClientDevice))
2469 fOverrideMaxPowerState = kIOPMPowerStateMax;
2470
39236c6e 2471 if ((state == kPowerStateZero) &&
fe8ab488
A
2472 (client != gIOPMPowerClientDevice) &&
2473 (client != gIOPMPowerClientDriver) &&
2474 (client != gIOPMPowerClientChildProxy))
2475 removePowerClient(client);
2476 else
2477 updatePowerClient(client, state);
2478
2479 adjustPowerState();
b0d623f7
A
2480 client->release();
2481}
2482
2483//*********************************************************************************
2484// [private] Helper functions to update/remove power clients.
2485//*********************************************************************************
2486
2487void IOService::updatePowerClient( const OSSymbol * client, uint32_t powerState )
2488{
39236c6e
A
2489 IOPMPowerStateIndex oldPowerState = kPowerStateZero;
2490
b0d623f7
A
2491 if (!fPowerClients)
2492 fPowerClients = OSDictionary::withCapacity(4);
2493 if (fPowerClients && client)
2494 {
2495 OSNumber * num = (OSNumber *) fPowerClients->getObject(client);
2496 if (num)
39236c6e
A
2497 {
2498 oldPowerState = num->unsigned32BitValue();
b0d623f7 2499 num->setValue(powerState);
39236c6e 2500 }
b0d623f7
A
2501 else
2502 {
2503 num = OSNumber::withNumber(powerState, 32);
2504 if (num)
2505 {
2506 fPowerClients->setObject(client, num);
2507 num->release();
2508 }
2509 }
39236c6e
A
2510
2511 PM_ACTION_3(actionUpdatePowerClient, client, oldPowerState, powerState);
b0d623f7
A
2512 }
2513}
2514
2515void IOService::removePowerClient( const OSSymbol * client )
2516{
2517 if (fPowerClients && client)
2518 fPowerClients->removeObject(client);
2519}
2520
2521uint32_t IOService::getPowerStateForClient( const OSSymbol * client )
2522{
39236c6e 2523 uint32_t powerState = kPowerStateZero;
b0d623f7
A
2524
2525 if (fPowerClients && client)
2526 {
2527 OSNumber * num = (OSNumber *) fPowerClients->getObject(client);
2528 if (num) powerState = num->unsigned32BitValue();
2529 }
2530 return powerState;
2d21ac55 2531}
1c79356b 2532
6d2010ae
A
2533//*********************************************************************************
2534// [protected] powerOverrideOnPriv
2535//*********************************************************************************
2536
39236c6e 2537IOReturn IOService::powerOverrideOnPriv( void )
6d2010ae 2538{
fe8ab488 2539 IOPMRequest * request;
6d2010ae
A
2540
2541 if (!initialized)
fe8ab488 2542 return IOPMNotYetInitialized;
6d2010ae 2543
fe8ab488
A
2544 if (gIOPMWorkLoop->inGate())
2545 {
2546 fDeviceOverrideEnabled = true;
2547 return IOPMNoErr;
2548 }
6d2010ae 2549
fe8ab488
A
2550 request = acquirePMRequest( this, kIOPMRequestTypePowerOverrideOnPriv );
2551 if (!request)
2552 return kIOReturnNoMemory;
6d2010ae 2553
fe8ab488 2554 submitPMRequest( request );
6d2010ae
A
2555 return IOPMNoErr;
2556}
2557
2558//*********************************************************************************
2559// [protected] powerOverrideOffPriv
2560//*********************************************************************************
2561
39236c6e 2562IOReturn IOService::powerOverrideOffPriv( void )
6d2010ae 2563{
fe8ab488 2564 IOPMRequest * request;
6d2010ae
A
2565
2566 if (!initialized)
fe8ab488 2567 return IOPMNotYetInitialized;
6d2010ae 2568
fe8ab488
A
2569 if (gIOPMWorkLoop->inGate())
2570 {
2571 fDeviceOverrideEnabled = false;
2572 return IOPMNoErr;
2573 }
6d2010ae 2574
fe8ab488
A
2575 request = acquirePMRequest( this, kIOPMRequestTypePowerOverrideOffPriv );
2576 if (!request)
2577 return kIOReturnNoMemory;
6d2010ae 2578
fe8ab488 2579 submitPMRequest( request );
6d2010ae
A
2580 return IOPMNoErr;
2581}
2582
2583//*********************************************************************************
2584// [private] handlePowerOverrideChanged
2585//*********************************************************************************
2586
39236c6e 2587void IOService::handlePowerOverrideChanged( IOPMRequest * request )
6d2010ae 2588{
fe8ab488
A
2589 PM_ASSERT_IN_GATE();
2590 if (request->getType() == kIOPMRequestTypePowerOverrideOnPriv)
2591 {
2592 OUR_PMLog(kPMLogOverrideOn, 0, 0);
2593 fDeviceOverrideEnabled = true;
2594 }
2595 else
2596 {
2597 OUR_PMLog(kPMLogOverrideOff, 0, 0);
2598 fDeviceOverrideEnabled = false;
6d2010ae 2599 }
6d2010ae 2600
fe8ab488 2601 adjustPowerState();
6d2010ae
A
2602}
2603
1c79356b 2604//*********************************************************************************
2d21ac55 2605// [private] computeDesiredState
1c79356b
A
2606//*********************************************************************************
2607
bd504ef0 2608void IOService::computeDesiredState( unsigned long localClamp, bool computeOnly )
1c79356b 2609{
fe8ab488
A
2610 OSIterator * iter;
2611 OSObject * next;
2612 IOPowerConnection * connection;
2613 uint32_t desiredState = kPowerStateZero;
39236c6e 2614 uint32_t newPowerState = kPowerStateZero;
b0d623f7 2615 bool hasChildren = false;
2d21ac55 2616
fe8ab488 2617 // Desired power state is always 0 without a controlling driver.
2d21ac55 2618
fe8ab488
A
2619 if (!fNumberOfPowerStates)
2620 {
39236c6e 2621 fDesiredPowerState = kPowerStateZero;
fe8ab488
A
2622 return;
2623 }
2d21ac55 2624
b0d623f7 2625 // Examine the children's desired power state.
1c79356b 2626
b0d623f7
A
2627 iter = getChildIterator(gIOPowerPlane);
2628 if (iter)
55e303ae 2629 {
b0d623f7 2630 while ((next = iter->getNextObject()))
55e303ae 2631 {
b0d623f7 2632 if ((connection = OSDynamicCast(IOPowerConnection, next)))
55e303ae 2633 {
b0d623f7 2634 if (connection->getReadyFlag() == false)
55e303ae 2635 {
6d2010ae 2636 PM_LOG3("[%s] %s: connection not ready\n",
b0d623f7
A
2637 getName(), __FUNCTION__);
2638 continue;
1c79356b 2639 }
b0d623f7
A
2640 if (connection->childHasRequestedPower())
2641 hasChildren = true;
39236c6e 2642 desiredState = StateMax(connection->getDesiredDomainState(), desiredState);
1c79356b 2643 }
1c79356b 2644 }
b0d623f7
A
2645 iter->release();
2646 }
2647 if (hasChildren)
2648 updatePowerClient(gIOPMPowerClientChildren, desiredState);
2649 else
2650 removePowerClient(gIOPMPowerClientChildren);
2d21ac55 2651
b0d623f7
A
2652 // Iterate through all power clients to determine the min power state.
2653
2654 iter = OSCollectionIterator::withCollection(fPowerClients);
2655 if (iter)
2656 {
2657 const OSSymbol * client;
2658 while ((client = (const OSSymbol *) iter->getNextObject()))
2659 {
fe8ab488 2660 // Ignore child and driver when override is in effect.
6d2010ae 2661 if ((fDeviceOverrideEnabled ||
b0d623f7
A
2662 (getPMRequestType() == kIOPMRequestTypeRequestPowerStateOverride)) &&
2663 ((client == gIOPMPowerClientChildren) ||
2664 (client == gIOPMPowerClientDriver)))
2665 continue;
2666
fe8ab488 2667 // Ignore child proxy when children are present.
b0d623f7
A
2668 if (hasChildren && (client == gIOPMPowerClientChildProxy))
2669 continue;
2670
bd504ef0 2671 // Advisory tickles are irrelevant unless system is in full wake
db609669
A
2672 if (client == gIOPMPowerClientAdvisoryTickle &&
2673 !gIOPMAdvisoryTickleEnabled)
2674 continue;
2675
b0d623f7 2676 desiredState = getPowerStateForClient(client);
fe8ab488
A
2677 assert(desiredState < fNumberOfPowerStates);
2678 PM_LOG1(" %u %s\n",
2679 desiredState, client->getCStringNoCopy());
b0d623f7 2680
39236c6e 2681 newPowerState = StateMax(newPowerState, desiredState);
b0d623f7
A
2682
2683 if (client == gIOPMPowerClientDevice)
2684 fDeviceDesire = desiredState;
2685 }
2686 iter->release();
1c79356b
A
2687 }
2688
b0d623f7
A
2689 // Factor in the temporary power desires.
2690
39236c6e
A
2691 newPowerState = StateMax(newPowerState, localClamp);
2692 newPowerState = StateMax(newPowerState, fTempClampPowerState);
b0d623f7
A
2693
2694 // Limit check against max power override.
2695
39236c6e 2696 newPowerState = StateMin(newPowerState, fOverrideMaxPowerState);
2d21ac55 2697
2d21ac55
A
2698 // Limit check against number of power states.
2699
b0d623f7 2700 if (newPowerState >= fNumberOfPowerStates)
39236c6e 2701 newPowerState = fHighestPowerState;
b0d623f7
A
2702
2703 fDesiredPowerState = newPowerState;
2704
6d2010ae 2705 PM_LOG1(" temp %u, clamp %u, current %u, new %u\n",
b0d623f7 2706 (uint32_t) localClamp, (uint32_t) fTempClampPowerState,
fe8ab488 2707 (uint32_t) fCurrentPowerState, newPowerState);
1c79356b 2708
bd504ef0 2709 if (!computeOnly)
db609669 2710 {
bd504ef0
A
2711 // Restart idle timer if possible when device desire has increased.
2712 // Or if an advisory desire exists.
2713
2714 if (fIdleTimerPeriod && fIdleTimerStopped)
db609669 2715 {
bd504ef0 2716 restartIdleTimer();
db609669 2717 }
2d21ac55 2718
bd504ef0
A
2719 // Invalidate cached tickle power state when desires change, and not
2720 // due to a tickle request. In case the driver has requested a lower
2721 // power state, but the tickle is caching a higher power state which
2722 // will drop future tickles until the cached value is lowered or in-
2723 // validated. The invalidation must occur before the power transition
2724 // to avoid dropping a necessary tickle.
2d21ac55 2725
bd504ef0
A
2726 if ((getPMRequestType() != kIOPMRequestTypeActivityTickle) &&
2727 (fActivityTicklePowerState != kInvalidTicklePowerState))
2728 {
2729 IOLockLock(fActivityLock);
2730 fActivityTicklePowerState = kInvalidTicklePowerState;
2731 IOLockUnlock(fActivityLock);
2732 }
db609669 2733 }
2d21ac55 2734}
1c79356b
A
2735
2736//*********************************************************************************
b0d623f7 2737// [public] currentPowerConsumption
1c79356b
A
2738//
2739//*********************************************************************************
2740
39236c6e 2741unsigned long IOService::currentPowerConsumption( void )
1c79356b 2742{
2d21ac55 2743 if (!initialized)
0b4e3aa0 2744 return kIOPMUnknown;
2d21ac55
A
2745
2746 return fCurrentPowerConsumption;
2747}
2748
2749//*********************************************************************************
b0d623f7 2750// [deprecated] getPMworkloop
2d21ac55
A
2751//*********************************************************************************
2752
39236c6e 2753IOWorkLoop * IOService::getPMworkloop( void )
2d21ac55 2754{
fe8ab488 2755 return gIOPMWorkLoop;
1c79356b
A
2756}
2757
6d2010ae
A
2758#if NOT_YET
2759
1c79356b 2760//*********************************************************************************
6d2010ae
A
2761// Power Parent/Children Applier
2762//*********************************************************************************
2763
2764static void
fe8ab488 2765applyToPowerChildren(
6d2010ae
A
2766 IOService * service,
2767 IOServiceApplierFunction applier,
2768 void * context,
2769 IOOptionBits options )
2770{
fe8ab488 2771 PM_ASSERT_IN_GATE();
6d2010ae
A
2772
2773 IORegistryEntry * entry;
2774 IORegistryIterator * iter;
2775 IOPowerConnection * connection;
2776 IOService * child;
2777
2778 iter = IORegistryIterator::iterateOver(service, gIOPowerPlane, options);
2779 if (iter)
2780 {
2781 while ((entry = iter->getNextObject()))
2782 {
2783 // Get child of IOPowerConnection objects
2784 if ((connection = OSDynamicCast(IOPowerConnection, entry)))
2785 {
2786 child = (IOService *) connection->copyChildEntry(gIOPowerPlane);
2787 if (child)
2788 {
2789 (*applier)(child, context);
2790 child->release();
2791 }
2792 }
2793 }
2794 iter->release();
2795 }
2796}
2797
2798static void
fe8ab488 2799applyToPowerParent(
6d2010ae
A
2800 IOService * service,
2801 IOServiceApplierFunction applier,
2802 void * context,
2803 IOOptionBits options )
2804{
fe8ab488 2805 PM_ASSERT_IN_GATE();
6d2010ae
A
2806
2807 IORegistryEntry * entry;
2808 IORegistryIterator * iter;
2809 IOPowerConnection * connection;
2810 IOService * parent;
2811
2812 iter = IORegistryIterator::iterateOver(service, gIOPowerPlane,
2813 options | kIORegistryIterateParents);
2814 if (iter)
2815 {
2816 while ((entry = iter->getNextObject()))
2817 {
2818 // Get child of IOPowerConnection objects
2819 if ((connection = OSDynamicCast(IOPowerConnection, entry)))
2820 {
2821 parent = (IOService *) connection->copyParentEntry(gIOPowerPlane);
2822 if (parent)
2823 {
2824 (*applier)(parent, context);
2825 parent->release();
2826 }
2827 }
2828 }
2829 iter->release();
2830 }
2831}
2832
2833#endif /* NOT_YET */
2834
2835// MARK: -
2836// MARK: Activity Tickle & Idle Timer
2837
db609669
A
2838void IOService::setAdvisoryTickleEnable( bool enable )
2839{
2840 gIOPMAdvisoryTickleEnabled = enable;
2841}
2842
6d2010ae
A
2843//*********************************************************************************
2844// [public] activityTickle
2845//
2846// The tickle with parameter kIOPMSuperclassPolicy1 causes the activity
2847// flag to be set, and the device state checked. If the device has been
2848// powered down, it is powered up again.
2d21ac55
A
2849// The tickle with parameter kIOPMSubclassPolicy is ignored here and
2850// should be intercepted by a subclass.
1c79356b
A
2851//*********************************************************************************
2852
39236c6e 2853bool IOService::activityTickle( unsigned long type, unsigned long stateNumber )
1c79356b 2854{
fe8ab488
A
2855 IOPMRequest * request;
2856 bool noPowerChange = true;
bd504ef0 2857 uint32_t tickleFlags;
e7c99d92 2858
db609669
A
2859 if (!initialized)
2860 return true; // no power change
2861
39236c6e 2862 if ((type == kIOPMSuperclassPolicy1) && StateOrder(stateNumber))
fe8ab488 2863 {
2d21ac55 2864 IOLockLock(fActivityLock);
e7c99d92 2865
fe8ab488 2866 // Record device activity for the idle timer handler.
e7c99d92 2867
6d2010ae 2868 fDeviceWasActive = true;
b0d623f7 2869 fActivityTickleCount++;
2d21ac55 2870 clock_get_uptime(&fDeviceActiveTimestamp);
55e303ae 2871
6d2010ae 2872 PM_ACTION_0(actionActivityTickle);
b0d623f7 2873
fe8ab488
A
2874 // Record the last tickle power state.
2875 // This helps to filter out redundant tickles as
2876 // this function may be called from the data path.
1c79356b 2877
39236c6e
A
2878 if ((fActivityTicklePowerState == kInvalidTicklePowerState)
2879 || StateOrder(fActivityTicklePowerState) < StateOrder(stateNumber))
fe8ab488
A
2880 {
2881 fActivityTicklePowerState = stateNumber;
2882 noPowerChange = false;
1c79356b 2883
bd504ef0 2884 tickleFlags = kTickleTypeActivity | kTickleTypePowerRise;
fe8ab488
A
2885 request = acquirePMRequest( this, kIOPMRequestTypeActivityTickle );
2886 if (request)
2887 {
2888 request->fArg0 = (void *) stateNumber;
2889 request->fArg1 = (void *)(uintptr_t) tickleFlags;
39236c6e 2890 request->fArg2 = (void *)(uintptr_t) gIOPMTickleGeneration;
fe8ab488
A
2891 submitPMRequest(request);
2892 }
2893 }
1c79356b 2894
fe8ab488
A
2895 IOLockUnlock(fActivityLock);
2896 }
1c79356b 2897
db609669 2898 else if ((type == kIOPMActivityTickleTypeAdvisory) &&
39236c6e 2899 ((stateNumber = fDeviceUsablePowerState) != kPowerStateZero))
db609669
A
2900 {
2901 IOLockLock(fActivityLock);
2902
2903 fAdvisoryTickled = true;
2904
fe8ab488
A
2905 if (fAdvisoryTicklePowerState != stateNumber)
2906 {
2907 fAdvisoryTicklePowerState = stateNumber;
2908 noPowerChange = false;
db609669 2909
bd504ef0 2910 tickleFlags = kTickleTypeAdvisory | kTickleTypePowerRise;
fe8ab488
A
2911 request = acquirePMRequest( this, kIOPMRequestTypeActivityTickle );
2912 if (request)
2913 {
2914 request->fArg0 = (void *) stateNumber;
2915 request->fArg1 = (void *)(uintptr_t) tickleFlags;
39236c6e 2916 request->fArg2 = (void *)(uintptr_t) gIOPMTickleGeneration;
fe8ab488
A
2917 submitPMRequest(request);
2918 }
2919 }
db609669 2920
fe8ab488 2921 IOLockUnlock(fActivityLock);
db609669
A
2922 }
2923
fe8ab488
A
2924 // Returns false if the activityTickle might cause a transition to a
2925 // higher powered state, true otherwise.
2d21ac55
A
2926
2927 return noPowerChange;
2928}
1c79356b
A
2929
2930//*********************************************************************************
b0d623f7
A
2931// [private] handleActivityTickle
2932//*********************************************************************************
2933
39236c6e 2934void IOService::handleActivityTickle( IOPMRequest * request )
b0d623f7 2935{
fe8ab488 2936 uint32_t ticklePowerState = (uint32_t)(uintptr_t) request->fArg0;
bd504ef0
A
2937 uint32_t tickleFlags = (uint32_t)(uintptr_t) request->fArg1;
2938 uint32_t tickleGeneration = (uint32_t)(uintptr_t) request->fArg2;
db609669 2939 bool adjustPower = false;
fe8ab488
A
2940
2941 PM_ASSERT_IN_GATE();
bd504ef0
A
2942 if (fResetPowerStateOnWake && (tickleGeneration != gIOPMTickleGeneration))
2943 {
2944 // Drivers that don't want power restored on wake will drop any
2945 // tickles that pre-dates the current system wake. The model is
2946 // that each wake is a fresh start, with power state depressed
2947 // until a new tickle or an explicit power up request from the
2948 // driver. It is possible for the PM work loop to enter the
2949 // system sleep path with tickle requests queued.
2950
2951 return;
2952 }
2953
2954 if (tickleFlags & kTickleTypeActivity)
db609669 2955 {
39236c6e 2956 IOPMPowerStateIndex deviceDesireOrder = StateOrder(fDeviceDesire);
fe8ab488 2957 uint32_t idleTimerGeneration = ticklePowerState; // kTickleTypePowerDrop
39236c6e 2958
bd504ef0 2959 if (tickleFlags & kTickleTypePowerRise)
db609669 2960 {
39236c6e 2961 if ((StateOrder(ticklePowerState) > deviceDesireOrder) &&
db609669
A
2962 (ticklePowerState < fNumberOfPowerStates))
2963 {
2964 fIdleTimerMinPowerState = ticklePowerState;
2965 updatePowerClient(gIOPMPowerClientDevice, ticklePowerState);
2966 adjustPower = true;
2967 }
2968 }
fe8ab488
A
2969 else if ((deviceDesireOrder > StateOrder(fIdleTimerMinPowerState)) &&
2970 (idleTimerGeneration == fIdleTimerGeneration))
db609669
A
2971 {
2972 // Power drop due to idle timer expiration.
2973 // Do not allow idle timer to reduce power below tickle power.
2974 // This prevents the idle timer from decreasing the device desire
2975 // to zero and cancelling the effect of a pre-sleep tickle when
2976 // system wakes up to doze state, while the device is unable to
2977 // raise its power state to satisfy the tickle.
fe8ab488 2978
39236c6e
A
2979 deviceDesireOrder--;
2980 if (deviceDesireOrder < fNumberOfPowerStates)
2981 {
2982 ticklePowerState = fPowerStates[deviceDesireOrder].stateOrderToIndex;
2983 updatePowerClient(gIOPMPowerClientDevice, ticklePowerState);
2984 adjustPower = true;
2985 }
db609669
A
2986 }
2987 }
2988 else // advisory tickle
2989 {
bd504ef0 2990 if (tickleFlags & kTickleTypePowerRise)
db609669
A
2991 {
2992 if ((ticklePowerState == fDeviceUsablePowerState) &&
2993 (ticklePowerState < fNumberOfPowerStates))
2994 {
2995 updatePowerClient(gIOPMPowerClientAdvisoryTickle, ticklePowerState);
2996 fHasAdvisoryDesire = true;
2997 fAdvisoryTickleUsed = true;
2998 adjustPower = true;
2999 }
3000 else
3001 {
3002 IOLockLock(fActivityLock);
3003 fAdvisoryTicklePowerState = kInvalidTicklePowerState;
3004 IOLockUnlock(fActivityLock);
3005 }
3006 }
3007 else if (fHasAdvisoryDesire)
3008 {
3009 removePowerClient(gIOPMPowerClientAdvisoryTickle);
3010 fHasAdvisoryDesire = false;
3011 adjustPower = true;
3012 }
3013 }
b0d623f7 3014
fe8ab488
A
3015 if (adjustPower)
3016 {
3017 adjustPowerState();
3018 }
b0d623f7
A
3019}
3020
6d2010ae 3021//******************************************************************************
b0d623f7 3022// [public] setIdleTimerPeriod
1c79356b 3023//
6d2010ae
A
3024// A subclass policy-maker is using our standard idleness detection service.
3025// Start the idle timer. Period is in seconds.
3026//******************************************************************************
1c79356b 3027
39236c6e 3028IOReturn IOService::setIdleTimerPeriod( unsigned long period )
1c79356b 3029{
b0d623f7 3030 if (!initialized)
fe8ab488 3031 return IOPMNotYetInitialized;
2d21ac55 3032
6d2010ae 3033 OUR_PMLog(kPMLogSetIdleTimerPeriod, period, fIdleTimerPeriod);
1c79356b 3034
b0d623f7
A
3035 IOPMRequest * request =
3036 acquirePMRequest( this, kIOPMRequestTypeSetIdleTimerPeriod );
3037 if (!request)
3038 return kIOReturnNoMemory;
1c79356b 3039
b0d623f7
A
3040 request->fArg0 = (void *) period;
3041 submitPMRequest( request );
2d21ac55 3042
6d2010ae 3043 return kIOReturnSuccess;
1c79356b
A
3044}
3045
7ddcb079
A
3046IOReturn IOService::setIgnoreIdleTimer( bool ignore )
3047{
3048 if (!initialized)
fe8ab488 3049 return IOPMNotYetInitialized;
7ddcb079
A
3050
3051 OUR_PMLog(kIOPMRequestTypeIgnoreIdleTimer, ignore, 0);
3052
3053 IOPMRequest * request =
3054 acquirePMRequest( this, kIOPMRequestTypeIgnoreIdleTimer );
3055 if (!request)
3056 return kIOReturnNoMemory;
3057
3058 request->fArg0 = (void *) ignore;
3059 submitPMRequest( request );
3060
3061 return kIOReturnSuccess;
3062}
3063
91447636 3064//******************************************************************************
b0d623f7 3065// [public] nextIdleTimeout
91447636
A
3066//
3067// Returns how many "seconds from now" the device should idle into its
3068// next lowest power state.
3069//******************************************************************************
2d21ac55 3070
91447636
A
3071SInt32 IOService::nextIdleTimeout(
3072 AbsoluteTime currentTime,
fe8ab488 3073 AbsoluteTime lastActivity,
91447636
A
3074 unsigned int powerState)
3075{
6d2010ae
A
3076 AbsoluteTime delta;
3077 UInt64 delta_ns;
3078 SInt32 delta_secs;
3079 SInt32 delay_secs;
1c79356b 3080
91447636
A
3081 // Calculate time difference using funky macro from clock.h.
3082 delta = currentTime;
3083 SUB_ABSOLUTETIME(&delta, &lastActivity);
fe8ab488 3084
91447636
A
3085 // Figure it in seconds.
3086 absolutetime_to_nanoseconds(delta, &delta_ns);
3087 delta_secs = (SInt32)(delta_ns / NSEC_PER_SEC);
3088
3089 // Be paranoid about delta somehow exceeding timer period.
b0d623f7 3090 if (delta_secs < (int) fIdleTimerPeriod)
2d21ac55 3091 delay_secs = (int) fIdleTimerPeriod - delta_secs;
91447636 3092 else
2d21ac55 3093 delay_secs = (int) fIdleTimerPeriod;
fe8ab488 3094
91447636
A
3095 return (SInt32)delay_secs;
3096}
3097
6d2010ae 3098//*********************************************************************************
b0d623f7 3099// [public] start_PM_idle_timer
6d2010ae 3100//*********************************************************************************
2d21ac55 3101
39236c6e 3102void IOService::start_PM_idle_timer( void )
1c79356b 3103{
6d2010ae
A
3104 static const int maxTimeout = 100000;
3105 static const int minTimeout = 1;
3106 AbsoluteTime uptime, deadline;
3107 SInt32 idle_in = 0;
fe8ab488 3108 boolean_t pending;
e7c99d92 3109
fe8ab488
A
3110 if (!initialized || !fIdleTimerPeriod)
3111 return;
2d21ac55
A
3112
3113 IOLockLock(fActivityLock);
e7c99d92
A
3114
3115 clock_get_uptime(&uptime);
6d2010ae 3116
91447636 3117 // Subclasses may modify idle sleep algorithm
2d21ac55 3118 idle_in = nextIdleTimeout(uptime, fDeviceActiveTimestamp, fCurrentPowerState);
e7c99d92 3119
91447636 3120 // Check for out-of range responses
2d21ac55 3121 if (idle_in > maxTimeout)
55e303ae 3122 {
91447636
A
3123 // use standard implementation
3124 idle_in = IOService::nextIdleTimeout(uptime,
2d21ac55
A
3125 fDeviceActiveTimestamp,
3126 fCurrentPowerState);
3127 } else if (idle_in < minTimeout) {
3128 idle_in = fIdleTimerPeriod;
e7c99d92
A
3129 }
3130
2d21ac55 3131 IOLockUnlock(fActivityLock);
e7c99d92 3132
fe8ab488
A
3133 fNextIdleTimerPeriod = idle_in;
3134 fIdleTimerStartTime = uptime;
3135
6d2010ae
A
3136 retain();
3137 clock_interval_to_absolutetime_interval(idle_in, kSecondScale, &deadline);
3138 ADD_ABSOLUTETIME(&deadline, &uptime);
3139 pending = thread_call_enter_delayed(fIdleTimer, deadline);
3140 if (pending) release();
3141}
3142
bd504ef0
A
3143//*********************************************************************************
3144// [private] restartIdleTimer
3145//*********************************************************************************
3146
3147void IOService::restartIdleTimer( void )
3148{
39236c6e 3149 if (fDeviceDesire != kPowerStateZero)
bd504ef0
A
3150 {
3151 fIdleTimerStopped = false;
3152 fActivityTickleCount = 0;
bd504ef0
A
3153 start_PM_idle_timer();
3154 }
3155 else if (fHasAdvisoryDesire)
3156 {
3157 fIdleTimerStopped = false;
3158 start_PM_idle_timer();
3159 }
3160 else
3161 {
3162 fIdleTimerStopped = true;
3163 }
3164}
3165
6d2010ae
A
3166//*********************************************************************************
3167// idle_timer_expired
3168//*********************************************************************************
3169
3170static void
39236c6e 3171idle_timer_expired(
6d2010ae
A
3172 thread_call_param_t arg0, thread_call_param_t arg1 )
3173{
fe8ab488 3174 IOService * me = (IOService *) arg0;
6d2010ae 3175
fe8ab488
A
3176 if (gIOPMWorkLoop)
3177 gIOPMWorkLoop->runAction(
6d2010ae
A
3178 OSMemberFunctionCast(IOWorkLoop::Action, me,
3179 &IOService::idleTimerExpired),
3180 me);
3181
fe8ab488 3182 me->release();
1c79356b
A
3183}
3184
1c79356b 3185//*********************************************************************************
b0d623f7 3186// [private] idleTimerExpired
1c79356b 3187//
6d2010ae 3188// The idle timer has expired. If there has been activity since the last
1c79356b
A
3189// expiration, just restart the timer and return. If there has not been
3190// activity, switch to the next lower power state and restart the timer.
3191//*********************************************************************************
3192
6d2010ae 3193void IOService::idleTimerExpired( void )
1c79356b 3194{
fe8ab488
A
3195 IOPMRequest * request;
3196 bool restartTimer = true;
bd504ef0 3197 uint32_t tickleFlags;
2d21ac55 3198
bd504ef0
A
3199 if ( !initialized || !fIdleTimerPeriod || fIdleTimerStopped ||
3200 fLockedFlags.PMStop )
55e303ae 3201 return;
1c79356b 3202
fe8ab488 3203 fIdleTimerStartTime = 0;
1c79356b 3204
fe8ab488 3205 IOLockLock(fActivityLock);
1c79356b 3206
fe8ab488
A
3207 // Check for device activity (tickles) over last timer period.
3208
3209 if (fDeviceWasActive)
3210 {
3211 // Device was active - do not drop power, restart timer.
3212 fDeviceWasActive = false;
3213 }
3214 else if (!fIdleTimerIgnored)
3215 {
3216 // No device activity - drop power state by one level.
3217 // Decrement the cached tickle power state when possible.
3218 // This value may be kInvalidTicklePowerState before activityTickle()
39236c6e 3219 // is called, but the power drop request must be issued regardless.
1c79356b 3220
fe8ab488 3221 if ((fActivityTicklePowerState != kInvalidTicklePowerState) &&
39236c6e 3222 (fActivityTicklePowerState != kPowerStateZero))
fe8ab488 3223 fActivityTicklePowerState--;
1c79356b 3224
bd504ef0 3225 tickleFlags = kTickleTypeActivity | kTickleTypePowerDrop;
fe8ab488
A
3226 request = acquirePMRequest( this, kIOPMRequestTypeActivityTickle );
3227 if (request)
3228 {
3229 request->fArg0 = (void *)(uintptr_t) fIdleTimerGeneration;
3230 request->fArg1 = (void *)(uintptr_t) tickleFlags;
39236c6e 3231 request->fArg2 = (void *)(uintptr_t) gIOPMTickleGeneration;
fe8ab488 3232 submitPMRequest( request );
1c79356b 3233
fe8ab488
A
3234 // Do not restart timer until after the tickle request has been
3235 // processed.
91447636 3236
fe8ab488
A
3237 restartTimer = false;
3238 }
1c79356b 3239 }
2d21ac55 3240
db609669
A
3241 if (fAdvisoryTickled)
3242 {
3243 fAdvisoryTickled = false;
3244 }
3245 else if (fHasAdvisoryDesire)
3246 {
3247 // Want new tickles to turn into pm request after we drop the lock
3248 fAdvisoryTicklePowerState = kInvalidTicklePowerState;
3249
bd504ef0 3250 tickleFlags = kTickleTypeAdvisory | kTickleTypePowerDrop;
fe8ab488
A
3251 request = acquirePMRequest( this, kIOPMRequestTypeActivityTickle );
3252 if (request)
3253 {
3254 request->fArg0 = (void *)(uintptr_t) fIdleTimerGeneration;
3255 request->fArg1 = (void *)(uintptr_t) tickleFlags;
39236c6e 3256 request->fArg2 = (void *)(uintptr_t) gIOPMTickleGeneration;
fe8ab488 3257 submitPMRequest( request );
db609669 3258
fe8ab488
A
3259 // Do not restart timer until after the tickle request has been
3260 // processed.
db609669 3261
fe8ab488
A
3262 restartTimer = false;
3263 }
db609669
A
3264 }
3265
fe8ab488 3266 IOLockUnlock(fActivityLock);
2d21ac55 3267
fe8ab488
A
3268 if (restartTimer)
3269 start_PM_idle_timer();
1c79356b
A
3270}
3271
b0d623f7 3272#ifndef __LP64__
2d21ac55 3273//*********************************************************************************
b0d623f7
A
3274// [deprecated] PM_idle_timer_expiration
3275//*********************************************************************************
3276
39236c6e 3277void IOService::PM_idle_timer_expiration( void )
b0d623f7
A
3278{
3279}
3280
3281//*********************************************************************************
3282// [deprecated] command_received
2d21ac55
A
3283//*********************************************************************************
3284
39236c6e 3285void IOService::command_received( void *statePtr , void *, void * , void * )
2d21ac55
A
3286{
3287}
b0d623f7 3288#endif /* !__LP64__ */
1c79356b
A
3289
3290//*********************************************************************************
b0d623f7 3291// [public] setAggressiveness
1c79356b
A
3292//
3293// Pass on the input parameters to all power domain children. All those which are
3294// power domains will pass it on to their children, etc.
3295//*********************************************************************************
3296
39236c6e 3297IOReturn IOService::setAggressiveness( unsigned long type, unsigned long newLevel )
1c79356b 3298{
b0d623f7 3299 return kIOReturnSuccess;
1c79356b
A
3300}
3301
3302//*********************************************************************************
b0d623f7 3303// [public] getAggressiveness
1c79356b
A
3304//
3305// Called by the user client.
3306//*********************************************************************************
3307
39236c6e 3308IOReturn IOService::getAggressiveness( unsigned long type, unsigned long * currentLevel )
1c79356b 3309{
b0d623f7 3310 IOPMrootDomain * rootDomain = getPMRootDomain();
55e303ae 3311
b0d623f7
A
3312 if (!rootDomain)
3313 return kIOReturnNotReady;
fe8ab488 3314
b0d623f7 3315 return rootDomain->getAggressiveness( type, currentLevel );
1c79356b
A
3316}
3317
3318//*********************************************************************************
2d21ac55
A
3319// [public] getPowerState
3320//
3321//*********************************************************************************
3322
39236c6e 3323UInt32 IOService::getPowerState( void )
2d21ac55
A
3324{
3325 if (!initialized)
39236c6e 3326 return kPowerStateZero;
2d21ac55
A
3327
3328 return fCurrentPowerState;
3329}
3330
b0d623f7 3331#ifndef __LP64__
2d21ac55 3332//*********************************************************************************
b0d623f7 3333// [deprecated] systemWake
1c79356b
A
3334//
3335// Pass this to all power domain children. All those which are
3336// power domains will pass it on to their children, etc.
3337//*********************************************************************************
3338
39236c6e 3339IOReturn IOService::systemWake( void )
1c79356b 3340{
fe8ab488
A
3341 OSIterator * iter;
3342 OSObject * next;
3343 IOPowerConnection * connection;
3344 IOService * theChild;
1c79356b 3345
1c79356b 3346 iter = getChildIterator(gIOPowerPlane);
2d21ac55 3347 if ( iter )
55e303ae 3348 {
2d21ac55 3349 while ( (next = iter->getNextObject()) )
55e303ae 3350 {
2d21ac55 3351 if ( (connection = OSDynamicCast(IOPowerConnection, next)) )
55e303ae 3352 {
fe8ab488
A
3353 if (connection->getReadyFlag() == false)
3354 {
3355 PM_LOG3("[%s] %s: connection not ready\n",
3356 getName(), __FUNCTION__);
3357 continue;
3358 }
2d21ac55 3359
0b4e3aa0 3360 theChild = (IOService *)connection->copyChildEntry(gIOPowerPlane);
2d21ac55 3361 if ( theChild )
55e303ae 3362 {
fe8ab488 3363 theChild->systemWake();
55e303ae 3364 theChild->release();
0b4e3aa0 3365 }
1c79356b
A
3366 }
3367 }
3368 iter->release();
3369 }
3370
2d21ac55 3371 if ( fControllingDriver != NULL )
55e303ae 3372 {
2d21ac55 3373 if ( fControllingDriver->didYouWakeSystem() )
55e303ae 3374 {
1c79356b
A
3375 makeUsable();
3376 }
3377 }
3378
3379 return IOPMNoErr;
3380}
3381
1c79356b 3382//*********************************************************************************
b0d623f7 3383// [deprecated] temperatureCriticalForZone
1c79356b
A
3384//*********************************************************************************
3385
39236c6e 3386IOReturn IOService::temperatureCriticalForZone( IOService * whichZone )
1c79356b 3387{
fe8ab488
A
3388 IOService * theParent;
3389 IOService * theNub;
3390
2d21ac55 3391 OUR_PMLog(kPMLogCriticalTemp, 0, 0);
1c79356b 3392
6d2010ae 3393 if ( inPlane(gIOPowerPlane) && !IS_PM_ROOT )
55e303ae 3394 {
0b4e3aa0 3395 theNub = (IOService *)copyParentEntry(gIOPowerPlane);
2d21ac55 3396 if ( theNub )
55e303ae 3397 {
0b4e3aa0
A
3398 theParent = (IOService *)theNub->copyParentEntry(gIOPowerPlane);
3399 theNub->release();
2d21ac55 3400 if ( theParent )
55e303ae 3401 {
0b4e3aa0
A
3402 theParent->temperatureCriticalForZone(whichZone);
3403 theParent->release();
3404 }
3405 }
1c79356b
A
3406 }
3407 return IOPMNoErr;
3408}
b0d623f7 3409#endif /* !__LP64__ */
1c79356b 3410
6d2010ae
A
3411// MARK: -
3412// MARK: Power Change (Common)
1c79356b
A
3413
3414//*********************************************************************************
b0d623f7 3415// [private] startPowerChange
6d2010ae
A
3416//
3417// All power state changes starts here.
1c79356b
A
3418//*********************************************************************************
3419
6d2010ae
A
3420IOReturn IOService::startPowerChange(
3421 IOPMPowerChangeFlags changeFlags,
3422 IOPMPowerStateIndex powerState,
3423 IOPMPowerFlags domainFlags,
3424 IOPowerConnection * parentConnection,
3425 IOPMPowerFlags parentFlags )
2d21ac55 3426{
fe8ab488
A
3427 PM_ASSERT_IN_GATE();
3428 assert( fMachineState == kIOPM_Finished );
b0d623f7 3429 assert( powerState < fNumberOfPowerStates );
2d21ac55 3430
b0d623f7 3431 if (powerState >= fNumberOfPowerStates)
55e303ae 3432 return IOPMAckImplied;
1c79356b 3433
6d2010ae
A
3434 fIsPreChange = true;
3435 PM_ACTION_2(actionPowerChangeOverride, &powerState, &changeFlags);
b7266188 3436
39236c6e
A
3437 if (changeFlags & kIOPMExpireIdleTimer)
3438 {
3439 // Root domain requested removal of tickle influence
3440 if (StateOrder(fDeviceDesire) > StateOrder(powerState))
3441 {
3442 // Reset device desire down to the clamped power state
3443 updatePowerClient(gIOPMPowerClientDevice, powerState);
3444 computeDesiredState(kPowerStateZero, true);
fe8ab488 3445
39236c6e
A
3446 // Invalidate tickle cache so the next tickle will issue a request
3447 IOLockLock(fActivityLock);
3448 fDeviceWasActive = false;
3449 fActivityTicklePowerState = kInvalidTicklePowerState;
3450 IOLockUnlock(fActivityLock);
3451
3452 fIdleTimerMinPowerState = kPowerStateZero;
3453 }
3454 }
3455
3456 // Root domain's override handler may cancel the power change by
3457 // setting the kIOPMNotDone flag.
3458
3459 if (changeFlags & kIOPMNotDone)
3460 return IOPMAckImplied;
3461
fe8ab488 3462 // Forks to either Driver or Parent initiated power change paths.
2d21ac55 3463
6d2010ae 3464 fHeadNoteChangeFlags = changeFlags;
b0d623f7 3465 fHeadNotePowerState = powerState;
fe8ab488
A
3466 fHeadNotePowerArrayEntry = &fPowerStates[ powerState ];
3467 fHeadNoteParentConnection = NULL;
1c79356b 3468
fe8ab488
A
3469 if (changeFlags & kIOPMSelfInitiated)
3470 {
b0d623f7
A
3471 if (changeFlags & kIOPMSynchronize)
3472 OurSyncStart();
3473 else
3474 OurChangeStart();
fe8ab488
A
3475 return 0;
3476 }
3477 else
3478 {
3479 assert(changeFlags & kIOPMParentInitiated);
b0d623f7 3480 fHeadNoteDomainFlags = domainFlags;
fe8ab488 3481 fHeadNoteParentFlags = parentFlags;
b0d623f7 3482 fHeadNoteParentConnection = parentConnection;
fe8ab488
A
3483 return ParentChangeStart();
3484 }
2d21ac55 3485}
1c79356b 3486
2d21ac55
A
3487//*********************************************************************************
3488// [private] notifyInterestedDrivers
3489//*********************************************************************************
3490
39236c6e 3491bool IOService::notifyInterestedDrivers( void )
2d21ac55 3492{
fe8ab488
A
3493 IOPMinformee * informee;
3494 IOPMinformeeList * list = fInterestedDrivers;
3495 DriverCallParam * param;
3496 IOItemCount count;
2d21ac55 3497
6d2010ae
A
3498 PM_ASSERT_IN_GATE();
3499 assert( fDriverCallParamCount == 0 );
3500 assert( fHeadNotePendingAcks == 0 );
2d21ac55 3501
b0d623f7
A
3502 fHeadNotePendingAcks = 0;
3503
6d2010ae
A
3504 count = list->numberOfItems();
3505 if (!count)
fe8ab488 3506 goto done; // no interested drivers
2d21ac55 3507
6d2010ae
A
3508 // Allocate an array of interested drivers and their return values
3509 // for the callout thread. Everything else is still "owned" by the
3510 // PM work loop, which can run to process acknowledgePowerChange()
3511 // responses.
2d21ac55 3512
6d2010ae
A
3513 param = (DriverCallParam *) fDriverCallParamPtr;
3514 if (count > fDriverCallParamSlots)
3515 {
3516 if (fDriverCallParamSlots)
3517 {
3518 assert(fDriverCallParamPtr);
3519 IODelete(fDriverCallParamPtr, DriverCallParam, fDriverCallParamSlots);
3520 fDriverCallParamPtr = 0;
3521 fDriverCallParamSlots = 0;
3522 }
2d21ac55 3523
6d2010ae
A
3524 param = IONew(DriverCallParam, count);
3525 if (!param)
fe8ab488 3526 goto done; // no memory
2d21ac55 3527
6d2010ae
A
3528 fDriverCallParamPtr = (void *) param;
3529 fDriverCallParamSlots = count;
3530 }
2d21ac55 3531
6d2010ae
A
3532 informee = list->firstInList();
3533 assert(informee);
3534 for (IOItemCount i = 0; i < count; i++)
3535 {
3536 informee->timer = -1;
3537 param[i].Target = informee;
3538 informee->retain();
2d21ac55 3539 informee = list->nextInList( informee );
6d2010ae 3540 }
2d21ac55 3541
6d2010ae
A
3542 fDriverCallParamCount = count;
3543 fHeadNotePendingAcks = count;
2d21ac55 3544
6d2010ae
A
3545 // Block state machine and wait for callout completion.
3546 assert(!fDriverCallBusy);
3547 fDriverCallBusy = true;
3548 thread_call_enter( fDriverCallEntry );
3549 return true;
2d21ac55
A
3550
3551done:
6d2010ae
A
3552 // Return false if there are no interested drivers or could not schedule
3553 // callout thread due to error.
3554 return false;
2d21ac55
A
3555}
3556
3557//*********************************************************************************
3558// [private] notifyInterestedDriversDone
3559//*********************************************************************************
3560
39236c6e 3561void IOService::notifyInterestedDriversDone( void )
2d21ac55 3562{
fe8ab488
A
3563 IOPMinformee * informee;
3564 IOItemCount count;
6d2010ae
A
3565 DriverCallParam * param;
3566 IOReturn result;
2d21ac55 3567
fe8ab488
A
3568 PM_ASSERT_IN_GATE();
3569 assert( fDriverCallBusy == false );
3570 assert( fMachineState == kIOPM_DriverThreadCallDone );
6d2010ae 3571
fe8ab488
A
3572 param = (DriverCallParam *) fDriverCallParamPtr;
3573 count = fDriverCallParamCount;
2d21ac55 3574
fe8ab488
A
3575 if (param && count)
3576 {
3577 for (IOItemCount i = 0; i < count; i++, param++)
3578 {
3579 informee = (IOPMinformee *) param->Target;
3580 result = param->Result;
2d21ac55 3581
fe8ab488
A
3582 if ((result == IOPMAckImplied) || (result < 0))
3583 {
3584 // Interested driver return IOPMAckImplied.
b0d623f7
A
3585 // If informee timer is zero, it must have de-registered
3586 // interest during the thread callout. That also drops
3587 // the pending ack count.
3588
fe8ab488 3589 if (fHeadNotePendingAcks && informee->timer)
b0d623f7
A
3590 fHeadNotePendingAcks--;
3591
3592 informee->timer = 0;
fe8ab488
A
3593 }
3594 else if (informee->timer)
3595 {
2d21ac55
A
3596 assert(informee->timer == -1);
3597
3598 // Driver has not acked, and has returned a positive result.
3599 // Enforce a minimum permissible timeout value.
3600 // Make the min value large enough so timeout is less likely
3601 // to occur if a driver misinterpreted that the return value
3602 // should be in microsecond units. And make it large enough
3603 // to be noticeable if a driver neglects to ack.
3604
3605 if (result < kMinAckTimeoutTicks)
3606 result = kMinAckTimeoutTicks;
3607
3608 informee->timer = (result / (ACK_TIMER_PERIOD / ns_per_us)) + 1;
fe8ab488
A
3609 }
3610 // else, child has already acked or driver has removed interest,
2d21ac55 3611 // and head_note_pendingAcks decremented.
fe8ab488 3612 // informee may have been removed from the interested drivers list,
2d21ac55
A
3613 // thus the informee must be retained across the callout.
3614
fe8ab488
A
3615 informee->release();
3616 }
2d21ac55 3617
fe8ab488 3618 fDriverCallParamCount = 0;
2d21ac55 3619
fe8ab488
A
3620 if ( fHeadNotePendingAcks )
3621 {
3622 OUR_PMLog(kPMLogStartAckTimer, 0, 0);
3623 start_ack_timer();
3624 }
3625 }
2d21ac55 3626
39236c6e 3627 MS_POP(); // pop the machine state passed to notifyAll()
6d2010ae 3628
39236c6e
A
3629 // If interest acks are outstanding, block the state machine until
3630 // fHeadNotePendingAcks drops to zero before notifying root domain.
3631 // Otherwise notify root domain directly.
2d21ac55 3632
6d2010ae
A
3633 if (!fHeadNotePendingAcks)
3634 {
39236c6e 3635 notifyRootDomain();
6d2010ae
A
3636 }
3637 else
3638 {
3639 MS_PUSH(fMachineState);
3640 fMachineState = kIOPM_NotifyChildrenStart;
6d2010ae 3641 }
2d21ac55
A
3642}
3643
39236c6e
A
3644//*********************************************************************************
3645// [private] notifyRootDomain
3646//*********************************************************************************
3647
3648void IOService::notifyRootDomain( void )
3649{
fe8ab488 3650 assert( fDriverCallBusy == false );
39236c6e
A
3651
3652 // Only for root domain in the will-change phase
3653 if (!IS_ROOT_DOMAIN || (fMachineState != kIOPM_OurChangeSetPowerState))
3654 {
3655 notifyChildren();
3656 return;
3657 }
3658
3659 MS_PUSH(fMachineState); // push notifyAll() machine state
3660 fMachineState = kIOPM_DriverThreadCallDone;
3661
22ba694c
A
3662 // Call IOPMrootDomain::willNotifyPowerChildren() on a thread call
3663 // to avoid a deadlock.
39236c6e
A
3664 fDriverCallReason = kRootDomainInformPreChange;
3665 fDriverCallBusy = true;
3666 thread_call_enter( fDriverCallEntry );
3667}
3668
3669void IOService::notifyRootDomainDone( void )
3670{
fe8ab488
A
3671 assert( fDriverCallBusy == false );
3672 assert( fMachineState == kIOPM_DriverThreadCallDone );
39236c6e
A
3673
3674 MS_POP(); // pop notifyAll() machine state
3675 notifyChildren();
3676}
3677
2d21ac55
A
3678//*********************************************************************************
3679// [private] notifyChildren
3680//*********************************************************************************
3681
39236c6e 3682void IOService::notifyChildren( void )
2d21ac55 3683{
fe8ab488
A
3684 OSIterator * iter;
3685 OSObject * next;
3686 IOPowerConnection * connection;
3687 OSArray * children = 0;
6d2010ae
A
3688 IOPMrootDomain * rootDomain;
3689 bool delayNotify = false;
fe8ab488 3690
6d2010ae
A
3691 if ((fHeadNotePowerState != fCurrentPowerState) &&
3692 (IS_POWER_DROP == fIsPreChange) &&
3693 ((rootDomain = getPMRootDomain()) == this))
3694 {
3695 rootDomain->tracePoint( IS_POWER_DROP ?
3696 kIOPMTracePointSleepPowerPlaneDrivers :
3697 kIOPMTracePointWakePowerPlaneDrivers );
3698 }
1c79356b 3699
fe8ab488
A
3700 if (fStrictTreeOrder)
3701 children = OSArray::withCapacity(8);
1c79356b 3702
2d21ac55 3703 // Sum child power consumption in notifyChild()
b0d623f7 3704 fHeadNotePowerArrayEntry->staticPower = 0;
2d21ac55
A
3705
3706 iter = getChildIterator(gIOPowerPlane);
3707 if ( iter )
3708 {
3709 while ((next = iter->getNextObject()))
55e303ae 3710 {
2d21ac55
A
3711 if ((connection = OSDynamicCast(IOPowerConnection, next)))
3712 {
fe8ab488
A
3713 if (connection->getReadyFlag() == false)
3714 {
3715 PM_LOG3("[%s] %s: connection not ready\n",
3716 getName(), __FUNCTION__);
3717 continue;
3718 }
2d21ac55 3719
6d2010ae
A
3720 // Mechanism to postpone the did-change notification to
3721 // certain power children to order those children last.
3722 // Cannot be used together with strict tree ordering.
3723
3724 if (!fIsPreChange &&
22ba694c 3725 connection->delayChildNotification &&
6d2010ae
A
3726 getPMRootDomain()->shouldDelayChildNotification(this))
3727 {
3728 if (!children)
3729 {
3730 children = OSArray::withCapacity(8);
3731 if (children)
3732 delayNotify = true;
3733 }
3734 if (delayNotify)
3735 {
3736 children->setObject( connection );
3737 continue;
3738 }
3739 }
3740
fe8ab488
A
3741 if (!delayNotify && children)
3742 children->setObject( connection );
3743 else
3744 notifyChild( connection );
3745 }
1c79356b 3746 }
2d21ac55 3747 iter->release();
1c79356b
A
3748 }
3749
6d2010ae
A
3750 if (children && (children->getCount() == 0))
3751 {
3752 children->release();
3753 children = 0;
3754 }
fe8ab488
A
3755 if (children)
3756 {
6d2010ae 3757 assert(fNotifyChildArray == 0);
fe8ab488 3758 fNotifyChildArray = children;
6d2010ae
A
3759 MS_PUSH(fMachineState);
3760
3761 if (delayNotify)
3762 {
22ba694c
A
3763 // Block until all non-delayed children have acked their
3764 // notification. Then notify the remaining delayed child
3765 // in the array. This is used to hold off graphics child
3766 // notification while the rest of the system powers up.
3767 // If a hid tickle arrives during this time, the delayed
3768 // children are immediately notified and root domain will
3769 // not clamp power for dark wake.
3770
6d2010ae
A
3771 fMachineState = kIOPM_NotifyChildrenDelayed;
3772 PM_LOG2("%s: %d children in delayed array\n",
3773 getName(), children->getCount());
3774 }
3775 else
3776 {
22ba694c 3777 // Child array created to support strict notification order.
6d2010ae 3778 // Notify children in the array one at a time.
22ba694c 3779
6d2010ae
A
3780 fMachineState = kIOPM_NotifyChildrenOrdered;
3781 }
fe8ab488 3782 }
2d21ac55 3783}
1c79356b 3784
2d21ac55 3785//*********************************************************************************
6d2010ae 3786// [private] notifyChildrenOrdered
2d21ac55 3787//*********************************************************************************
1c79356b 3788
39236c6e 3789void IOService::notifyChildrenOrdered( void )
2d21ac55 3790{
fe8ab488
A
3791 PM_ASSERT_IN_GATE();
3792 assert(fNotifyChildArray);
3793 assert(fMachineState == kIOPM_NotifyChildrenOrdered);
3794
3795 // Notify one child, wait for it to ack, then repeat for next child.
3796 // This is a workaround for some drivers with multiple instances at
3797 // the same branch in the power tree, but the driver is slow to power
3798 // up unless the tree ordering is observed. Problem observed only on
3799 // system wake, not on system sleep.
3800 //
3801 // We have the ability to power off in reverse child index order.
3802 // That works nicely on some machines, but not on all HW configs.
3803
3804 if (fNotifyChildArray->getCount())
3805 {
3806 IOPowerConnection * connection;
3807 connection = (IOPowerConnection *) fNotifyChildArray->getObject(0);
3808 notifyChild( connection );
3809 fNotifyChildArray->removeObject(0);
3810 }
3811 else
3812 {
3813 fNotifyChildArray->release();
3814 fNotifyChildArray = 0;
6d2010ae
A
3815
3816 MS_POP(); // pushed by notifyChildren()
fe8ab488 3817 }
1c79356b
A
3818}
3819
6d2010ae
A
3820//*********************************************************************************
3821// [private] notifyChildrenDelayed
3822//*********************************************************************************
3823
39236c6e 3824void IOService::notifyChildrenDelayed( void )
6d2010ae 3825{
fe8ab488 3826 IOPowerConnection * connection;
6d2010ae 3827
fe8ab488
A
3828 PM_ASSERT_IN_GATE();
3829 assert(fNotifyChildArray);
3830 assert(fMachineState == kIOPM_NotifyChildrenDelayed);
6d2010ae
A
3831
3832 // Wait after all non-delayed children and interested drivers have ack'ed,
22ba694c
A
3833 // then notify all delayed children. If notify delay is canceled, child
3834 // acks may be outstanding with PM blocked on fHeadNotePendingAcks != 0.
3835 // But the handling for either case is identical.
6d2010ae
A
3836
3837 for (int i = 0; ; i++)
3838 {
fe8ab488 3839 connection = (IOPowerConnection *) fNotifyChildArray->getObject(i);
6d2010ae
A
3840 if (!connection)
3841 break;
3842
fe8ab488 3843 notifyChild( connection );
6d2010ae
A
3844 }
3845
3846 PM_LOG2("%s: notified delayed children\n", getName());
3847 fNotifyChildArray->release();
3848 fNotifyChildArray = 0;
fe8ab488 3849
6d2010ae
A
3850 MS_POP(); // pushed by notifyChildren()
3851}
3852
1c79356b 3853//*********************************************************************************
2d21ac55 3854// [private] notifyAll
1c79356b
A
3855//*********************************************************************************
3856
39236c6e 3857IOReturn IOService::notifyAll( uint32_t nextMS )
1c79356b 3858{
fe8ab488 3859 // Save the machine state to be restored by notifyInterestedDriversDone()
1c79356b 3860
fe8ab488 3861 PM_ASSERT_IN_GATE();
6d2010ae 3862 MS_PUSH(nextMS);
fe8ab488
A
3863 fMachineState = kIOPM_DriverThreadCallDone;
3864 fDriverCallReason = fIsPreChange ?
3865 kDriverCallInformPreChange : kDriverCallInformPostChange;
6601e61a 3866
fe8ab488
A
3867 if (!notifyInterestedDrivers())
3868 notifyInterestedDriversDone();
55e303ae 3869
fe8ab488 3870 return IOPMWillAckLater;
2d21ac55 3871}
0c530ab8 3872
2d21ac55
A
3873//*********************************************************************************
3874// [private, static] pmDriverCallout
3875//
3876// Thread call context
3877//*********************************************************************************
0c530ab8 3878
39236c6e 3879IOReturn IOService::actionDriverCalloutDone(
fe8ab488
A
3880 OSObject * target,
3881 void * arg0, void * arg1,
3882 void * arg2, void * arg3 )
2d21ac55 3883{
6d2010ae 3884 IOServicePM * pwrMgt = (IOServicePM *) arg0;
0c530ab8 3885
6d2010ae
A
3886 assert( fDriverCallBusy );
3887 fDriverCallBusy = false;
1c79356b 3888
6d2010ae
A
3889 assert(gIOPMWorkQueue);
3890 gIOPMWorkQueue->signalWorkAvailable();
1c79356b 3891
6d2010ae 3892 return kIOReturnSuccess;
2d21ac55 3893}
1c79356b 3894
39236c6e 3895void IOService::pmDriverCallout( IOService * from )
2d21ac55 3896{
fe8ab488
A
3897 assert(from);
3898 switch (from->fDriverCallReason)
3899 {
3900 case kDriverCallSetPowerState:
3901 from->driverSetPowerState();
3902 break;
2d21ac55 3903
fe8ab488
A
3904 case kDriverCallInformPreChange:
3905 case kDriverCallInformPostChange:
3906 from->driverInformPowerChange();
3907 break;
2d21ac55 3908
39236c6e
A
3909 case kRootDomainInformPreChange:
3910 getPMRootDomain()->willNotifyPowerChildren(from->fHeadNotePowerState);
3911 break;
3912
fe8ab488
A
3913 default:
3914 panic("IOService::pmDriverCallout bad machine state %x",
b0d623f7 3915 from->fDriverCallReason);
fe8ab488 3916 }
2d21ac55 3917
fe8ab488
A
3918 gIOPMWorkLoop->runAction(actionDriverCalloutDone,
3919 /* target */ from,
3920 /* arg0 */ (void *) from->pwrMgt );
2d21ac55
A
3921}
3922
3923//*********************************************************************************
3924// [private] driverSetPowerState
3925//
3926// Thread call context
3927//*********************************************************************************
3928
39236c6e 3929void IOService::driverSetPowerState( void )
2d21ac55 3930{
6d2010ae 3931 IOPMPowerStateIndex powerState;
fe8ab488 3932 DriverCallParam * param;
6d2010ae 3933 IOPMDriverCallEntry callEntry;
2d21ac55 3934 AbsoluteTime end;
6d2010ae
A
3935 IOReturn result;
3936 uint32_t oldPowerState = getPowerState();
2d21ac55 3937
6d2010ae
A
3938 assert( fDriverCallBusy );
3939 assert( fDriverCallParamPtr );
3940 assert( fDriverCallParamCount == 1 );
2d21ac55 3941
6d2010ae
A
3942 param = (DriverCallParam *) fDriverCallParamPtr;
3943 powerState = fHeadNotePowerState;
2d21ac55 3944
6d2010ae
A
3945 if (assertPMDriverCall(&callEntry))
3946 {
3947 OUR_PMLog( kPMLogProgramHardware, (uintptr_t) this, powerState);
3e170ce0 3948 start_spindump_timer("SetState");
2d21ac55 3949 clock_get_uptime(&fDriverCallStartTime);
6d2010ae 3950 result = fControllingDriver->setPowerState( powerState, this );
2d21ac55 3951 clock_get_uptime(&end);
3e170ce0 3952 stop_spindump_timer();
6d2010ae
A
3953 OUR_PMLog((UInt32) -kPMLogProgramHardware, (uintptr_t) this, (UInt32) result);
3954
3955 deassertPMDriverCall(&callEntry);
3956
fe8ab488
A
3957 // Record the most recent max power state residency timings.
3958 // Use with DeviceActiveTimestamp to diagnose tickle issues.
3959 if (powerState == fHighestPowerState)
3960 fMaxPowerStateEntryTime = end;
3961 else if (oldPowerState == fHighestPowerState)
3962 fMaxPowerStateExitTime = end;
3963
6d2010ae
A
3964 if (result < 0)
3965 {
3966 PM_LOG("%s::setPowerState(%p, %lu -> %lu) returned 0x%x\n",
fe8ab488 3967 fName, OBFUSCATE(this), fCurrentPowerState, powerState, result);
6d2010ae 3968 }
2d21ac55
A
3969
3970#if LOG_SETPOWER_TIMES
3971 if ((result == IOPMAckImplied) || (result < 0))
55e303ae 3972 {
2d21ac55 3973 uint64_t nsec;
0c530ab8 3974
2d21ac55
A
3975 SUB_ABSOLUTETIME(&end, &fDriverCallStartTime);
3976 absolutetime_to_nanoseconds(end, &nsec);
fe8ab488
A
3977 if (nsec > LOG_SETPOWER_TIMES) {
3978 getPMRootDomain()->pmStatsRecordApplicationResponse(
3979 gIOPMStatsDriverPSChangeSlow,
3980 fName, kDriverCallSetPowerState, NS_TO_MS(nsec), 0, NULL, powerState);
3981 }
1c79356b 3982 }
2d21ac55 3983#endif
6d2010ae
A
3984 }
3985 else
3986 result = kIOPMAckImplied;
1c79356b 3987
6d2010ae 3988 param->Result = result;
2d21ac55 3989}
55e303ae 3990
2d21ac55
A
3991//*********************************************************************************
3992// [private] driverInformPowerChange
3993//
3994// Thread call context
3995//*********************************************************************************
0c530ab8 3996
39236c6e 3997void IOService::driverInformPowerChange( void )
2d21ac55 3998{
fe8ab488
A
3999 IOPMinformee * informee;
4000 IOService * driver;
4001 DriverCallParam * param;
6d2010ae 4002 IOPMDriverCallEntry callEntry;
fe8ab488 4003 IOPMPowerFlags powerFlags;
6d2010ae 4004 IOPMPowerStateIndex powerState;
2d21ac55 4005 AbsoluteTime end;
6d2010ae 4006 IOReturn result;
fe8ab488 4007 IOItemCount count;
2d21ac55 4008
6d2010ae
A
4009 assert( fDriverCallBusy );
4010 assert( fDriverCallParamPtr );
4011 assert( fDriverCallParamCount );
2d21ac55 4012
6d2010ae
A
4013 param = (DriverCallParam *) fDriverCallParamPtr;
4014 count = fDriverCallParamCount;
2d21ac55 4015
6d2010ae
A
4016 powerFlags = fHeadNotePowerArrayEntry->capabilityFlags;
4017 powerState = fHeadNotePowerState;
2d21ac55 4018
6d2010ae
A
4019 for (IOItemCount i = 0; i < count; i++)
4020 {
4021 informee = (IOPMinformee *) param->Target;
4022 driver = informee->whatObject;
4023
4024 if (assertPMDriverCall(&callEntry, 0, informee))
4025 {
4026 if (fDriverCallReason == kDriverCallInformPreChange)
4027 {
4028 OUR_PMLog(kPMLogInformDriverPreChange, (uintptr_t) this, powerState);
3e170ce0 4029 start_spindump_timer("WillChange");
2d21ac55 4030 clock_get_uptime(&informee->startTime);
6d2010ae 4031 result = driver->powerStateWillChangeTo(powerFlags, powerState, this);
2d21ac55 4032 clock_get_uptime(&end);
3e170ce0 4033 stop_spindump_timer();
6d2010ae
A
4034 OUR_PMLog((UInt32)-kPMLogInformDriverPreChange, (uintptr_t) this, result);
4035 }
4036 else
4037 {
4038 OUR_PMLog(kPMLogInformDriverPostChange, (uintptr_t) this, powerState);
3e170ce0 4039 start_spindump_timer("DidChange");
6d2010ae
A
4040 clock_get_uptime(&informee->startTime);
4041 result = driver->powerStateDidChangeTo(powerFlags, powerState, this);
4042 clock_get_uptime(&end);
3e170ce0 4043 stop_spindump_timer();
6d2010ae
A
4044 OUR_PMLog((UInt32)-kPMLogInformDriverPostChange, (uintptr_t) this, result);
4045 }
fe8ab488 4046
6d2010ae 4047 deassertPMDriverCall(&callEntry);
2d21ac55
A
4048
4049#if LOG_SETPOWER_TIMES
4050 if ((result == IOPMAckImplied) || (result < 0))
4051 {
4052 uint64_t nsec;
4053
4054 SUB_ABSOLUTETIME(&end, &informee->startTime);
4055 absolutetime_to_nanoseconds(end, &nsec);
fe8ab488
A
4056 if (nsec > LOG_SETPOWER_TIMES) {
4057 getPMRootDomain()->pmStatsRecordApplicationResponse(
4058 gIOPMStatsDriverPSChangeSlow, driver->getName(),
4059 fDriverCallReason, NS_TO_MS(nsec), 0, NULL, powerState);
4060 }
2d21ac55
A
4061 }
4062#endif
6d2010ae
A
4063 }
4064 else
4065 result = kIOPMAckImplied;
0c530ab8 4066
6d2010ae
A
4067 param->Result = result;
4068 param++;
4069 }
1c79356b
A
4070}
4071
1c79356b 4072//*********************************************************************************
2d21ac55 4073// [private] notifyChild
1c79356b
A
4074//
4075// Notify a power domain child of an upcoming power change.
1c79356b
A
4076// If the object acknowledges the current change, we return TRUE.
4077//*********************************************************************************
4078
39236c6e 4079bool IOService::notifyChild( IOPowerConnection * theNub )
1c79356b 4080{
6d2010ae
A
4081 IOReturn ret = IOPMAckImplied;
4082 unsigned long childPower;
4083 IOService * theChild;
fe8ab488 4084 IOPMRequest * childRequest;
6d2010ae 4085 IOPMPowerChangeFlags requestArg2;
fe8ab488 4086 int requestType;
2d21ac55 4087
fe8ab488 4088 PM_ASSERT_IN_GATE();
3a60a9f5 4089 theChild = (IOService *)(theNub->copyChildEntry(gIOPowerPlane));
2d21ac55 4090 if (!theChild)
55e303ae 4091 {
0b4e3aa0 4092 return true;
55e303ae 4093 }
2d21ac55 4094
3a60a9f5
A
4095 // Unless the child handles the notification immediately and returns
4096 // kIOPMAckImplied, we'll be awaiting their acknowledgement later.
fe8ab488 4097 fHeadNotePendingAcks++;
3a60a9f5 4098 theNub->setAwaitingAck(true);
b0d623f7 4099
6d2010ae 4100 requestArg2 = fHeadNoteChangeFlags;
39236c6e 4101 if (StateOrder(fHeadNotePowerState) < StateOrder(fCurrentPowerState))
b0d623f7
A
4102 requestArg2 |= kIOPMDomainPowerDrop;
4103
6d2010ae 4104 requestType = fIsPreChange ?
b0d623f7
A
4105 kIOPMRequestTypePowerDomainWillChange :
4106 kIOPMRequestTypePowerDomainDidChange;
2d21ac55 4107
fe8ab488
A
4108 childRequest = acquirePMRequest( theChild, requestType );
4109 if (childRequest)
4110 {
cf7d32b8 4111 theNub->retain();
fe8ab488
A
4112 childRequest->fArg0 = (void *) fHeadNotePowerArrayEntry->outputPowerFlags;
4113 childRequest->fArg1 = (void *) theNub;
4114 childRequest->fArg2 = (void *)(uintptr_t) requestArg2;
4115 theChild->submitPMRequest( childRequest );
4116 ret = IOPMWillAckLater;
4117 }
4118 else
4119 {
4120 ret = IOPMAckImplied;
4121 fHeadNotePendingAcks--;
4122 theNub->setAwaitingAck(false);
0b4e3aa0 4123 childPower = theChild->currentPowerConsumption();
2d21ac55 4124 if ( childPower == kIOPMUnknown )
55e303ae 4125 {
b0d623f7 4126 fHeadNotePowerArrayEntry->staticPower = kIOPMUnknown;
55e303ae 4127 } else {
b0d623f7
A
4128 if (fHeadNotePowerArrayEntry->staticPower != kIOPMUnknown )
4129 fHeadNotePowerArrayEntry->staticPower += childPower;
0b4e3aa0 4130 }
55e303ae 4131 }
55e303ae 4132
2d21ac55 4133 theChild->release();
fe8ab488 4134 return (IOPMAckImplied == ret);
1c79356b
A
4135}
4136
6d2010ae
A
4137//*********************************************************************************
4138// [private] notifyControllingDriver
4139//*********************************************************************************
4140
39236c6e 4141bool IOService::notifyControllingDriver( void )
6d2010ae 4142{
fe8ab488 4143 DriverCallParam * param;
6d2010ae
A
4144
4145 PM_ASSERT_IN_GATE();
4146 assert( fDriverCallParamCount == 0 );
4147 assert( fControllingDriver );
4148
4149 if (fInitialSetPowerState)
4150 {
316670eb
A
4151 fInitialSetPowerState = false;
4152 fHeadNoteChangeFlags |= kIOPMInitialPowerChange;
4153
6d2010ae
A
4154 // Driver specified flag to skip the inital setPowerState()
4155 if (fHeadNotePowerArrayEntry->capabilityFlags & kIOPMInitialDeviceState)
4156 {
4157 return false;
4158 }
6d2010ae
A
4159 }
4160
4161 param = (DriverCallParam *) fDriverCallParamPtr;
4162 if (!param)
4163 {
4164 param = IONew(DriverCallParam, 1);
4165 if (!param)
fe8ab488 4166 return false; // no memory
6d2010ae
A
4167
4168 fDriverCallParamPtr = (void *) param;
4169 fDriverCallParamSlots = 1;
4170 }
4171
4172 param->Target = fControllingDriver;
4173 fDriverCallParamCount = 1;
4174 fDriverTimer = -1;
4175
4176 // Block state machine and wait for callout completion.
4177 assert(!fDriverCallBusy);
4178 fDriverCallBusy = true;
4179 thread_call_enter( fDriverCallEntry );
4180
4181 return true;
4182}
4183
4184//*********************************************************************************
4185// [private] notifyControllingDriverDone
4186//*********************************************************************************
4187
4188void IOService::notifyControllingDriverDone( void )
4189{
fe8ab488
A
4190 DriverCallParam * param;
4191 IOReturn result;
4192
4193 PM_ASSERT_IN_GATE();
4194 param = (DriverCallParam *) fDriverCallParamPtr;
6d2010ae 4195
fe8ab488
A
4196 assert( fDriverCallBusy == false );
4197 assert( fMachineState == kIOPM_DriverThreadCallDone );
6d2010ae 4198
fe8ab488
A
4199 if (param && fDriverCallParamCount)
4200 {
4201 assert(fDriverCallParamCount == 1);
6d2010ae 4202
fe8ab488
A
4203 // the return value from setPowerState()
4204 result = param->Result;
6d2010ae 4205
fe8ab488
A
4206 if ((result == IOPMAckImplied) || (result < 0))
4207 {
6d2010ae 4208 fDriverTimer = 0;
fe8ab488
A
4209 }
4210 else if (fDriverTimer)
4211 {
6d2010ae
A
4212 assert(fDriverTimer == -1);
4213
4214 // Driver has not acked, and has returned a positive result.
4215 // Enforce a minimum permissible timeout value.
4216 // Make the min value large enough so timeout is less likely
4217 // to occur if a driver misinterpreted that the return value
4218 // should be in microsecond units. And make it large enough
4219 // to be noticeable if a driver neglects to ack.
4220
4221 if (result < kMinAckTimeoutTicks)
4222 result = kMinAckTimeoutTicks;
4223
4224 fDriverTimer = (result / (ACK_TIMER_PERIOD / ns_per_us)) + 1;
fe8ab488
A
4225 }
4226 // else, child has already acked and driver_timer reset to 0.
6d2010ae 4227
fe8ab488 4228 fDriverCallParamCount = 0;
6d2010ae 4229
fe8ab488
A
4230 if ( fDriverTimer )
4231 {
4232 OUR_PMLog(kPMLogStartAckTimer, 0, 0);
4233 start_ack_timer();
4234 }
4235 }
6d2010ae
A
4236
4237 MS_POP(); // pushed by OurChangeSetPowerState()
4238 fIsPreChange = false;
4239}
4240
4241//*********************************************************************************
4242// [private] all_done
4243//
4244// A power change is done.
4245//*********************************************************************************
4246
39236c6e 4247void IOService::all_done( void )
6d2010ae
A
4248{
4249 IOPMPowerStateIndex prevPowerState;
4250 const IOPMPSEntry * powerStatePtr;
4251 IOPMDriverCallEntry callEntry;
4252 uint32_t prevMachineState = fMachineState;
3e170ce0 4253 bool actionCalled = false;
39236c6e 4254 uint64_t ts;
6d2010ae
A
4255
4256 fMachineState = kIOPM_Finished;
4257
4258 if ((fHeadNoteChangeFlags & kIOPMSynchronize) &&
4259 ((prevMachineState == kIOPM_Finished) ||
4260 (prevMachineState == kIOPM_SyncFinish)))
4261 {
4262 // Sync operation and no power change occurred.
4263 // Do not inform driver and clients about this request completion,
4264 // except for the originator (root domain).
4265
4266 PM_ACTION_2(actionPowerChangeDone,
4267 fHeadNotePowerState, fHeadNoteChangeFlags);
4268
4269 if (getPMRequestType() == kIOPMRequestTypeSynchronizePowerTree)
4270 {
4271 powerChangeDone(fCurrentPowerState);
4272 }
db609669
A
4273 else if (fAdvisoryTickleUsed)
4274 {
bd504ef0 4275 // Not root domain and advisory tickle target.
db609669 4276 // Re-adjust power after power tree sync at the 'did' pass
bd504ef0
A
4277 // to recompute desire and adjust power state between dark
4278 // and full wake transitions. Root domain is responsible
4279 // for calling setAdvisoryTickleEnable() before starting
4280 // the kIOPMSynchronize power change.
4281
db609669
A
4282 if (!fAdjustPowerScheduled &&
4283 (fHeadNoteChangeFlags & kIOPMDomainDidChange))
4284 {
4285 IOPMRequest * request;
4286 request = acquirePMRequest( this, kIOPMRequestTypeAdjustPowerState );
4287 if (request)
4288 {
4289 submitPMRequest( request );
4290 fAdjustPowerScheduled = true;
4291 }
4292 }
4293 }
6d2010ae
A
4294
4295 return;
4296 }
4297
4298 // our power change
3e170ce0 4299 if (fHeadNoteChangeFlags & kIOPMSelfInitiated)
6d2010ae 4300 {
3e170ce0
A
4301 // power state changed
4302 if ((fHeadNoteChangeFlags & kIOPMNotDone) == 0)
6d2010ae 4303 {
316670eb
A
4304 trackSystemSleepPreventers(
4305 fCurrentPowerState, fHeadNotePowerState, fHeadNoteChangeFlags);
4306
fe8ab488 4307 // we changed, tell our parent
6d2010ae
A
4308 requestDomainPower(fHeadNotePowerState);
4309
4310 // yes, did power raise?
39236c6e 4311 if ( StateOrder(fCurrentPowerState) < StateOrder(fHeadNotePowerState) )
6d2010ae
A
4312 {
4313 // yes, inform clients and apps
4314 tellChangeUp (fHeadNotePowerState);
4315 }
4316 prevPowerState = fCurrentPowerState;
4317 // either way
4318 fCurrentPowerState = fHeadNotePowerState;
39236c6e
A
4319 PM_LOCK();
4320 if (fReportBuf) {
4321 ts = mach_absolute_time();
4322 STATEREPORT_SETSTATE(fReportBuf, fCurrentPowerState, ts);
4323 }
4324 PM_UNLOCK();
6d2010ae
A
4325#if PM_VARS_SUPPORT
4326 fPMVars->myCurrentState = fCurrentPowerState;
4327#endif
4b17d6b6 4328 OUR_PMLog(kPMLogChangeDone, fCurrentPowerState, prevPowerState);
6d2010ae
A
4329 PM_ACTION_2(actionPowerChangeDone,
4330 fHeadNotePowerState, fHeadNoteChangeFlags);
3e170ce0 4331 actionCalled = true;
6d2010ae
A
4332
4333 powerStatePtr = &fPowerStates[fCurrentPowerState];
4334 fCurrentCapabilityFlags = powerStatePtr->capabilityFlags;
4335 if (fCurrentCapabilityFlags & kIOPMStaticPowerValid)
4336 fCurrentPowerConsumption = powerStatePtr->staticPower;
4337
bd504ef0
A
4338 if (fHeadNoteChangeFlags & kIOPMRootChangeDown)
4339 {
4340 // Bump tickle generation count once the entire tree is down
4341 gIOPMTickleGeneration++;
4342 }
4343
6d2010ae
A
4344 // inform subclass policy-maker
4345 if (fPCDFunctionOverride && fParentsKnowState &&
4346 assertPMDriverCall(&callEntry, kIOPMADC_NoInactiveCheck))
4347 {
4348 powerChangeDone(prevPowerState);
4349 deassertPMDriverCall(&callEntry);
4350 }
4351 }
4352 else if (getPMRequestType() == kIOPMRequestTypeRequestPowerStateOverride)
4353 {
4354 // changePowerStateWithOverrideTo() was cancelled
4355 fOverrideMaxPowerState = kIOPMPowerStateMax;
4356 }
4357 }
4358
3e170ce0
A
4359 // parent-initiated power change
4360 if (fHeadNoteChangeFlags & kIOPMParentInitiated)
6d2010ae 4361 {
bd504ef0
A
4362 if (fHeadNoteChangeFlags & kIOPMRootChangeDown)
4363 ParentChangeRootChangeDown();
fe8ab488 4364
3e170ce0
A
4365 // power state changed
4366 if ((fHeadNoteChangeFlags & kIOPMNotDone) == 0)
6d2010ae 4367 {
316670eb
A
4368 trackSystemSleepPreventers(
4369 fCurrentPowerState, fHeadNotePowerState, fHeadNoteChangeFlags);
7ee9d059 4370
6d2010ae 4371 // did power raise?
39236c6e 4372 if ( StateOrder(fCurrentPowerState) < StateOrder(fHeadNotePowerState) )
6d2010ae
A
4373 {
4374 // yes, inform clients and apps
4375 tellChangeUp (fHeadNotePowerState);
4376 }
4377 // either way
4378 prevPowerState = fCurrentPowerState;
4379 fCurrentPowerState = fHeadNotePowerState;
39236c6e
A
4380 PM_LOCK();
4381 if (fReportBuf) {
4382 ts = mach_absolute_time();
4383 STATEREPORT_SETSTATE(fReportBuf, fCurrentPowerState, ts);
4384 }
4385 PM_UNLOCK();
6d2010ae
A
4386#if PM_VARS_SUPPORT
4387 fPMVars->myCurrentState = fCurrentPowerState;
4388#endif
6d2010ae 4389
4b17d6b6 4390 OUR_PMLog(kPMLogChangeDone, fCurrentPowerState, prevPowerState);
6d2010ae
A
4391 PM_ACTION_2(actionPowerChangeDone,
4392 fHeadNotePowerState, fHeadNoteChangeFlags);
3e170ce0 4393 actionCalled = true;
6d2010ae
A
4394
4395 powerStatePtr = &fPowerStates[fCurrentPowerState];
4396 fCurrentCapabilityFlags = powerStatePtr->capabilityFlags;
4397 if (fCurrentCapabilityFlags & kIOPMStaticPowerValid)
4398 fCurrentPowerConsumption = powerStatePtr->staticPower;
4399
4400 // inform subclass policy-maker
4401 if (fPCDFunctionOverride && fParentsKnowState &&
4402 assertPMDriverCall(&callEntry, kIOPMADC_NoInactiveCheck))
4403 {
4404 powerChangeDone(prevPowerState);
4405 deassertPMDriverCall(&callEntry);
4406 }
4407 }
4408 }
4409
4410 // When power rises enough to satisfy the tickle's desire for more power,
4411 // the condition preventing idle-timer from dropping power is removed.
4412
39236c6e 4413 if (StateOrder(fCurrentPowerState) >= StateOrder(fIdleTimerMinPowerState))
6d2010ae 4414 {
39236c6e 4415 fIdleTimerMinPowerState = kPowerStateZero;
6d2010ae
A
4416 }
4417
3e170ce0 4418 if (!actionCalled)
6d2010ae
A
4419 {
4420 PM_ACTION_2(actionPowerChangeDone,
4421 fHeadNotePowerState, fHeadNoteChangeFlags);
4422 }
4423}
4424
7e4a7d39
A
4425// MARK: -
4426// MARK: Power Change Initiated by Driver
4427
4428//*********************************************************************************
4429// [private] OurChangeStart
4430//
4431// Begin the processing of a power change initiated by us.
4432//*********************************************************************************
4433
39236c6e 4434void IOService::OurChangeStart( void )
7e4a7d39 4435{
fe8ab488 4436 PM_ASSERT_IN_GATE();
7e4a7d39
A
4437 OUR_PMLog( kPMLogStartDeviceChange, fHeadNotePowerState, fCurrentPowerState );
4438
fe8ab488
A
4439 // fMaxPowerState is our maximum possible power state based on the current
4440 // power state of our parents. If we are trying to raise power beyond the
4441 // maximum, send an async request for more power to all parents.
7e4a7d39 4442
39236c6e 4443 if (!IS_PM_ROOT && (StateOrder(fMaxPowerState) < StateOrder(fHeadNotePowerState)))
7e4a7d39 4444 {
6d2010ae 4445 fHeadNoteChangeFlags |= kIOPMNotDone;
7e4a7d39
A
4446 requestDomainPower(fHeadNotePowerState);
4447 OurChangeFinish();
4448 return;
4449 }
4450
fe8ab488 4451 // Redundant power changes skips to the end of the state machine.
7e4a7d39 4452
6d2010ae 4453 if (!fInitialPowerChange && (fHeadNotePowerState == fCurrentPowerState))
fe8ab488
A
4454 {
4455 OurChangeFinish();
4456 return;
7e4a7d39 4457 }
6d2010ae 4458 fInitialPowerChange = false;
7e4a7d39 4459
7e4a7d39
A
4460 // Change started, but may not complete...
4461 // Can be canceled (power drop) or deferred (power rise).
4462
6d2010ae 4463 PM_ACTION_2(actionPowerChangeStart, fHeadNotePowerState, &fHeadNoteChangeFlags);
7e4a7d39 4464
fe8ab488
A
4465 // Two separate paths, depending if power is being raised or lowered.
4466 // Lowering power is subject to approval by clients of this service.
7e4a7d39
A
4467
4468 if (IS_POWER_DROP)
4469 {
7e4a7d39
A
4470 fDoNotPowerDown = false;
4471
6d2010ae
A
4472 // Ask for persmission to drop power state
4473 fMachineState = kIOPM_OurChangeTellClientsPowerDown;
7e4a7d39 4474 fOutOfBandParameter = kNotifyApps;
6d2010ae 4475 askChangeDown(fHeadNotePowerState);
7e4a7d39 4476 }
fe8ab488
A
4477 else
4478 {
7e4a7d39
A
4479 // This service is raising power and parents are able to support the
4480 // new power state. However a parent may have already committed to
4481 // drop power, which might force this object to temporarily drop power.
4482 // This results in "oscillations" before the state machines converge
4483 // to a steady state.
4484 //
4485 // To prevent this, a child must make a power reservation against all
4486 // parents before raising power. If the reservation fails, indicating
4487 // that the child will be unable to sustain the higher power state,
4488 // then the child will signal the parent to adjust power, and the child
4489 // will defer its power change.
4490
7e4a7d39
A
4491 IOReturn ret;
4492
4493 // Reserve parent power necessary to achieve fHeadNotePowerState.
4494 ret = requestDomainPower( fHeadNotePowerState, kReserveDomainPower );
4495 if (ret != kIOReturnSuccess)
4496 {
4497 // Reservation failed, defer power rise.
6d2010ae 4498 fHeadNoteChangeFlags |= kIOPMNotDone;
7e4a7d39
A
4499 OurChangeFinish();
4500 return;
4501 }
6d2010ae
A
4502
4503 OurChangeTellCapabilityWillChange();
7e4a7d39
A
4504 }
4505}
4506
bd504ef0
A
4507//*********************************************************************************
4508// [private] requestDomainPowerApplier
4509//
4510// Call requestPowerDomainState() on all power parents.
7e4a7d39
A
4511//*********************************************************************************
4512
4513struct IOPMRequestDomainPowerContext {
4514 IOService * child; // the requesting child
4515 IOPMPowerFlags requestPowerFlags; // power flags requested by child
4516};
4517
4518static void
4519requestDomainPowerApplier(
4520 IORegistryEntry * entry,
4521 void * inContext )
4522{
4523 IOPowerConnection * connection;
4524 IOService * parent;
4525 IOPMRequestDomainPowerContext * context;
4526
4527 if ((connection = OSDynamicCast(IOPowerConnection, entry)) == 0)
4528 return;
4529 parent = (IOService *) connection->copyParentEntry(gIOPowerPlane);
4530 if (!parent)
4531 return;
4532
4533 assert(inContext);
4534 context = (IOPMRequestDomainPowerContext *) inContext;
4535
4536 if (connection->parentKnowsState() && connection->getReadyFlag())
4537 {
4538 parent->requestPowerDomainState(
4539 context->requestPowerFlags,
4540 connection,
4541 IOPMLowestState);
4542 }
4543
4544 parent->release();
4545}
4546
4547//*********************************************************************************
4548// [private] requestDomainPower
bd504ef0
A
4549//
4550// Called by a power child to broadcast its desired power state to all parents.
4551// If the child self-initiates a power change, it must call this function to
4552// allow its parents to adjust power state.
7e4a7d39
A
4553//*********************************************************************************
4554
4555IOReturn IOService::requestDomainPower(
6d2010ae
A
4556 IOPMPowerStateIndex ourPowerState,
4557 IOOptionBits options )
7e4a7d39 4558{
7e4a7d39 4559 IOPMPowerFlags requestPowerFlags;
6d2010ae 4560 IOPMPowerStateIndex maxPowerState;
7e4a7d39
A
4561 IOPMRequestDomainPowerContext context;
4562
fe8ab488 4563 PM_ASSERT_IN_GATE();
7e4a7d39
A
4564 assert(ourPowerState < fNumberOfPowerStates);
4565 if (ourPowerState >= fNumberOfPowerStates)
4566 return kIOReturnBadArgument;
6d2010ae 4567 if (IS_PM_ROOT)
7e4a7d39
A
4568 return kIOReturnSuccess;
4569
bd504ef0 4570 // Fetch our input power flags for the requested power state.
7e4a7d39
A
4571 // Parent request is stated in terms of required power flags.
4572
fe8ab488 4573 requestPowerFlags = fPowerStates[ourPowerState].inputPowerFlags;
7e4a7d39
A
4574
4575 // Disregard the "previous request" for power reservation.
4576
4577 if (((options & kReserveDomainPower) == 0) &&
6d2010ae 4578 (fPreviousRequestPowerFlags == requestPowerFlags))
7e4a7d39
A
4579 {
4580 // skip if domain already knows our requirements
4581 goto done;
4582 }
6d2010ae 4583 fPreviousRequestPowerFlags = requestPowerFlags;
7e4a7d39 4584
bd504ef0 4585 // The results will be collected by fHeadNoteDomainTargetFlags
7e4a7d39
A
4586 context.child = this;
4587 context.requestPowerFlags = requestPowerFlags;
4588 fHeadNoteDomainTargetFlags = 0;
4589 applyToParents(requestDomainPowerApplier, &context, gIOPowerPlane);
4590
4591 if (options & kReserveDomainPower)
4592 {
4593 maxPowerState = fControllingDriver->maxCapabilityForDomainState(
4594 fHeadNoteDomainTargetFlags );
4595
39236c6e 4596 if (StateOrder(maxPowerState) < StateOrder(ourPowerState))
7e4a7d39 4597 {
6d2010ae 4598 PM_LOG1("%s: power desired %u:0x%x got %u:0x%x\n",
7e4a7d39
A
4599 getName(),
4600 (uint32_t) ourPowerState, (uint32_t) requestPowerFlags,
4601 (uint32_t) maxPowerState, (uint32_t) fHeadNoteDomainTargetFlags);
4602 return kIOReturnNoPower;
4603 }
4604 }
4605
4606done:
4607 return kIOReturnSuccess;
4608}
4609
4610//*********************************************************************************
4611// [private] OurSyncStart
4612//*********************************************************************************
4613
39236c6e 4614void IOService::OurSyncStart( void )
7e4a7d39 4615{
fe8ab488 4616 PM_ASSERT_IN_GATE();
7e4a7d39 4617
6d2010ae 4618 if (fInitialPowerChange)
7e4a7d39
A
4619 return;
4620
6d2010ae
A
4621 PM_ACTION_2(actionPowerChangeStart, fHeadNotePowerState, &fHeadNoteChangeFlags);
4622
4623 if (fHeadNoteChangeFlags & kIOPMNotDone)
4624 {
fe8ab488
A
4625 OurChangeFinish();
4626 return;
6d2010ae 4627 }
7e4a7d39 4628
6d2010ae
A
4629 if (fHeadNoteChangeFlags & kIOPMSyncTellPowerDown)
4630 {
4631 fDoNotPowerDown = false;
7e4a7d39 4632
6d2010ae
A
4633 // Ask for permission to drop power state
4634 fMachineState = kIOPM_SyncTellClientsPowerDown;
4635 fOutOfBandParameter = kNotifyApps;
4636 askChangeDown(fHeadNotePowerState);
4637 }
4638 else
4639 {
4640 // Only inform capability app and clients.
4641 tellSystemCapabilityChange( kIOPM_SyncNotifyWillChange );
4642 }
7e4a7d39
A
4643}
4644
1c79356b 4645//*********************************************************************************
2d21ac55 4646// [private] OurChangeTellClientsPowerDown
1c79356b 4647//
6d2010ae 4648// All applications and kernel clients have acknowledged our permission to drop
fe8ab488 4649// power. Here we notify them that we will lower the power and wait for acks.
1c79356b
A
4650//*********************************************************************************
4651
39236c6e 4652void IOService::OurChangeTellClientsPowerDown( void )
0b4e3aa0 4653{
39236c6e
A
4654 if(!IS_ROOT_DOMAIN)
4655 fMachineState = kIOPM_OurChangeTellPriorityClientsPowerDown;
4656 else
4657 {
4658 fMachineState = kIOPM_OurChangeTellUserPMPolicyPowerDown;
4659 }
b0d623f7 4660 tellChangeDown1(fHeadNotePowerState);
0b4e3aa0
A
4661}
4662
39236c6e
A
4663//*********************************************************************************
4664// [private] OurChangeTellUserPMPolicyPowerDown
4665//
4666// All applications and kernel clients have acknowledged our permission to drop
4667// power. Here we notify power management policy in user-space and wait for acks
4668// one last time before we lower power
4669//*********************************************************************************
4670void IOService::OurChangeTellUserPMPolicyPowerDown ( void )
4671{
4672 fMachineState = kIOPM_OurChangeTellPriorityClientsPowerDown;
4673 fOutOfBandParameter = kNotifyApps;
4674
4675 tellClientsWithResponse(kIOPMMessageLastCallBeforeSleep);
4676}
4677
0b4e3aa0 4678//*********************************************************************************
2d21ac55 4679// [private] OurChangeTellPriorityClientsPowerDown
0b4e3aa0 4680//
6d2010ae
A
4681// All applications and kernel clients have acknowledged our intention to drop
4682// power. Here we notify "priority" clients that we are lowering power.
0b4e3aa0
A
4683//*********************************************************************************
4684
39236c6e 4685void IOService::OurChangeTellPriorityClientsPowerDown( void )
1c79356b 4686{
2d21ac55 4687 fMachineState = kIOPM_OurChangeNotifyInterestedDriversWillChange;
b0d623f7 4688 tellChangeDown2(fHeadNotePowerState);
1c79356b
A
4689}
4690
6d2010ae
A
4691//*********************************************************************************
4692// [private] OurChangeTellCapabilityWillChange
4693//
4694// Extra stage for root domain to notify apps and drivers about the
4695// system capability change when raising power state.
4696//*********************************************************************************
4697
39236c6e 4698void IOService::OurChangeTellCapabilityWillChange( void )
6d2010ae
A
4699{
4700 if (!IS_ROOT_DOMAIN)
4701 return OurChangeNotifyInterestedDriversWillChange();
4702
4703 tellSystemCapabilityChange( kIOPM_OurChangeNotifyInterestedDriversWillChange );
4704}
4705
1c79356b 4706//*********************************************************************************
2d21ac55 4707// [private] OurChangeNotifyInterestedDriversWillChange
1c79356b 4708//
6d2010ae
A
4709// All applications and kernel clients have acknowledged our power state change.
4710// Here we notify interested drivers pre-change.
1c79356b
A
4711//*********************************************************************************
4712
39236c6e 4713void IOService::OurChangeNotifyInterestedDriversWillChange( void )
1c79356b 4714{
6d2010ae 4715 IOPMrootDomain * rootDomain;
b0d623f7
A
4716 if ((rootDomain = getPMRootDomain()) == this)
4717 {
6d2010ae
A
4718 if (IS_POWER_DROP)
4719 {
4720 rootDomain->tracePoint( kIOPMTracePointSleepWillChangeInterests );
6d2010ae
A
4721 }
4722 else
4723 rootDomain->tracePoint( kIOPMTracePointWakeWillChangeInterests );
b0d623f7
A
4724 }
4725
6d2010ae 4726 notifyAll( kIOPM_OurChangeSetPowerState );
1c79356b
A
4727}
4728
1c79356b 4729//*********************************************************************************
2d21ac55 4730// [private] OurChangeSetPowerState
1c79356b 4731//
6d2010ae
A
4732// Instruct our controlling driver to program the hardware for the power state
4733// change. Wait for async completions.
1c79356b
A
4734//*********************************************************************************
4735
39236c6e 4736void IOService::OurChangeSetPowerState( void )
1c79356b 4737{
6d2010ae
A
4738 MS_PUSH( kIOPM_OurChangeWaitForPowerSettle );
4739 fMachineState = kIOPM_DriverThreadCallDone;
4740 fDriverCallReason = kDriverCallSetPowerState;
55e303ae 4741
6d2010ae
A
4742 if (notifyControllingDriver() == false)
4743 notifyControllingDriverDone();
1c79356b
A
4744}
4745
1c79356b 4746//*********************************************************************************
2d21ac55 4747// [private] OurChangeWaitForPowerSettle
1c79356b 4748//
6d2010ae
A
4749// Our controlling driver has completed the power state change we initiated.
4750// Wait for the driver specified settle time to expire.
1c79356b
A
4751//*********************************************************************************
4752
39236c6e 4753void IOService::OurChangeWaitForPowerSettle( void )
1c79356b 4754{
6d2010ae 4755 fMachineState = kIOPM_OurChangeNotifyInterestedDriversDidChange;
7e4a7d39 4756 startSettleTimer();
1c79356b
A
4757}
4758
1c79356b 4759//*********************************************************************************
2d21ac55 4760// [private] OurChangeNotifyInterestedDriversDidChange
1c79356b 4761//
6d2010ae
A
4762// Power has settled on a power change we initiated. Here we notify
4763// all our interested drivers post-change.
1c79356b
A
4764//*********************************************************************************
4765
39236c6e 4766void IOService::OurChangeNotifyInterestedDriversDidChange( void )
1c79356b 4767{
6d2010ae
A
4768 IOPMrootDomain * rootDomain;
4769 if ((rootDomain = getPMRootDomain()) == this)
4770 {
4771 rootDomain->tracePoint( IS_POWER_DROP ?
4772 kIOPMTracePointSleepDidChangeInterests :
4773 kIOPMTracePointWakeDidChangeInterests );
4774 }
4775
4776 notifyAll( kIOPM_OurChangeTellCapabilityDidChange );
4777}
4778
4779//*********************************************************************************
4780// [private] OurChangeTellCapabilityDidChange
4781//
4782// For root domain to notify capability power-change.
4783//*********************************************************************************
4784
39236c6e 4785void IOService::OurChangeTellCapabilityDidChange( void )
6d2010ae
A
4786{
4787 if (!IS_ROOT_DOMAIN)
4788 return OurChangeFinish();
4789
4790 getPMRootDomain()->tracePoint( IS_POWER_DROP ?
4791 kIOPMTracePointSleepCapabilityClients :
4792 kIOPMTracePointWakeCapabilityClients );
4793
4794 tellSystemCapabilityChange( kIOPM_OurChangeFinish );
1c79356b
A
4795}
4796
1c79356b 4797//*********************************************************************************
2d21ac55 4798// [private] OurChangeFinish
1c79356b 4799//
6d2010ae 4800// Done with this self-induced power state change.
1c79356b
A
4801//*********************************************************************************
4802
39236c6e 4803void IOService::OurChangeFinish( void )
1c79356b
A
4804{
4805 all_done();
4806}
4807
7e4a7d39
A
4808// MARK: -
4809// MARK: Power Change Initiated by Parent
0b4e3aa0 4810
1c79356b 4811//*********************************************************************************
7e4a7d39 4812// [private] ParentChangeStart
1c79356b 4813//
7e4a7d39 4814// Here we begin the processing of a power change initiated by our parent.
1c79356b
A
4815//*********************************************************************************
4816
39236c6e 4817IOReturn IOService::ParentChangeStart( void )
1c79356b 4818{
fe8ab488 4819 PM_ASSERT_IN_GATE();
7e4a7d39
A
4820 OUR_PMLog( kPMLogStartParentChange, fHeadNotePowerState, fCurrentPowerState );
4821
bd504ef0
A
4822 // Root power domain has transitioned to its max power state
4823 if ((fHeadNoteChangeFlags & (kIOPMDomainDidChange | kIOPMRootChangeUp)) ==
4824 (kIOPMDomainDidChange | kIOPMRootChangeUp))
b0d623f7 4825 {
bd504ef0
A
4826 // Restart the idle timer stopped by ParentChangeRootChangeDown()
4827 if (fIdleTimerPeriod && fIdleTimerStopped)
4828 {
4829 restartIdleTimer();
4830 }
4831 }
b0d623f7 4832
bd504ef0 4833 // Power domain is forcing us to lower power
39236c6e 4834 if ( StateOrder(fHeadNotePowerState) < StateOrder(fCurrentPowerState) )
bd504ef0 4835 {
6d2010ae 4836 PM_ACTION_2(actionPowerChangeStart, fHeadNotePowerState, &fHeadNoteChangeFlags);
1c79356b 4837
fe8ab488
A
4838 // Tell apps and kernel clients
4839 fInitialPowerChange = false;
6d2010ae 4840 fMachineState = kIOPM_ParentChangeTellPriorityClientsPowerDown;
fe8ab488 4841 tellChangeDown1(fHeadNotePowerState);
7e4a7d39
A
4842 return IOPMWillAckLater;
4843 }
4844
39236c6e
A
4845 // Power domain is allowing us to raise power up to fHeadNotePowerState
4846 if ( StateOrder(fHeadNotePowerState) > StateOrder(fCurrentPowerState) )
7e4a7d39 4847 {
39236c6e 4848 if ( StateOrder(fDesiredPowerState) > StateOrder(fCurrentPowerState) )
7e4a7d39 4849 {
39236c6e 4850 if ( StateOrder(fDesiredPowerState) < StateOrder(fHeadNotePowerState) )
7e4a7d39
A
4851 {
4852 // We power up, but not all the way
4853 fHeadNotePowerState = fDesiredPowerState;
fe8ab488 4854 fHeadNotePowerArrayEntry = &fPowerStates[fDesiredPowerState];
7e4a7d39
A
4855 OUR_PMLog(kPMLogAmendParentChange, fHeadNotePowerState, 0);
4856 }
4857 } else {
4858 // We don't need to change
4859 fHeadNotePowerState = fCurrentPowerState;
fe8ab488 4860 fHeadNotePowerArrayEntry = &fPowerStates[fCurrentPowerState];
7e4a7d39
A
4861 OUR_PMLog(kPMLogAmendParentChange, fHeadNotePowerState, 0);
4862 }
4863 }
4864
6d2010ae 4865 if ( fHeadNoteChangeFlags & kIOPMDomainDidChange )
fe8ab488 4866 {
39236c6e 4867 if ( StateOrder(fHeadNotePowerState) > StateOrder(fCurrentPowerState) )
7e4a7d39 4868 {
6d2010ae
A
4869 PM_ACTION_2(actionPowerChangeStart,
4870 fHeadNotePowerState, &fHeadNoteChangeFlags);
7e4a7d39
A
4871
4872 // Parent did change up - start our change up
fe8ab488 4873 fInitialPowerChange = false;
6d2010ae 4874 ParentChangeTellCapabilityWillChange();
7e4a7d39
A
4875 return IOPMWillAckLater;
4876 }
bd504ef0 4877 else if (fHeadNoteChangeFlags & kIOPMRootBroadcastFlags)
7e4a7d39 4878 {
bd504ef0
A
4879 // No need to change power state, but broadcast change
4880 // to our children.
7e4a7d39
A
4881 fMachineState = kIOPM_SyncNotifyDidChange;
4882 fDriverCallReason = kDriverCallInformPreChange;
3e170ce0 4883 fHeadNoteChangeFlags |= kIOPMNotDone;
7e4a7d39
A
4884 notifyChildren();
4885 return IOPMWillAckLater;
4886 }
4887 }
4888
3e170ce0
A
4889 // No power state change necessary
4890 fHeadNoteChangeFlags |= kIOPMNotDone;
4891
7e4a7d39
A
4892 all_done();
4893 return IOPMAckImplied;
4894}
4895
bd504ef0
A
4896//******************************************************************************
4897// [private] ParentChangeRootChangeDown
4898//
4899// Root domain has finished the transition to the system sleep state. And all
4900// drivers in the power plane should have powered down. Cancel the idle timer,
4901// and also reset the device desire for those drivers that don't want power
4902// automatically restored on wake.
4903//******************************************************************************
4904
4905void IOService::ParentChangeRootChangeDown( void )
4906{
4907 // Always stop the idle timer before root power down
4908 if (fIdleTimerPeriod && !fIdleTimerStopped)
4909 {
4910 fIdleTimerStopped = true;
4911 if (fIdleTimer && thread_call_cancel(fIdleTimer))
4912 release();
4913 }
4914
4915 if (fResetPowerStateOnWake)
4916 {
4917 // Reset device desire down to the lowest power state.
4918 // Advisory tickle desire is intentionally untouched since
4919 // it has no effect until system is promoted to full wake.
4920
39236c6e 4921 if (fDeviceDesire != kPowerStateZero)
bd504ef0 4922 {
39236c6e
A
4923 updatePowerClient(gIOPMPowerClientDevice, kPowerStateZero);
4924 computeDesiredState(kPowerStateZero, true);
3e170ce0 4925 requestDomainPower( fDesiredPowerState );
bd504ef0
A
4926 PM_LOG1("%s: tickle desire removed\n", fName);
4927 }
4928
4929 // Invalidate tickle cache so the next tickle will issue a request
4930 IOLockLock(fActivityLock);
4931 fDeviceWasActive = false;
4932 fActivityTicklePowerState = kInvalidTicklePowerState;
4933 IOLockUnlock(fActivityLock);
4934
39236c6e 4935 fIdleTimerMinPowerState = kPowerStateZero;
bd504ef0
A
4936 }
4937 else if (fAdvisoryTickleUsed)
4938 {
4939 // Less aggressive mechanism to accelerate idle timer expiration
4940 // before system sleep. May not always allow the driver to wake
4941 // up from system sleep in the min power state.
4942
4943 AbsoluteTime now;
4944 uint64_t nsec;
4945 bool dropTickleDesire = false;
4946
4947 if (fIdleTimerPeriod && !fIdleTimerIgnored &&
39236c6e
A
4948 (fIdleTimerMinPowerState == kPowerStateZero) &&
4949 (fDeviceDesire != kPowerStateZero))
bd504ef0
A
4950 {
4951 IOLockLock(fActivityLock);
4952
4953 if (!fDeviceWasActive)
4954 {
4955 // No tickles since the last idle timer expiration.
4956 // Safe to drop the device desire to zero.
4957 dropTickleDesire = true;
4958 }
4959 else
4960 {
4961 // Was tickled since the last idle timer expiration,
4962 // but not in the last minute.
4963 clock_get_uptime(&now);
4964 SUB_ABSOLUTETIME(&now, &fDeviceActiveTimestamp);
4965 absolutetime_to_nanoseconds(now, &nsec);
4966 if (nsec >= kNoTickleCancelWindow)
4967 {
4968 dropTickleDesire = true;
4969 }
4970 }
4971
4972 if (dropTickleDesire)
4973 {
4974 // Force the next tickle to raise power state
4975 fDeviceWasActive = false;
4976 fActivityTicklePowerState = kInvalidTicklePowerState;
4977 }
4978
4979 IOLockUnlock(fActivityLock);
4980 }
4981
4982 if (dropTickleDesire)
4983 {
4984 // Advisory tickle desire is intentionally untouched since
4985 // it has no effect until system is promoted to full wake.
4986
39236c6e
A
4987 updatePowerClient(gIOPMPowerClientDevice, kPowerStateZero);
4988 computeDesiredState(kPowerStateZero, true);
bd504ef0
A
4989 PM_LOG1("%s: tickle desire dropped\n", fName);
4990 }
4991 }
4992}
4993
7e4a7d39 4994//*********************************************************************************
6d2010ae 4995// [private] ParentChangeTellPriorityClientsPowerDown
7e4a7d39 4996//
6d2010ae
A
4997// All applications and kernel clients have acknowledged our intention to drop
4998// power. Here we notify "priority" clients that we are lowering power.
7e4a7d39
A
4999//*********************************************************************************
5000
39236c6e 5001void IOService::ParentChangeTellPriorityClientsPowerDown( void )
7e4a7d39 5002{
6d2010ae 5003 fMachineState = kIOPM_ParentChangeNotifyInterestedDriversWillChange;
fe8ab488 5004 tellChangeDown2(fHeadNotePowerState);
7e4a7d39
A
5005}
5006
5007//*********************************************************************************
6d2010ae 5008// [private] ParentChangeTellCapabilityWillChange
7e4a7d39 5009//
6d2010ae
A
5010// All (legacy) applications and kernel clients have acknowledged, extra stage for
5011// root domain to notify apps and drivers about the system capability change.
7e4a7d39
A
5012//*********************************************************************************
5013
39236c6e 5014void IOService::ParentChangeTellCapabilityWillChange( void )
7e4a7d39 5015{
6d2010ae
A
5016 if (!IS_ROOT_DOMAIN)
5017 return ParentChangeNotifyInterestedDriversWillChange();
7e4a7d39 5018
6d2010ae 5019 tellSystemCapabilityChange( kIOPM_ParentChangeNotifyInterestedDriversWillChange );
7e4a7d39
A
5020}
5021
5022//*********************************************************************************
6d2010ae 5023// [private] ParentChangeNotifyInterestedDriversWillChange
7e4a7d39 5024//
6d2010ae
A
5025// All applications and kernel clients have acknowledged our power state change.
5026// Here we notify interested drivers pre-change.
1c79356b
A
5027//*********************************************************************************
5028
39236c6e 5029void IOService::ParentChangeNotifyInterestedDriversWillChange( void )
1c79356b 5030{
fe8ab488 5031 notifyAll( kIOPM_ParentChangeSetPowerState );
6d2010ae 5032}
1c79356b 5033
6d2010ae
A
5034//*********************************************************************************
5035// [private] ParentChangeSetPowerState
5036//
5037// Instruct our controlling driver to program the hardware for the power state
5038// change. Wait for async completions.
5039//*********************************************************************************
5040
39236c6e 5041void IOService::ParentChangeSetPowerState( void )
6d2010ae
A
5042{
5043 MS_PUSH( kIOPM_ParentChangeWaitForPowerSettle );
5044 fMachineState = kIOPM_DriverThreadCallDone;
5045 fDriverCallReason = kDriverCallSetPowerState;
5046
5047 if (notifyControllingDriver() == false)
5048 notifyControllingDriverDone();
1c79356b
A
5049}
5050
1c79356b 5051//*********************************************************************************
6d2010ae 5052// [private] ParentChangeWaitForPowerSettle
1c79356b 5053//
6d2010ae
A
5054// Our controlling driver has completed the power state change initiated by our
5055// parent. Wait for the driver specified settle time to expire.
1c79356b
A
5056//*********************************************************************************
5057
39236c6e 5058void IOService::ParentChangeWaitForPowerSettle( void )
1c79356b 5059{
fe8ab488 5060 fMachineState = kIOPM_ParentChangeNotifyInterestedDriversDidChange;
7e4a7d39 5061 startSettleTimer();
1c79356b
A
5062}
5063
1c79356b 5064//*********************************************************************************
6d2010ae
A
5065// [private] ParentChangeNotifyInterestedDriversDidChange
5066//
5067// Power has settled on a power change initiated by our parent. Here we notify
5068// all our interested drivers post-change.
5069//*********************************************************************************
5070
39236c6e 5071void IOService::ParentChangeNotifyInterestedDriversDidChange( void )
6d2010ae 5072{
fe8ab488 5073 notifyAll( kIOPM_ParentChangeTellCapabilityDidChange );
6d2010ae
A
5074}
5075
5076//*********************************************************************************
5077// [private] ParentChangeTellCapabilityDidChange
1c79356b 5078//
6d2010ae 5079// For root domain to notify capability power-change.
1c79356b
A
5080//*********************************************************************************
5081
39236c6e 5082void IOService::ParentChangeTellCapabilityDidChange( void )
1c79356b 5083{
6d2010ae
A
5084 if (!IS_ROOT_DOMAIN)
5085 return ParentChangeAcknowledgePowerChange();
5086
5087 tellSystemCapabilityChange( kIOPM_ParentChangeAcknowledgePowerChange );
1c79356b
A
5088}
5089
1c79356b 5090//*********************************************************************************
b0d623f7 5091// [private] ParentAcknowledgePowerChange
1c79356b 5092//
fe8ab488 5093// Acknowledge our power parent that our power change is done.
1c79356b
A
5094//*********************************************************************************
5095
39236c6e 5096void IOService::ParentChangeAcknowledgePowerChange( void )
1c79356b 5097{
fe8ab488
A
5098 IORegistryEntry * nub;
5099 IOService * parent;
2d21ac55 5100
b0d623f7 5101 nub = fHeadNoteParentConnection;
55e303ae 5102 nub->retain();
1c79356b 5103 all_done();
0b4e3aa0 5104 parent = (IOService *)nub->copyParentEntry(gIOPowerPlane);
2d21ac55 5105 if ( parent )
55e303ae 5106 {
0b4e3aa0
A
5107 parent->acknowledgePowerChange((IOService *)nub);
5108 parent->release();
5109 }
5110 nub->release();
1c79356b
A
5111}
5112
6d2010ae
A
5113// MARK: -
5114// MARK: Ack and Settle timers
5115
1c79356b 5116//*********************************************************************************
6d2010ae 5117// [private] settleTimerExpired
1c79356b 5118//
6d2010ae
A
5119// Power has settled after our last change. Notify interested parties that
5120// there is a new power state.
1c79356b
A
5121//*********************************************************************************
5122
6d2010ae 5123void IOService::settleTimerExpired( void )
1c79356b 5124{
fe8ab488
A
5125 fSettleTimeUS = 0;
5126 gIOPMWorkQueue->signalWorkAvailable();
1c79356b
A
5127}
5128
1c79356b 5129//*********************************************************************************
6d2010ae 5130// settle_timer_expired
1c79356b 5131//
6d2010ae 5132// Holds a retain while the settle timer callout is in flight.
1c79356b
A
5133//*********************************************************************************
5134
7e4a7d39
A
5135static void
5136settle_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
1c79356b 5137{
fe8ab488 5138 IOService * me = (IOService *) arg0;
7e4a7d39 5139
fe8ab488
A
5140 if (gIOPMWorkLoop && gIOPMWorkQueue)
5141 {
5142 gIOPMWorkLoop->runAction(
7e4a7d39
A
5143 OSMemberFunctionCast(IOWorkLoop::Action, me, &IOService::settleTimerExpired),
5144 me);
fe8ab488
A
5145 }
5146 me->release();
7e4a7d39
A
5147}
5148
5149//*********************************************************************************
5150// [private] startSettleTimer
5151//
5152// Calculate a power-settling delay in microseconds and start a timer.
5153//*********************************************************************************
5154
5155void IOService::startSettleTimer( void )
5156{
bd504ef0
A
5157#if NOT_USEFUL
5158 // This function is broken and serves no useful purpose since it never
5159 // updates fSettleTimeUS to a non-zero value to stall the state machine,
5160 // yet it starts a delay timer. It appears no driver relies on a delay
5161 // from settleUpTime and settleDownTime in the power state table.
5162
7e4a7d39 5163 AbsoluteTime deadline;
39236c6e
A
5164 IOPMPowerStateIndex stateIndex;
5165 IOPMPowerStateIndex currentOrder, newOrder, i;
7e4a7d39 5166 uint32_t settleTime = 0;
fe8ab488 5167 boolean_t pending;
2d21ac55 5168
fe8ab488 5169 PM_ASSERT_IN_GATE();
1c79356b 5170
39236c6e
A
5171 currentOrder = StateOrder(fCurrentPowerState);
5172 newOrder = StateOrder(fHeadNotePowerState);
5173
5174 i = currentOrder;
55e303ae 5175
7e4a7d39 5176 // lowering power
39236c6e 5177 if ( newOrder < currentOrder )
55e303ae 5178 {
39236c6e 5179 while ( i > newOrder )
55e303ae 5180 {
39236c6e
A
5181 stateIndex = fPowerStates[i].stateOrderToIndex;
5182 settleTime += (uint32_t) fPowerStates[stateIndex].settleDownTime;
1c79356b
A
5183 i--;
5184 }
5185 }
5186
7e4a7d39 5187 // raising power
39236c6e 5188 if ( newOrder > currentOrder )
55e303ae 5189 {
39236c6e 5190 while ( i < newOrder )
55e303ae 5191 {
39236c6e
A
5192 stateIndex = fPowerStates[i+1].stateOrderToIndex;
5193 settleTime += (uint32_t) fPowerStates[stateIndex].settleUpTime;
1c79356b
A
5194 i++;
5195 }
5196 }
5197
7e4a7d39
A
5198 if (settleTime)
5199 {
5200 retain();
5201 clock_interval_to_deadline(settleTime, kMicrosecondScale, &deadline);
5202 pending = thread_call_enter_delayed(fSettleTimer, deadline);
5203 if (pending) release();
5204 }
bd504ef0 5205#endif
1c79356b
A
5206}
5207
5208//*********************************************************************************
7e4a7d39 5209// [private] ackTimerTick
1c79356b
A
5210//
5211// The acknowledgement timeout periodic timer has ticked.
5212// If we are awaiting acks for a power change notification,
5213// we decrement the timer word of each interested driver which hasn't acked.
5214// If a timer word becomes zero, we pretend the driver aknowledged.
5215// If we are waiting for the controlling driver to change the power
5216// state of the hardware, we decrement its timer word, and if it becomes
5217// zero, we pretend the driver acknowledged.
2d21ac55
A
5218//
5219// Returns true if the timer tick made it possible to advance to the next
5220// machine state, false otherwise.
1c79356b
A
5221//*********************************************************************************
5222
b0d623f7 5223#ifndef __LP64__
1c79356b
A
5224void IOService::ack_timer_ticked ( void )
5225{
fe8ab488 5226 assert(false);
2d21ac55 5227}
b0d623f7 5228#endif /* !__LP64__ */
1c79356b 5229
2d21ac55
A
5230bool IOService::ackTimerTick( void )
5231{
fe8ab488
A
5232 IOPMinformee * nextObject;
5233 bool done = false;
1c79356b 5234
fe8ab488 5235 PM_ASSERT_IN_GATE();
2d21ac55 5236 switch (fMachineState) {
55e303ae 5237 case kIOPM_OurChangeWaitForPowerSettle:
6d2010ae 5238 case kIOPM_ParentChangeWaitForPowerSettle:
2d21ac55
A
5239 // are we waiting for controlling driver to acknowledge?
5240 if ( fDriverTimer > 0 )
5241 {
5242 // yes, decrement timer tick
5243 fDriverTimer--;
5244 if ( fDriverTimer == 0 )
55e303ae 5245 {
2d21ac55
A
5246 // controlling driver is tardy
5247 uint64_t nsec = computeTimeDeltaNS(&fDriverCallStartTime);
5248 OUR_PMLog(kPMLogCtrlDriverTardy, 0, 0);
5249 setProperty(kIOPMTardyAckSPSKey, kOSBooleanTrue);
5250 PM_ERROR("%s::setPowerState(%p, %lu -> %lu) timed out after %d ms\n",
39236c6e 5251 fName, OBFUSCATE(this), fCurrentPowerState, fHeadNotePowerState, NS_TO_MS(nsec));
2d21ac55
A
5252
5253 if (gIOKitDebug & kIOLogDebugPower)
5254 {
5255 panic("%s::setPowerState(%p, %lu -> %lu) timed out after %d ms",
b0d623f7 5256 fName, this, fCurrentPowerState, fHeadNotePowerState, NS_TO_MS(nsec));
2d21ac55
A
5257 }
5258 else
fe8ab488
A
5259 {
5260 // Unblock state machine and pretend driver has acked.
5261 done = true;
5262 }
55e303ae
A
5263 } else {
5264 // still waiting, set timer again
1c79356b 5265 start_ack_timer();
1c79356b
A
5266 }
5267 }
1c79356b
A
5268 break;
5269
6d2010ae 5270 case kIOPM_NotifyChildrenStart:
55e303ae 5271 // are we waiting for interested parties to acknowledge?
2d21ac55 5272 if ( fHeadNotePendingAcks != 0 )
55e303ae
A
5273 {
5274 // yes, go through the list of interested drivers
2d21ac55 5275 nextObject = fInterestedDrivers->firstInList();
55e303ae 5276 // and check each one
2d21ac55 5277 while ( nextObject != NULL )
55e303ae 5278 {
2d21ac55 5279 if ( nextObject->timer > 0 )
55e303ae 5280 {
2d21ac55 5281 nextObject->timer--;
55e303ae 5282 // this one should have acked by now
2d21ac55 5283 if ( nextObject->timer == 0 )
55e303ae 5284 {
2d21ac55
A
5285 uint64_t nsec = computeTimeDeltaNS(&nextObject->startTime);
5286 OUR_PMLog(kPMLogIntDriverTardy, 0, 0);
5287 nextObject->whatObject->setProperty(kIOPMTardyAckPSCKey, kOSBooleanTrue);
5288 PM_ERROR("%s::powerState%sChangeTo(%p, %s, %lu -> %lu) timed out after %d ms\n",
5289 nextObject->whatObject->getName(),
5290 (fDriverCallReason == kDriverCallInformPreChange) ? "Will" : "Did",
39236c6e 5291 OBFUSCATE(nextObject->whatObject), fName, fCurrentPowerState, fHeadNotePowerState,
2d21ac55
A
5292 NS_TO_MS(nsec));
5293
5294 // Pretend driver has acked.
5295 fHeadNotePendingAcks--;
1c79356b
A
5296 }
5297 }
2d21ac55 5298 nextObject = fInterestedDrivers->nextInList(nextObject);
1c79356b 5299 }
55e303ae
A
5300
5301 // is that the last?
2d21ac55 5302 if ( fHeadNotePendingAcks == 0 )
55e303ae 5303 {
55e303ae 5304 // yes, we can continue
fe8ab488 5305 done = true;
55e303ae
A
5306 } else {
5307 // no, set timer again
1c79356b 5308 start_ack_timer();
1c79356b 5309 }
1c79356b
A
5310 }
5311 break;
5312
6d2010ae 5313 // TODO: aggreggate this
55e303ae 5314 case kIOPM_OurChangeTellClientsPowerDown:
39236c6e 5315 case kIOPM_OurChangeTellUserPMPolicyPowerDown:
55e303ae 5316 case kIOPM_OurChangeTellPriorityClientsPowerDown:
55e303ae 5317 case kIOPM_OurChangeNotifyInterestedDriversWillChange:
6d2010ae
A
5318 case kIOPM_ParentChangeTellPriorityClientsPowerDown:
5319 case kIOPM_ParentChangeNotifyInterestedDriversWillChange:
5320 case kIOPM_SyncTellClientsPowerDown:
5321 case kIOPM_SyncTellPriorityClientsPowerDown:
5322 case kIOPM_SyncNotifyWillChange:
5323 case kIOPM_TellCapabilityChangeDone:
fe8ab488 5324 // apps didn't respond in time
2d21ac55
A
5325 cleanClientResponses(true);
5326 OUR_PMLog(kPMLogClientTardy, 0, 1);
fe8ab488
A
5327 // tardy equates to approval
5328 done = true;
1c79356b 5329 break;
2d21ac55 5330
1c79356b 5331 default:
6d2010ae 5332 PM_LOG1("%s: unexpected ack timer tick (state = %d)\n",
fe8ab488 5333 getName(), fMachineState);
1c79356b
A
5334 break;
5335 }
fe8ab488 5336 return done;
1c79356b
A
5337}
5338
39236c6e
A
5339//*********************************************************************************
5340// [private] start_watchdog_timer
5341//*********************************************************************************
5342void IOService::start_watchdog_timer( void )
5343{
5344 AbsoluteTime deadline;
5345 boolean_t pending;
3e170ce0 5346 static int timeout = -1;
39236c6e 5347
fe8ab488 5348 if (!fWatchdogTimer || (kIOSleepWakeWdogOff & gIOKitDebug))
39236c6e
A
5349 return;
5350
5351 if (thread_call_isactive(fWatchdogTimer)) return;
3e170ce0
A
5352 if (timeout == -1) {
5353 PE_parse_boot_argn("swd_timeout", &timeout, sizeof(timeout));
5354 }
5355 if (timeout < 60) {
5356 timeout = WATCHDOG_TIMER_PERIOD;
5357 }
39236c6e 5358
3e170ce0 5359 clock_interval_to_deadline(timeout, kSecondScale, &deadline);
39236c6e
A
5360
5361 retain();
5362 pending = thread_call_enter_delayed(fWatchdogTimer, deadline);
5363 if (pending) release();
5364
5365}
5366
5367//*********************************************************************************
5368// [private] stop_watchdog_timer
5369// Returns true if watchdog was enabled and stopped now
5370//*********************************************************************************
5371
5372bool IOService::stop_watchdog_timer( void )
5373{
5374 boolean_t pending;
5375
fe8ab488 5376 if (!fWatchdogTimer || (kIOSleepWakeWdogOff & gIOKitDebug))
39236c6e
A
5377 return false;
5378
5379 pending = thread_call_cancel(fWatchdogTimer);
5380 if (pending) release();
5381
5382 return pending;
5383}
5384
5385//*********************************************************************************
5386// reset_watchdog_timer
5387//*********************************************************************************
5388
5389void IOService::reset_watchdog_timer( void )
5390{
5391 if (stop_watchdog_timer())
5392 start_watchdog_timer();
5393}
5394
5395
5396//*********************************************************************************
5397// [static] watchdog_timer_expired
5398//
5399// Inside PM work loop's gate.
5400//*********************************************************************************
5401
5402void
5403IOService::watchdog_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
5404{
fe8ab488 5405 IOService * me = (IOService *) arg0;
39236c6e
A
5406
5407
5408 gIOPMWatchDogThread = current_thread();
5409 getPMRootDomain()->sleepWakeDebugTrig(true);
5410 gIOPMWatchDogThread = 0;
fe8ab488
A
5411 thread_call_free(me->fWatchdogTimer);
5412 me->fWatchdogTimer = 0;
39236c6e 5413
fe8ab488 5414 return ;
39236c6e
A
5415}
5416
5417
1c79356b 5418//*********************************************************************************
2d21ac55 5419// [private] start_ack_timer
1c79356b
A
5420//*********************************************************************************
5421
39236c6e 5422void IOService::start_ack_timer( void )
1c79356b 5423{
fe8ab488 5424 start_ack_timer( ACK_TIMER_PERIOD, kNanosecondScale );
1c79356b
A
5425}
5426
2d21ac55
A
5427void IOService::start_ack_timer ( UInt32 interval, UInt32 scale )
5428{
39236c6e
A
5429 AbsoluteTime deadline;
5430 boolean_t pending;
2d21ac55
A
5431
5432 clock_interval_to_deadline(interval, scale, &deadline);
5433
39236c6e 5434 retain();
2d21ac55 5435 pending = thread_call_enter_delayed(fAckTimer, deadline);
39236c6e
A
5436 if (pending) release();
5437
5438 // Stop watchdog if ack is delayed by more than a sec
5439 if (interval * scale > kSecondScale) {
5440 stop_watchdog_timer();
5441 }
2d21ac55 5442}
1c79356b
A
5443
5444//*********************************************************************************
2d21ac55 5445// [private] stop_ack_timer
1c79356b
A
5446//*********************************************************************************
5447
39236c6e 5448void IOService::stop_ack_timer( void )
1c79356b 5449{
39236c6e 5450 boolean_t pending;
1c79356b 5451
2d21ac55 5452 pending = thread_call_cancel(fAckTimer);
39236c6e
A
5453 if (pending) release();
5454
5455 start_watchdog_timer();
2d21ac55 5456}
1c79356b
A
5457
5458//*********************************************************************************
b0d623f7 5459// [static] actionAckTimerExpired
1c79356b 5460//
2d21ac55 5461// Inside PM work loop's gate.
1c79356b
A
5462//*********************************************************************************
5463
2d21ac55 5464IOReturn
39236c6e
A
5465IOService::actionAckTimerExpired(
5466 OSObject * target,
5467 void * arg0, void * arg1,
5468 void * arg2, void * arg3 )
1c79356b 5469{
39236c6e
A
5470 IOService * me = (IOService *) target;
5471 bool done;
1c79356b 5472
39236c6e
A
5473 // done will be true if the timer tick unblocks the machine state,
5474 // otherwise no need to signal the work loop.
1c79356b 5475
39236c6e
A
5476 done = me->ackTimerTick();
5477 if (done && gIOPMWorkQueue)
5478 {
5479 gIOPMWorkQueue->signalWorkAvailable();
5480 me->start_watchdog_timer();
5481 }
1c79356b 5482
39236c6e 5483 return kIOReturnSuccess;
2d21ac55 5484}
1c79356b
A
5485
5486//*********************************************************************************
2d21ac55 5487// ack_timer_expired
1c79356b 5488//
2d21ac55 5489// Thread call function. Holds a retain while the callout is in flight.
1c79356b
A
5490//*********************************************************************************
5491
2d21ac55 5492void
39236c6e 5493IOService::ack_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
1c79356b 5494{
fe8ab488 5495 IOService * me = (IOService *) arg0;
55e303ae 5496
fe8ab488
A
5497 if (gIOPMWorkLoop)
5498 {
5499 gIOPMWorkLoop->runAction(&actionAckTimerExpired, me);
5500 }
5501 me->release();
1c79356b
A
5502}
5503
3e170ce0
A
5504//*********************************************************************************
5505// [private] start_spindump_timer
5506//*********************************************************************************
5507
5508void IOService::start_spindump_timer( const char * delay_type )
5509{
5510 AbsoluteTime deadline;
5511 boolean_t pending;
5512
5513 if (!fSpinDumpTimer || !(kIOKextSpinDump & gIOKitDebug))
5514 return;
5515
5516 if (gIOSpinDumpKextName[0] == '\0' &&
5517 !(PE_parse_boot_argn("swd_kext_name", &gIOSpinDumpKextName,
5518 sizeof(gIOSpinDumpKextName))))
5519 {
5520 return;
5521 }
5522
5523 if (strncmp(gIOSpinDumpKextName, fName, sizeof(gIOSpinDumpKextName)) != 0)
5524 return;
5525
5526 if (gIOSpinDumpDelayType[0] == '\0' &&
5527 !(PE_parse_boot_argn("swd_delay_type", &gIOSpinDumpDelayType,
5528 sizeof(gIOSpinDumpDelayType))))
5529 {
5530 strncpy(gIOSpinDumpDelayType, "SetState", sizeof(gIOSpinDumpDelayType));
5531 }
5532
5533 if (strncmp(delay_type, gIOSpinDumpDelayType, sizeof(gIOSpinDumpDelayType)) != 0)
5534 return;
5535
5536 if (gIOSpinDumpDelayDuration == 0 &&
5537 !(PE_parse_boot_argn("swd_delay_duration", &gIOSpinDumpDelayDuration,
5538 sizeof(gIOSpinDumpDelayDuration))))
5539 {
5540 gIOSpinDumpDelayDuration = 300;
5541 }
5542
5543 clock_interval_to_deadline(gIOSpinDumpDelayDuration, kMillisecondScale, &deadline);
5544
5545 retain();
5546 pending = thread_call_enter_delayed(fSpinDumpTimer, deadline);
5547 if (pending) release();
5548}
5549
5550//*********************************************************************************
5551// [private] stop_spindump_timer
5552//*********************************************************************************
5553
5554void IOService::stop_spindump_timer( void )
5555{
5556 boolean_t pending;
5557
5558 if (!fSpinDumpTimer || !(kIOKextSpinDump & gIOKitDebug))
5559 return;
5560
5561 pending = thread_call_cancel(fSpinDumpTimer);
5562 if (pending) release();
5563}
5564
5565
5566//*********************************************************************************
5567// [static] actionSpinDumpTimerExpired
5568//
5569// Inside PM work loop's gate.
5570//*********************************************************************************
5571
5572IOReturn
5573IOService::actionSpinDumpTimerExpired(
5574 OSObject * target,
5575 void * arg0, void * arg1,
5576 void * arg2, void * arg3 )
5577{
5578 getPMRootDomain()->takeStackshot(false, false, true);
5579
5580 return kIOReturnSuccess;
5581}
5582
5583//*********************************************************************************
5584// spindump_timer_expired
5585//
5586// Thread call function. Holds a retain while the callout is in flight.
5587//*********************************************************************************
5588
5589void
5590IOService::spindump_timer_expired( thread_call_param_t arg0, thread_call_param_t arg1 )
5591{
5592 IOService * me = (IOService *) arg0;
5593
5594 if (gIOPMWorkLoop)
5595 {
5596 gIOPMWorkLoop->runAction(&actionSpinDumpTimerExpired, me);
5597 }
5598 me->release();
5599}
5600
6d2010ae
A
5601// MARK: -
5602// MARK: Client Messaging
1c79356b 5603
1c79356b 5604//*********************************************************************************
6d2010ae 5605// [private] tellSystemCapabilityChange
1c79356b
A
5606//*********************************************************************************
5607
6d2010ae 5608void IOService::tellSystemCapabilityChange( uint32_t nextMS )
1c79356b 5609{
fe8ab488 5610 MS_PUSH( nextMS );
6d2010ae
A
5611 fMachineState = kIOPM_TellCapabilityChangeDone;
5612 fOutOfBandMessage = kIOMessageSystemCapabilityChange;
2d21ac55 5613
6d2010ae
A
5614 if (fIsPreChange)
5615 {
5616 // Notify app first on pre-change.
5617 fOutOfBandParameter = kNotifyCapabilityChangeApps;
5618 }
5619 else
5620 {
5621 // Notify kernel clients first on post-change.
5622 fOutOfBandParameter = kNotifyCapabilityChangePriority;
5623 }
1c79356b 5624
6d2010ae 5625 tellClientsWithResponse( fOutOfBandMessage );
1c79356b
A
5626}
5627
1c79356b 5628//*********************************************************************************
b0d623f7 5629// [public] askChangeDown
1c79356b
A
5630//
5631// Ask registered applications and kernel clients if we can change to a lower
5632// power state.
5633//
5634// Subclass can override this to send a different message type. Parameter is
5635// the destination state number.
5636//
5637// Return true if we don't have to wait for acknowledgements
5638//*********************************************************************************
5639
39236c6e 5640bool IOService::askChangeDown( unsigned long stateNum )
1c79356b 5641{
2d21ac55 5642 return tellClientsWithResponse( kIOMessageCanDevicePowerOff );
1c79356b
A
5643}
5644
0b4e3aa0 5645//*********************************************************************************
b0d623f7 5646// [private] tellChangeDown1
0b4e3aa0
A
5647//
5648// Notify registered applications and kernel clients that we are definitely
5649// dropping power.
5650//
5651// Return true if we don't have to wait for acknowledgements
5652//*********************************************************************************
5653
39236c6e 5654bool IOService::tellChangeDown1( unsigned long stateNum )
0b4e3aa0 5655{
2d21ac55 5656 fOutOfBandParameter = kNotifyApps;
0b4e3aa0
A
5657 return tellChangeDown(stateNum);
5658}
5659
0b4e3aa0 5660//*********************************************************************************
b0d623f7 5661// [private] tellChangeDown2
0b4e3aa0
A
5662//
5663// Notify priority clients that we are definitely dropping power.
5664//
5665// Return true if we don't have to wait for acknowledgements
5666//*********************************************************************************
5667
39236c6e 5668bool IOService::tellChangeDown2( unsigned long stateNum )
0b4e3aa0 5669{
2d21ac55 5670 fOutOfBandParameter = kNotifyPriority;
0b4e3aa0
A
5671 return tellChangeDown(stateNum);
5672}
5673
1c79356b 5674//*********************************************************************************
b0d623f7 5675// [public] tellChangeDown
1c79356b
A
5676//
5677// Notify registered applications and kernel clients that we are definitely
5678// dropping power.
5679//
5680// Subclass can override this to send a different message type. Parameter is
5681// the destination state number.
5682//
5683// Return true if we don't have to wait for acknowledgements
5684//*********************************************************************************
5685
39236c6e 5686bool IOService::tellChangeDown( unsigned long stateNum )
1c79356b 5687{
2d21ac55
A
5688 return tellClientsWithResponse( kIOMessageDeviceWillPowerOff );
5689}
5690
5691//*********************************************************************************
5692// cleanClientResponses
5693//
5694//*********************************************************************************
5695
39236c6e 5696static void logAppTimeouts( OSObject * object, void * arg )
2d21ac55 5697{
b0d623f7
A
5698 IOPMInterestContext * context = (IOPMInterestContext *) arg;
5699 OSObject * flag;
5700 unsigned int clientIndex;
39236c6e
A
5701 int pid = -1;
5702 char name[128];
2d21ac55 5703
b0d623f7
A
5704 if (OSDynamicCast(_IOServiceInterestNotifier, object))
5705 {
5706 // Discover the 'counter' value or index assigned to this client
5707 // when it was notified, by searching for the array index of the
5708 // client in an array holding the cached interested clients.
5709
5710 clientIndex = context->notifyClients->getNextIndexOfObject(object, 0);
5711
5712 if ((clientIndex != (unsigned int) -1) &&
6d2010ae 5713 (flag = context->responseArray->getObject(clientIndex)) &&
b0d623f7 5714 (flag != kOSBooleanTrue))
2d21ac55 5715 {
fe8ab488
A
5716 OSNumber *clientID = copyClientIDForNotification(object, context);
5717
39236c6e 5718 name[0] = '\0';
316670eb 5719 if (clientID) {
39236c6e
A
5720 pid = clientID->unsigned32BitValue();
5721 proc_name(pid, name, sizeof(name));
316670eb
A
5722 clientID->release();
5723 }
fe8ab488 5724
39236c6e 5725 PM_ERROR(context->errorLog, pid, name);
b0d623f7
A
5726
5727 // TODO: record message type if possible
5728 IOService::getPMRootDomain()->pmStatsRecordApplicationResponse(
5729 gIOPMStatsApplicationResponseTimedOut,
fe8ab488 5730 name, 0, (30*1000), pid, object);
b0d623f7 5731
2d21ac55 5732 }
2d21ac55 5733 }
1c79356b
A
5734}
5735
39236c6e 5736void IOService::cleanClientResponses( bool logErrors )
2d21ac55 5737{
6d2010ae
A
5738 if (logErrors && fResponseArray)
5739 {
2d21ac55
A
5740 switch ( fOutOfBandParameter ) {
5741 case kNotifyApps:
6d2010ae
A
5742 case kNotifyCapabilityChangeApps:
5743 if (fNotifyClientArray)
5744 {
5745 IOPMInterestContext context;
5746
5747 context.responseArray = fResponseArray;
5748 context.notifyClients = fNotifyClientArray;
5749 context.serialNumber = fSerialNumber;
5750 context.messageType = kIOMessageCopyClientID;
5751 context.notifyType = kNotifyApps;
5752 context.isPreChange = fIsPreChange;
5753 context.enableTracing = false;
5754 context.us = this;
5755 context.maxTimeRequested = 0;
5756 context.stateNumber = fHeadNotePowerState;
5757 context.stateFlags = fHeadNotePowerArrayEntry->capabilityFlags;
5758 context.changeFlags = fHeadNoteChangeFlags;
39236c6e 5759 context.errorLog = "PM notification timeout (pid %d, %s)\n";
6d2010ae
A
5760
5761 applyToInterested(gIOAppPowerStateInterest, logAppTimeouts, (void *) &context);
5762 }
5763 break;
5764
2d21ac55 5765 default:
6d2010ae
A
5766 // kNotifyPriority, kNotifyCapabilityChangePriority
5767 // TODO: identify the priority client that has not acked
5768 PM_ERROR("PM priority notification timeout\n");
5769 if (gIOKitDebug & kIOLogDebugPower)
5770 {
5771 panic("PM priority notification timeout");
5772 }
2d21ac55
A
5773 break;
5774 }
5775 }
5776
b0d623f7 5777 if (fResponseArray)
2d21ac55 5778 {
2d21ac55
A
5779 fResponseArray->release();
5780 fResponseArray = NULL;
5781 }
b0d623f7
A
5782 if (fNotifyClientArray)
5783 {
5784 fNotifyClientArray->release();
5785 fNotifyClientArray = NULL;
5786 }
2d21ac55 5787}
1c79356b
A
5788
5789//*********************************************************************************
b0d623f7 5790// [protected] tellClientsWithResponse
1c79356b
A
5791//
5792// Notify registered applications and kernel clients that we are definitely
5793// dropping power.
5794//
5795// Return true if we don't have to wait for acknowledgements
5796//*********************************************************************************
5797
39236c6e 5798bool IOService::tellClientsWithResponse( int messageType )
1c79356b 5799{
b0d623f7 5800 IOPMInterestContext context;
6d2010ae 5801 bool isRootDomain = IS_ROOT_DOMAIN;
3e170ce0 5802 uint32_t maxTimeOut = kMaxTimeRequested;
2d21ac55 5803
fe8ab488 5804 PM_ASSERT_IN_GATE();
b0d623f7
A
5805 assert( fResponseArray == NULL );
5806 assert( fNotifyClientArray == NULL );
1c79356b 5807
39236c6e
A
5808 if(messageType == (int)kIOPMMessageLastCallBeforeSleep)
5809 RD_LOG("tellClientsWithResponse( kIOPMMessageLastCallBeforeSleep, %d )\n",
5810 fOutOfBandParameter);
5811 else
5812 RD_LOG("tellClientsWithResponse( %s, %d )\n",
5813 getIOMessageString(messageType), fOutOfBandParameter);
6d2010ae 5814
2d21ac55 5815 fResponseArray = OSArray::withCapacity( 1 );
b0d623f7
A
5816 if (!fResponseArray)
5817 goto exit;
5818
5819 fResponseArray->setCapacityIncrement(8);
6d2010ae 5820 if (++fSerialNumber == 0)
fe8ab488 5821 fSerialNumber++;
b0d623f7 5822
6d2010ae 5823 context.responseArray = fResponseArray;
b0d623f7
A
5824 context.notifyClients = 0;
5825 context.serialNumber = fSerialNumber;
6d2010ae
A
5826 context.messageType = messageType;
5827 context.notifyType = fOutOfBandParameter;
5828 context.isPreChange = fIsPreChange;
5829 context.enableTracing = false;
b0d623f7
A
5830 context.us = this;
5831 context.maxTimeRequested = 0;
5832 context.stateNumber = fHeadNotePowerState;
5833 context.stateFlags = fHeadNotePowerArrayEntry->capabilityFlags;
6d2010ae
A
5834 context.changeFlags = fHeadNoteChangeFlags;
5835 context.messageFilter = (isRootDomain) ?
5836 OSMemberFunctionCast(
5837 IOPMMessageFilter,
5838 this,
5839 &IOPMrootDomain::systemMessageFilter) : 0;
0b4e3aa0 5840
2d21ac55 5841 switch ( fOutOfBandParameter ) {
0b4e3aa0 5842 case kNotifyApps:
b0d623f7 5843 applyToInterested( gIOAppPowerStateInterest,
fe8ab488 5844 pmTellAppWithResponse, (void *) &context );
6d2010ae
A
5845
5846 if (isRootDomain &&
5847 (fMachineState != kIOPM_OurChangeTellClientsPowerDown) &&
39236c6e
A
5848 (fMachineState != kIOPM_SyncTellClientsPowerDown) &&
5849 (context.messageType != kIOPMMessageLastCallBeforeSleep))
6d2010ae
A
5850 {
5851 // Notify capability app for tellChangeDown1()
5852 // but not for askChangeDown().
5853 context.notifyType = kNotifyCapabilityChangeApps;
5854 context.messageType = kIOMessageSystemCapabilityChange;
5855 applyToInterested( gIOAppPowerStateInterest,
fe8ab488 5856 pmTellCapabilityAppWithResponse, (void *) &context );
6d2010ae
A
5857 context.notifyType = fOutOfBandParameter;
5858 context.messageType = messageType;
5859 }
3e170ce0
A
5860 if(context.messageType == kIOMessageCanSystemSleep)
5861 {
5862 maxTimeOut = kCanSleepMaxTimeReq;
5863 if(gCanSleepTimeout)
5864 {
5865 maxTimeOut = (gCanSleepTimeout*us_per_s);
5866 }
5867 }
5868 context.maxTimeRequested = maxTimeOut;
b0d623f7 5869 applyToInterested( gIOGeneralInterest,
fe8ab488 5870 pmTellClientWithResponse, (void *) &context );
6d2010ae
A
5871
5872 fNotifyClientArray = context.notifyClients;
0b4e3aa0 5873 break;
b0d623f7 5874
0b4e3aa0 5875 case kNotifyPriority:
6d2010ae 5876 context.enableTracing = isRootDomain;
b0d623f7 5877 applyToInterested( gIOPriorityPowerStateInterest,
fe8ab488 5878 pmTellClientWithResponse, (void *) &context );
6d2010ae
A
5879
5880 if (isRootDomain)
5881 {
5882 // Notify capability clients for tellChangeDown2().
5883 context.notifyType = kNotifyCapabilityChangePriority;
5884 context.messageType = kIOMessageSystemCapabilityChange;
5885 applyToInterested( gIOPriorityPowerStateInterest,
5886 pmTellCapabilityClientWithResponse, (void *) &context );
5887 }
5888 break;
5889
5890 case kNotifyCapabilityChangeApps:
5891 applyToInterested( gIOAppPowerStateInterest,
fe8ab488 5892 pmTellCapabilityAppWithResponse, (void *) &context );
6d2010ae 5893 fNotifyClientArray = context.notifyClients;
3e170ce0
A
5894 if(context.messageType == kIOMessageCanSystemSleep)
5895 {
5896 maxTimeOut = kCanSleepMaxTimeReq;
5897 if(gCanSleepTimeout)
5898 {
5899 maxTimeOut = (gCanSleepTimeout*us_per_s);
5900 }
5901 }
5902 context.maxTimeRequested = maxTimeOut;
6d2010ae
A
5903 break;
5904
5905 case kNotifyCapabilityChangePriority:
5906 applyToInterested( gIOPriorityPowerStateInterest,
fe8ab488 5907 pmTellCapabilityClientWithResponse, (void *) &context );
0b4e3aa0
A
5908 break;
5909 }
b0d623f7 5910
55e303ae 5911 // do we have to wait for somebody?
2d21ac55 5912 if ( !checkForDone() )
55e303ae 5913 {
b0d623f7 5914 OUR_PMLog(kPMLogStartAckTimer, context.maxTimeRequested, 0);
6d2010ae
A
5915 if (context.enableTracing)
5916 getPMRootDomain()->traceDetail( context.maxTimeRequested / 1000 );
fe8ab488 5917 start_ack_timer( context.maxTimeRequested / 1000, kMillisecondScale );
1c79356b
A
5918 return false;
5919 }
2d21ac55 5920
b0d623f7 5921exit:
55e303ae 5922 // everybody responded
b0d623f7
A
5923 if (fResponseArray)
5924 {
5925 fResponseArray->release();
5926 fResponseArray = NULL;
5927 }
5928 if (fNotifyClientArray)
5929 {
5930 fNotifyClientArray->release();
5931 fNotifyClientArray = NULL;
5932 }
5933
1c79356b
A
5934 return true;
5935}
5936
1c79356b 5937//*********************************************************************************
2d21ac55 5938// [static private] pmTellAppWithResponse
1c79356b
A
5939//
5940// We send a message to an application, and we expect a response, so we compute a
5941// cookie we can identify the response with.
5942//*********************************************************************************
2d21ac55 5943
39236c6e 5944void IOService::pmTellAppWithResponse( OSObject * object, void * arg )
1c79356b 5945{
6d2010ae 5946 IOPMInterestContext * context = (IOPMInterestContext *) arg;
b0d623f7 5947 IOServicePM * pwrMgt = context->us->pwrMgt;
6d2010ae 5948 uint32_t msgIndex, msgRef, msgType;
316670eb
A
5949 OSNumber *clientID = NULL;
5950 proc_t proc = NULL;
5951 boolean_t proc_suspended = FALSE;
fe8ab488 5952 OSObject * waitForReply = kOSBooleanTrue;
6d2010ae 5953#if LOG_APP_RESPONSE_TIMES
b0d623f7 5954 AbsoluteTime now;
6d2010ae 5955#endif
91447636 5956
b0d623f7 5957 if (!OSDynamicCast(_IOServiceInterestNotifier, object))
6d2010ae
A
5958 return;
5959
316670eb
A
5960 if (context->us == getPMRootDomain())
5961 {
5962 if ((clientID = copyClientIDForNotification(object, context)))
5963 {
5964 uint32_t clientPID = clientID->unsigned32BitValue();
5965 clientID->release();
5966 proc = proc_find(clientPID);
5967
5968 if (proc)
5969 {
5970 proc_suspended = get_task_pidsuspended((task_t) proc->task);
5971 proc_rele(proc);
5972
5973 if (proc_suspended)
5974 {
5975 logClientIDForNotification(object, context, "PMTellAppWithResponse - Suspended");
5976 return;
5977 }
5978 }
5979 }
5980 }
fe8ab488 5981
6d2010ae 5982 if (context->messageFilter &&
fe8ab488 5983 !context->messageFilter(context->us, object, context, 0, &waitForReply))
55e303ae 5984 {
6d2010ae
A
5985 if (kIOLogDebugPower & gIOKitDebug)
5986 {
316670eb 5987 logClientIDForNotification(object, context, "DROP App");
6d2010ae 5988 }
b0d623f7
A
5989 return;
5990 }
2d21ac55 5991
6d2010ae
A
5992 // Create client array (for tracking purposes) only if the service
5993 // has app clients. Usually only root domain does.
b0d623f7 5994 if (0 == context->notifyClients)
b0d623f7 5995 context->notifyClients = OSArray::withCapacity( 32 );
6d2010ae
A
5996
5997 msgType = context->messageType;
5998 msgIndex = context->responseArray->getCount();
5999 msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
6000
6001 OUR_PMLog(kPMLogAppNotify, msgType, msgRef);
6002 if (kIOLogDebugPower & gIOKitDebug)
6003 {
316670eb 6004 logClientIDForNotification(object, context, "MESG App");
b0d623f7
A
6005 }
6006
fe8ab488
A
6007 if (waitForReply == kOSBooleanTrue)
6008 {
6d2010ae 6009#if LOG_APP_RESPONSE_TIMES
fe8ab488
A
6010 OSNumber * num;
6011 clock_get_uptime(&now);
6012 num = OSNumber::withNumber(AbsoluteTime_to_scalar(&now), sizeof(uint64_t) * 8);
6013 if (num)
6014 {
6015 context->responseArray->setObject(msgIndex, num);
6016 num->release();
6017 }
6018 else
6019#endif
6020 context->responseArray->setObject(msgIndex, kOSBooleanFalse);
6021 }
6022 else
b0d623f7 6023 {
fe8ab488
A
6024 context->responseArray->setObject(msgIndex, kOSBooleanTrue);
6025 if (kIOLogDebugPower & gIOKitDebug)
6026 {
6027 logClientIDForNotification(object, context, "App response ignored");
6028 }
b0d623f7 6029 }
6d2010ae
A
6030
6031 if (context->notifyClients)
6032 context->notifyClients->setObject(msgIndex, object);
6033
39236c6e 6034 context->us->messageClient(msgType, object, (void *)(uintptr_t) msgRef);
6d2010ae
A
6035}
6036
6037//*********************************************************************************
6038// [static private] pmTellClientWithResponse
6039//
6040// We send a message to an in-kernel client, and we expect a response,
6041// so we compute a cookie we can identify the response with.
6042//*********************************************************************************
6043
39236c6e 6044void IOService::pmTellClientWithResponse( OSObject * object, void * arg )
6d2010ae
A
6045{
6046 IOPowerStateChangeNotification notify;
6047 IOPMInterestContext * context = (IOPMInterestContext *) arg;
6048 OSObject * replied = kOSBooleanTrue;
6049 _IOServiceInterestNotifier * notifier;
6050 uint32_t msgIndex, msgRef, msgType;
6051 IOReturn retCode;
6052
6053 if (context->messageFilter &&
6054 !context->messageFilter(context->us, object, context, 0, 0))
b0d623f7 6055 {
6d2010ae
A
6056 if ((kIOLogDebugPower & gIOKitDebug) &&
6057 (OSDynamicCast(_IOServiceInterestNotifier, object)))
6058 {
6059 _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
6060 PM_LOG("%s DROP Client %s, notifier %p, handler %p\n",
6061 context->us->getName(),
6062 getIOMessageString(context->messageType),
39236c6e 6063 OBFUSCATE(object), OBFUSCATE(n->handler));
fe8ab488 6064 }
6d2010ae
A
6065 return;
6066 }
b0d623f7 6067
6d2010ae
A
6068 notifier = OSDynamicCast(_IOServiceInterestNotifier, object);
6069 msgType = context->messageType;
6070 msgIndex = context->responseArray->getCount();
6071 msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
6072
6073 IOServicePM * pwrMgt = context->us->pwrMgt;
6074 if (gIOKitDebug & kIOLogPower) {
fe8ab488
A
6075 OUR_PMLog(kPMLogClientNotify, msgRef, msgType);
6076 if (OSDynamicCast(IOService, object)) {
6077 const char *who = ((IOService *) object)->getName();
6078 gPlatform->PMLog(who, kPMLogClientNotify, (uintptr_t) object, 0);
6079 }
6d2010ae 6080 else if (notifier) {
fe8ab488 6081 OUR_PMLog(kPMLogClientNotify, (uintptr_t) notifier->handler, 0);
6d2010ae
A
6082 }
6083 }
6084 if ((kIOLogDebugPower & gIOKitDebug) && notifier)
6085 {
6086 PM_LOG("%s MESG Client %s, notifier %p, handler %p\n",
6087 context->us->getName(),
6088 getIOMessageString(msgType),
39236c6e 6089 OBFUSCATE(object), OBFUSCATE(notifier->handler));
6d2010ae
A
6090 }
6091
6092 notify.powerRef = (void *)(uintptr_t) msgRef;
6093 notify.returnValue = 0;
6094 notify.stateNumber = context->stateNumber;
6095 notify.stateFlags = context->stateFlags;
6096
6097 if (context->enableTracing && (notifier != 0))
6098 {
6099 uint32_t detail = ((msgIndex & 0xff) << 24) |
6100 ((msgType & 0xfff) << 12) |
6101 (((uintptr_t) notifier->handler) & 0xfff);
6102 getPMRootDomain()->traceDetail( detail );
6103 }
6104
7ddcb079 6105 retCode = context->us->messageClient(msgType, object, (void *) &notify, sizeof(notify));
316670eb
A
6106
6107 if (kIOReturnSuccess == retCode)
6d2010ae 6108 {
316670eb 6109 if (0 == notify.returnValue) {
fe8ab488 6110 OUR_PMLog(kPMLogClientAcknowledge, msgRef, (uintptr_t) object);
316670eb 6111 } else {
6d2010ae
A
6112 replied = kOSBooleanFalse;
6113 if ( notify.returnValue > context->maxTimeRequested )
6114 {
6115 if (notify.returnValue > kPriorityClientMaxWait)
6116 {
6117 context->maxTimeRequested = kPriorityClientMaxWait;
6118 PM_ERROR("%s: client %p returned %llu for %s\n",
6119 context->us->getName(),
39236c6e 6120 notifier ? (void *) OBFUSCATE(notifier->handler) : OBFUSCATE(object),
6d2010ae
A
6121 (uint64_t) notify.returnValue,
6122 getIOMessageString(msgType));
6123 }
6124 else
6125 context->maxTimeRequested = notify.returnValue;
6126 }
b0d623f7 6127 }
316670eb 6128 } else {
6d2010ae
A
6129 // not a client of ours
6130 // so we won't be waiting for response
fe8ab488 6131 OUR_PMLog(kPMLogClientAcknowledge, msgRef, 0);
6d2010ae
A
6132 }
6133
6134 context->responseArray->setObject(msgIndex, replied);
6135}
6136
6137//*********************************************************************************
6138// [static private] pmTellCapabilityAppWithResponse
6139//*********************************************************************************
2d21ac55 6140
39236c6e 6141void IOService::pmTellCapabilityAppWithResponse( OSObject * object, void * arg )
6d2010ae
A
6142{
6143 IOPMSystemCapabilityChangeParameters msgArg;
6144 IOPMInterestContext * context = (IOPMInterestContext *) arg;
6145 OSObject * replied = kOSBooleanTrue;
6146 IOServicePM * pwrMgt = context->us->pwrMgt;
6147 uint32_t msgIndex, msgRef, msgType;
6148#if LOG_APP_RESPONSE_TIMES
6149 AbsoluteTime now;
6150#endif
6151
6152 if (!OSDynamicCast(_IOServiceInterestNotifier, object))
6153 return;
6154
6155 memset(&msgArg, 0, sizeof(msgArg));
6156 if (context->messageFilter &&
6157 !context->messageFilter(context->us, object, context, &msgArg, &replied))
6158 {
6159 return;
6160 }
6161
6162 // Create client array (for tracking purposes) only if the service
6163 // has app clients. Usually only root domain does.
6164 if (0 == context->notifyClients)
6165 context->notifyClients = OSArray::withCapacity( 32 );
6166
6167 msgType = context->messageType;
6168 msgIndex = context->responseArray->getCount();
6169 msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
6170
6171 OUR_PMLog(kPMLogAppNotify, msgType, msgRef);
6172 if (kIOLogDebugPower & gIOKitDebug)
6173 {
6174 // Log client pid/name and client array index.
316670eb
A
6175 OSNumber * clientID = NULL;
6176 OSString * clientIDString = NULL;;
6d2010ae 6177 context->us->messageClient(kIOMessageCopyClientID, object, &clientID);
316670eb
A
6178 if (clientID) {
6179 clientIDString = IOCopyLogNameForPID(clientID->unsigned32BitValue());
6180 }
fe8ab488 6181
6d2010ae
A
6182 PM_LOG("%s MESG App(%u) %s, wait %u, %s\n",
6183 context->us->getName(),
6184 msgIndex, getIOMessageString(msgType),
6185 (replied != kOSBooleanTrue),
316670eb 6186 clientIDString ? clientIDString->getCStringNoCopy() : "");
6d2010ae 6187 if (clientID) clientID->release();
316670eb 6188 if (clientIDString) clientIDString->release();
6d2010ae
A
6189 }
6190
6191 msgArg.notifyRef = msgRef;
6192 msgArg.maxWaitForReply = 0;
6193
6194 if (replied == kOSBooleanTrue)
6195 {
6196 msgArg.notifyRef = 0;
6197 context->responseArray->setObject(msgIndex, kOSBooleanTrue);
6198 if (context->notifyClients)
6199 context->notifyClients->setObject(msgIndex, kOSBooleanTrue);
6200 }
6201 else
6202 {
2d21ac55
A
6203#if LOG_APP_RESPONSE_TIMES
6204 OSNumber * num;
6205 clock_get_uptime(&now);
6206 num = OSNumber::withNumber(AbsoluteTime_to_scalar(&now), sizeof(uint64_t) * 8);
6207 if (num)
6208 {
6d2010ae 6209 context->responseArray->setObject(msgIndex, num);
2d21ac55
A
6210 num->release();
6211 }
6212 else
6213#endif
6d2010ae 6214 context->responseArray->setObject(msgIndex, kOSBooleanFalse);
2d21ac55 6215
6d2010ae
A
6216 if (context->notifyClients)
6217 context->notifyClients->setObject(msgIndex, object);
1c79356b 6218 }
b0d623f7 6219
6d2010ae 6220 context->us->messageClient(msgType, object, (void *) &msgArg, sizeof(msgArg));
1c79356b
A
6221}
6222
1c79356b 6223//*********************************************************************************
6d2010ae 6224// [static private] pmTellCapabilityClientWithResponse
1c79356b 6225//*********************************************************************************
2d21ac55 6226
6d2010ae
A
6227void IOService::pmTellCapabilityClientWithResponse(
6228 OSObject * object, void * arg )
1c79356b 6229{
6d2010ae 6230 IOPMSystemCapabilityChangeParameters msgArg;
b0d623f7 6231 IOPMInterestContext * context = (IOPMInterestContext *) arg;
6d2010ae
A
6232 OSObject * replied = kOSBooleanTrue;
6233 _IOServiceInterestNotifier * notifier;
6234 uint32_t msgIndex, msgRef, msgType;
b0d623f7 6235 IOReturn retCode;
2d21ac55 6236
6d2010ae
A
6237 memset(&msgArg, 0, sizeof(msgArg));
6238 if (context->messageFilter &&
6239 !context->messageFilter(context->us, object, context, &msgArg, 0))
6240 {
6241 if ((kIOLogDebugPower & gIOKitDebug) &&
6242 (OSDynamicCast(_IOServiceInterestNotifier, object)))
6243 {
6244 _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
6245 PM_LOG("%s DROP Client %s, notifier %p, handler %p\n",
6246 context->us->getName(),
6247 getIOMessageString(context->messageType),
39236c6e 6248 OBFUSCATE(object), OBFUSCATE(n->handler));
fe8ab488 6249 }
b0d623f7 6250 return;
6d2010ae 6251 }
0b4e3aa0 6252
6d2010ae
A
6253 notifier = OSDynamicCast(_IOServiceInterestNotifier, object);
6254 msgType = context->messageType;
6255 msgIndex = context->responseArray->getCount();
6256 msgRef = ((context->serialNumber & 0xFFFF) << 16) + (msgIndex & 0xFFFF);
b0d623f7
A
6257
6258 IOServicePM * pwrMgt = context->us->pwrMgt;
91447636 6259 if (gIOKitDebug & kIOLogPower) {
fe8ab488
A
6260 OUR_PMLog(kPMLogClientNotify, msgRef, msgType);
6261 if (OSDynamicCast(IOService, object)) {
6262 const char *who = ((IOService *) object)->getName();
6263 gPlatform->PMLog(who, kPMLogClientNotify, (uintptr_t) object, 0);
6264 }
6d2010ae 6265 else if (notifier) {
fe8ab488
A
6266 OUR_PMLog(kPMLogClientNotify, (uintptr_t) notifier->handler, 0);
6267 }
91447636 6268 }
6d2010ae
A
6269 if ((kIOLogDebugPower & gIOKitDebug) && notifier)
6270 {
6271 PM_LOG("%s MESG Client %s, notifier %p, handler %p\n",
6272 context->us->getName(),
6273 getIOMessageString(msgType),
39236c6e 6274 OBFUSCATE(object), OBFUSCATE(notifier->handler));
6d2010ae 6275 }
91447636 6276
6d2010ae
A
6277 msgArg.notifyRef = msgRef;
6278 msgArg.maxWaitForReply = 0;
6279
6280 if (context->enableTracing && (notifier != 0))
6281 {
6282 uint32_t detail = ((msgIndex & 0xff) << 24) |
6283 ((msgType & 0xfff) << 12) |
6284 (((uintptr_t) notifier->handler) & 0xfff);
6285 getPMRootDomain()->traceDetail( detail );
6286 }
6287
6288 retCode = context->us->messageClient(
6289 msgType, object, (void *) &msgArg, sizeof(msgArg));
6290
6291 if ( kIOReturnSuccess == retCode )
55e303ae 6292 {
6d2010ae 6293 if ( 0 == msgArg.maxWaitForReply )
55e303ae
A
6294 {
6295 // client doesn't want time to respond
fe8ab488 6296 OUR_PMLog(kPMLogClientAcknowledge, msgRef, (uintptr_t) object);
6d2010ae
A
6297 }
6298 else
6299 {
6300 replied = kOSBooleanFalse;
6301 if ( msgArg.maxWaitForReply > context->maxTimeRequested )
55e303ae 6302 {
6d2010ae 6303 if (msgArg.maxWaitForReply > kCapabilityClientMaxWait)
55e303ae 6304 {
6d2010ae
A
6305 context->maxTimeRequested = kCapabilityClientMaxWait;
6306 PM_ERROR("%s: client %p returned %u for %s\n",
6307 context->us->getName(),
39236c6e 6308 notifier ? (void *) OBFUSCATE(notifier->handler) : OBFUSCATE(object),
6d2010ae
A
6309 msgArg.maxWaitForReply,
6310 getIOMessageString(msgType));
1c79356b 6311 }
6d2010ae
A
6312 else
6313 context->maxTimeRequested = msgArg.maxWaitForReply;
1c79356b 6314 }
1c79356b 6315 }
6d2010ae
A
6316 }
6317 else
6318 {
55e303ae 6319 // not a client of ours
55e303ae 6320 // so we won't be waiting for response
fe8ab488 6321 OUR_PMLog(kPMLogClientAcknowledge, msgRef, 0);
1c79356b 6322 }
6d2010ae
A
6323
6324 context->responseArray->setObject(msgIndex, replied);
1c79356b
A
6325}
6326
1c79356b 6327//*********************************************************************************
b0d623f7 6328// [public] tellNoChangeDown
1c79356b
A
6329//
6330// Notify registered applications and kernel clients that we are not
6331// dropping power.
6332//
6333// Subclass can override this to send a different message type. Parameter is
6334// the aborted destination state number.
6335//*********************************************************************************
6336
39236c6e 6337void IOService::tellNoChangeDown( unsigned long )
1c79356b 6338{
2d21ac55 6339 return tellClients( kIOMessageDeviceWillNotPowerOff );
1c79356b
A
6340}
6341
1c79356b 6342//*********************************************************************************
b0d623f7 6343// [public] tellChangeUp
1c79356b
A
6344//
6345// Notify registered applications and kernel clients that we are raising power.
6346//
6347// Subclass can override this to send a different message type. Parameter is
6348// the aborted destination state number.
6349//*********************************************************************************
6350
39236c6e 6351void IOService::tellChangeUp( unsigned long )
1c79356b 6352{
2d21ac55 6353 return tellClients( kIOMessageDeviceHasPoweredOn );
1c79356b
A
6354}
6355
1c79356b 6356//*********************************************************************************
b0d623f7 6357// [protected] tellClients
1c79356b
A
6358//
6359// Notify registered applications and kernel clients of something.
6360//*********************************************************************************
6361
39236c6e 6362void IOService::tellClients( int messageType )
b0d623f7
A
6363{
6364 IOPMInterestContext context;
1c79356b 6365
6d2010ae
A
6366 RD_LOG("tellClients( %s )\n", getIOMessageString(messageType));
6367
6368 memset(&context, 0, sizeof(context));
6369 context.messageType = messageType;
6370 context.isPreChange = fIsPreChange;
6371 context.us = this;
6372 context.stateNumber = fHeadNotePowerState;
6373 context.stateFlags = fHeadNotePowerArrayEntry->capabilityFlags;
6374 context.changeFlags = fHeadNoteChangeFlags;
6375 context.messageFilter = (IS_ROOT_DOMAIN) ?
6376 OSMemberFunctionCast(
6377 IOPMMessageFilter,
6378 this,
6379 &IOPMrootDomain::systemMessageFilter) : 0;
6380
6381 context.notifyType = kNotifyPriority;
b0d623f7
A
6382 applyToInterested( gIOPriorityPowerStateInterest,
6383 tellKernelClientApplier, (void *) &context );
6d2010ae
A
6384
6385 context.notifyType = kNotifyApps;
b0d623f7
A
6386 applyToInterested( gIOAppPowerStateInterest,
6387 tellAppClientApplier, (void *) &context );
6388
6389 applyToInterested( gIOGeneralInterest,
6390 tellKernelClientApplier, (void *) &context );
1c79356b
A
6391}
6392
1c79356b 6393//*********************************************************************************
b0d623f7 6394// [private] tellKernelClientApplier
1c79356b 6395//
b0d623f7 6396// Message a kernel client.
1c79356b 6397//*********************************************************************************
2d21ac55 6398
39236c6e 6399static void tellKernelClientApplier( OSObject * object, void * arg )
1c79356b 6400{
fe8ab488 6401 IOPowerStateChangeNotification notify;
6d2010ae 6402 IOPMInterestContext * context = (IOPMInterestContext *) arg;
1c79356b 6403
6d2010ae
A
6404 if (context->messageFilter &&
6405 !context->messageFilter(context->us, object, context, 0, 0))
6406 {
6407 if ((kIOLogDebugPower & gIOKitDebug) &&
6408 (OSDynamicCast(_IOServiceInterestNotifier, object)))
6409 {
6410 _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
6411 PM_LOG("%s DROP Client %s, notifier %p, handler %p\n",
6412 context->us->getName(),
6413 IOService::getIOMessageString(context->messageType),
39236c6e 6414 OBFUSCATE(object), OBFUSCATE(n->handler));
fe8ab488 6415 }
b0d623f7 6416 return;
6d2010ae 6417 }
b0d623f7
A
6418
6419 notify.powerRef = (void *) 0;
fe8ab488
A
6420 notify.returnValue = 0;
6421 notify.stateNumber = context->stateNumber;
6422 notify.stateFlags = context->stateFlags;
b0d623f7 6423
7ddcb079 6424 context->us->messageClient(context->messageType, object, &notify, sizeof(notify));
6d2010ae
A
6425
6426 if ((kIOLogDebugPower & gIOKitDebug) &&
6427 (OSDynamicCast(_IOServiceInterestNotifier, object)))
6428 {
6429 _IOServiceInterestNotifier *n = (_IOServiceInterestNotifier *) object;
6430 PM_LOG("%s MESG Client %s, notifier %p, handler %p\n",
6431 context->us->getName(),
6432 IOService::getIOMessageString(context->messageType),
39236c6e 6433 OBFUSCATE(object), OBFUSCATE(n->handler));
6d2010ae 6434 }
b0d623f7
A
6435}
6436
316670eb 6437static OSNumber * copyClientIDForNotification(
fe8ab488 6438 OSObject *object,
316670eb
A
6439 IOPMInterestContext *context)
6440{
6441 OSNumber *clientID = NULL;
6442 context->us->messageClient(kIOMessageCopyClientID, object, &clientID);
6443 return clientID;
6444}
6445
6446static void logClientIDForNotification(
6447 OSObject *object,
fe8ab488 6448 IOPMInterestContext *context,
316670eb
A
6449 const char *logString)
6450{
6451 OSString *logClientID = NULL;
fe8ab488 6452 OSNumber *clientID = copyClientIDForNotification(object, context);
316670eb 6453
fe8ab488 6454 if (logString)
316670eb
A
6455 {
6456 if (clientID)
6457 logClientID = IOCopyLogNameForPID(clientID->unsigned32BitValue());
fe8ab488 6458
316670eb
A
6459 PM_LOG("%s %s %s, %s\n",
6460 context->us->getName(), logString,
6461 IOService::getIOMessageString(context->messageType),
6462 logClientID ? logClientID->getCStringNoCopy() : "");
6463
fe8ab488 6464 if (logClientID)
316670eb
A
6465 logClientID->release();
6466 }
fe8ab488
A
6467
6468 if (clientID)
316670eb
A
6469 clientID->release();
6470
6471 return;
6472}
6473
39236c6e 6474static void tellAppClientApplier( OSObject * object, void * arg )
b0d623f7 6475{
6d2010ae 6476 IOPMInterestContext * context = (IOPMInterestContext *) arg;
316670eb
A
6477 OSNumber * clientID = NULL;
6478 proc_t proc = NULL;
6479 boolean_t proc_suspended = FALSE;
fe8ab488 6480
316670eb
A
6481 if (context->us == IOService::getPMRootDomain())
6482 {
6483 if ((clientID = copyClientIDForNotification(object, context)))
6484 {
6485 uint32_t clientPID = clientID->unsigned32BitValue();
6486 clientID->release();
6487 proc = proc_find(clientPID);
6488
6489 if (proc)
6490 {
6491 proc_suspended = get_task_pidsuspended((task_t) proc->task);
6492 proc_rele(proc);
6493
6494 if (proc_suspended)
6495 {
6496 logClientIDForNotification(object, context, "tellAppClientApplier - Suspended");
6497 return;
6498 }
6499 }
6500 }
6501 }
b0d623f7 6502
6d2010ae
A
6503 if (context->messageFilter &&
6504 !context->messageFilter(context->us, object, context, 0, 0))
6505 {
6506 if (kIOLogDebugPower & gIOKitDebug)
6507 {
316670eb 6508 logClientIDForNotification(object, context, "DROP App");
6d2010ae 6509 }
b0d623f7 6510 return;
6d2010ae
A
6511 }
6512
6513 if (kIOLogDebugPower & gIOKitDebug)
6514 {
316670eb 6515 logClientIDForNotification(object, context, "MESG App");
6d2010ae 6516 }
0b4e3aa0 6517
6d2010ae 6518 context->us->messageClient(context->messageType, object, 0);
1c79356b
A
6519}
6520
2d21ac55
A
6521//*********************************************************************************
6522// [private] checkForDone
6523//*********************************************************************************
1c79356b 6524
39236c6e 6525bool IOService::checkForDone( void )
1c79356b 6526{
fe8ab488
A
6527 int i = 0;
6528 OSObject * theFlag;
1c79356b 6529
316670eb 6530 if (fResponseArray == NULL) {
1c79356b
A
6531 return true;
6532 }
fe8ab488 6533
316670eb 6534 for (i = 0; ; i++) {
2d21ac55 6535 theFlag = fResponseArray->getObject(i);
316670eb
A
6536
6537 if (NULL == theFlag) {
1c79356b
A
6538 break;
6539 }
316670eb
A
6540
6541 if (kOSBooleanTrue != theFlag) {
1c79356b
A
6542 return false;
6543 }
6544 }
1c79356b
A
6545 return true;
6546}
6547
2d21ac55
A
6548//*********************************************************************************
6549// [public] responseValid
6550//*********************************************************************************
1c79356b 6551
39236c6e 6552bool IOService::responseValid( uint32_t refcon, int pid )
2d21ac55 6553{
fe8ab488
A
6554 UInt16 serialComponent;
6555 UInt16 ordinalComponent;
6556 OSObject * theFlag;
6557 OSObject *object = 0;
2d21ac55
A
6558
6559 serialComponent = (refcon >> 16) & 0xFFFF;
6560 ordinalComponent = (refcon & 0xFFFF);
6561
6562 if ( serialComponent != fSerialNumber )
55e303ae 6563 {
1c79356b
A
6564 return false;
6565 }
fe8ab488 6566
2d21ac55 6567 if ( fResponseArray == NULL )
55e303ae 6568 {
1c79356b
A
6569 return false;
6570 }
fe8ab488 6571
2d21ac55 6572 theFlag = fResponseArray->getObject(ordinalComponent);
fe8ab488 6573
2d21ac55 6574 if ( theFlag == 0 )
55e303ae 6575 {
1c79356b
A
6576 return false;
6577 }
2d21ac55 6578
fe8ab488
A
6579 if (fNotifyClientArray)
6580 object = fNotifyClientArray->getObject(ordinalComponent);
6581
2d21ac55
A
6582 OSNumber * num;
6583 if ((num = OSDynamicCast(OSNumber, theFlag)))
6584 {
6585#if LOG_APP_RESPONSE_TIMES
fe8ab488
A
6586 AbsoluteTime now;
6587 AbsoluteTime start;
6d2010ae 6588 uint64_t nsec;
39236c6e 6589 char name[128];
2d21ac55 6590
39236c6e
A
6591 name[0] = '\0';
6592 proc_name(pid, name, sizeof(name));
2d21ac55
A
6593 clock_get_uptime(&now);
6594 AbsoluteTime_to_scalar(&start) = num->unsigned64BitValue();
6595 SUB_ABSOLUTETIME(&now, &start);
6596 absolutetime_to_nanoseconds(now, &nsec);
6d2010ae
A
6597
6598 if (kIOLogDebugPower & gIOKitDebug)
6599 {
6600 PM_LOG("Ack(%u) %u ms\n",
6601 (uint32_t) ordinalComponent,
6602 NS_TO_MS(nsec));
6603 }
2d21ac55
A
6604
6605 // > 100 ms
6606 if (nsec > LOG_APP_RESPONSE_TIMES)
6607 {
fe8ab488 6608 IOLog("PM response took %d ms (%d, %s)\n", NS_TO_MS(nsec),
39236c6e 6609 pid, name);
fe8ab488 6610 }
b0d623f7 6611
fe8ab488
A
6612 if (nsec > LOG_APP_RESPONSE_MSG_TRACER)
6613 {
6614 // TODO: populate the messageType argument
6615 getPMRootDomain()->pmStatsRecordApplicationResponse(
6616 gIOPMStatsApplicationResponseSlow,
6617 name, 0, NS_TO_MS(nsec), pid, object);
6618 }
6619 else
6620 {
6621 getPMRootDomain()->pmStatsRecordApplicationResponse(
6622 gIOPMStatsApplicationResponsePrompt,
6623 name, 0, NS_TO_MS(nsec), pid, object);
2d21ac55 6624 }
6d2010ae 6625
2d21ac55
A
6626#endif
6627 theFlag = kOSBooleanFalse;
6628 }
fe8ab488
A
6629 else if (object) {
6630 getPMRootDomain()->pmStatsRecordApplicationResponse(
6631 gIOPMStatsApplicationResponsePrompt,
6632 0, 0, 0, pid, object);
6633
6634 }
2d21ac55 6635
fe8ab488 6636 if ( kOSBooleanFalse == theFlag )
55e303ae 6637 {
2d21ac55 6638 fResponseArray->replaceObject(ordinalComponent, kOSBooleanTrue);
1c79356b 6639 }
fe8ab488 6640
1c79356b
A
6641 return true;
6642}
6643
2d21ac55 6644//*********************************************************************************
b0d623f7 6645// [public] allowPowerChange
1c79356b
A
6646//
6647// Our power state is about to lower, and we have notified applications
6648// and kernel clients, and one of them has acknowledged. If this is the last to do
6649// so, and all acknowledgements are positive, we continue with the power change.
2d21ac55
A
6650//*********************************************************************************
6651
39236c6e 6652IOReturn IOService::allowPowerChange( unsigned long refcon )
1c79356b 6653{
fe8ab488 6654 IOPMRequest * request;
2d21ac55
A
6655
6656 if ( !initialized )
55e303ae
A
6657 {
6658 // we're unloading
6659 return kIOReturnSuccess;
1c79356b
A
6660 }
6661
fe8ab488
A
6662 request = acquirePMRequest( this, kIOPMRequestTypeAllowPowerChange );
6663 if (!request)
6664 return kIOReturnNoMemory;
2d21ac55 6665
fe8ab488
A
6666 request->fArg0 = (void *) refcon;
6667 request->fArg1 = (void *)(uintptr_t) proc_selfpid();
6668 request->fArg2 = (void *) 0;
6669 submitPMRequest( request );
2d21ac55 6670
fe8ab488 6671 return kIOReturnSuccess;
1c79356b 6672}
2d21ac55 6673
b0d623f7 6674#ifndef __LP64__
39236c6e 6675IOReturn IOService::serializedAllowPowerChange2( unsigned long refcon )
1c79356b 6676{
fe8ab488
A
6677 // [deprecated] public
6678 return kIOReturnUnsupported;
1c79356b 6679}
b0d623f7 6680#endif /* !__LP64__ */
1c79356b 6681
2d21ac55 6682//*********************************************************************************
b0d623f7 6683// [public] cancelPowerChange
1c79356b
A
6684//
6685// Our power state is about to lower, and we have notified applications
6686// and kernel clients, and one of them has vetoed the change. If this is the last
6687// client to respond, we abandon the power change.
2d21ac55
A
6688//*********************************************************************************
6689
39236c6e 6690IOReturn IOService::cancelPowerChange( unsigned long refcon )
1c79356b 6691{
fe8ab488 6692 IOPMRequest * request;
39236c6e
A
6693 char name[128];
6694 pid_t pid = proc_selfpid();
2d21ac55
A
6695
6696 if ( !initialized )
55e303ae
A
6697 {
6698 // we're unloading
6699 return kIOReturnSuccess;
1c79356b
A
6700 }
6701
39236c6e
A
6702 name[0] = '\0';
6703 proc_name(pid, name, sizeof(name));
6704 PM_ERROR("PM notification cancel (pid %d, %s)\n", pid, name);
593a1d5f 6705
fe8ab488
A
6706 request = acquirePMRequest( this, kIOPMRequestTypeCancelPowerChange );
6707 if (!request)
b0d623f7 6708 {
b0d623f7
A
6709 return kIOReturnNoMemory;
6710 }
2d21ac55 6711
39236c6e
A
6712 request->fArg0 = (void *) refcon;
6713 request->fArg1 = (void *)(uintptr_t) proc_selfpid();
6714 request->fArg2 = (void *) OSString::withCString(name);
b0d623f7 6715 submitPMRequest( request );
2d21ac55 6716
b0d623f7 6717 return kIOReturnSuccess;
1c79356b
A
6718}
6719
b0d623f7 6720#ifndef __LP64__
39236c6e 6721IOReturn IOService::serializedCancelPowerChange2( unsigned long refcon )
1c79356b 6722{
fe8ab488
A
6723 // [deprecated] public
6724 return kIOReturnUnsupported;
1c79356b
A
6725}
6726
1c79356b
A
6727//*********************************************************************************
6728// PM_Clamp_Timer_Expired
6729//
6730// called when clamp timer expires...set power state to 0.
6731//*********************************************************************************
6732
39236c6e 6733void IOService::PM_Clamp_Timer_Expired( void )
1c79356b 6734{
1c79356b
A
6735}
6736
2d21ac55 6737//*********************************************************************************
91447636 6738// clampPowerOn
1c79356b 6739//
91447636 6740// Set to highest available power state for a minimum of duration milliseconds
2d21ac55 6741//*********************************************************************************
91447636 6742
39236c6e 6743void IOService::clampPowerOn( unsigned long duration )
1c79356b 6744{
91447636 6745}
b0d623f7 6746#endif /* !__LP64__ */
1c79356b 6747
39236c6e
A
6748//*********************************************************************************
6749// configurePowerStateReport
6750//
6751// Configures the IOStateReport for kPMPowerStateChannel
6752//*********************************************************************************
6753IOReturn IOService::configurePowerStatesReport( IOReportConfigureAction action, void *result )
6754{
6755
6756 IOReturn rc = kIOReturnSuccess;
6757 size_t reportSize;
6758 unsigned long i;
6759 uint64_t ts;
6760
fe8ab488 6761 if (!pwrMgt)
39236c6e
A
6762 return kIOReturnUnsupported;
6763
6764 if (!fNumberOfPowerStates)
6765 return kIOReturnSuccess; // For drivers which are in power plane, but haven't called registerPowerDriver()
6766 PM_LOCK();
6767
fe8ab488 6768 switch (action)
39236c6e
A
6769 {
6770 case kIOReportEnable:
fe8ab488 6771 if (fReportBuf)
39236c6e
A
6772 {
6773 fReportClientCnt++;
6774 break;
6775 }
6776 reportSize = STATEREPORT_BUFSIZE(fNumberOfPowerStates);
6777 fReportBuf = IOMalloc(reportSize);
6778 if (!fReportBuf) {
6779 rc = kIOReturnNoMemory;
6780 break;
6781 }
6782 memset(fReportBuf, 0, reportSize);
6783
6784 STATEREPORT_INIT(fNumberOfPowerStates, fReportBuf, reportSize,
6785 getRegistryEntryID(), kPMPowerStatesChID, kIOReportCategoryPower);
6786
6787 for (i = 0; i < fNumberOfPowerStates; i++) {
6788 unsigned bits = 0;
6789
6790 if (fPowerStates[i].capabilityFlags & kIOPMPowerOn)
6791 bits |= kPMReportPowerOn;
6792 if (fPowerStates[i].capabilityFlags & kIOPMDeviceUsable)
6793 bits |= kPMReportDeviceUsable;
6794 if (fPowerStates[i].capabilityFlags & kIOPMLowPower)
6795 bits |= kPMReportLowPower;
6796
fe8ab488 6797 STATEREPORT_SETSTATEID(fReportBuf, i, ((bits & 0xff) << 8) |
39236c6e
A
6798 ((StateOrder(fMaxPowerState) & 0xf) << 4) | (StateOrder(i) & 0xf));
6799 }
6800 ts = mach_absolute_time();
6801 STATEREPORT_SETSTATE(fReportBuf, fCurrentPowerState, ts);
6802 break;
6803
6804 case kIOReportDisable:
6805 if (fReportClientCnt == 0) {
6806 rc = kIOReturnBadArgument;
6807 break;
6808 }
6809 if (fReportClientCnt == 1)
6810 {
6811 IOFree(fReportBuf, STATEREPORT_BUFSIZE(fNumberOfPowerStates));
6812 fReportBuf = NULL;
6813 }
6814 fReportClientCnt--;
6815 break;
6816
6817 case kIOReportGetDimensions:
6818 if (fReportBuf)
6819 STATEREPORT_UPDATERES(fReportBuf, kIOReportGetDimensions, result);
6820 break;
6821 }
6822
6823 PM_UNLOCK();
6824
6825 return rc;
6826}
6827
6828//*********************************************************************************
6829// updatePowerStateReport
6830//
6831// Updates the IOStateReport for kPMPowerStateChannel
6832//*********************************************************************************
6833IOReturn IOService::updatePowerStatesReport( IOReportConfigureAction action, void *result, void *destination )
6834{
6835 uint32_t size2cpy;
6836 void *data2cpy;
6837 uint64_t ts;
6838 IOReturn rc = kIOReturnSuccess;
6839 IOBufferMemoryDescriptor *dest = OSDynamicCast(IOBufferMemoryDescriptor, (OSObject *)destination);
6840
6841
fe8ab488 6842 if (!pwrMgt)
39236c6e 6843 return kIOReturnUnsupported;
fe8ab488 6844 if (!fNumberOfPowerStates)
39236c6e
A
6845 return kIOReturnSuccess;
6846
6847 if ( !result || !dest ) return kIOReturnBadArgument;
6848 PM_LOCK();
6849
6850 switch (action) {
fe8ab488 6851 case kIOReportCopyChannelData:
39236c6e
A
6852 if ( !fReportBuf ) {
6853 rc = kIOReturnNotOpen;
6854 break;
6855 }
6856
6857 ts = mach_absolute_time();
6858 STATEREPORT_UPDATEPREP(fReportBuf, ts, data2cpy, size2cpy);
6859 if (size2cpy > (dest->getCapacity() - dest->getLength()) ) {
6860 rc = kIOReturnOverrun;
6861 break;
6862 }
6863
6864 STATEREPORT_UPDATERES(fReportBuf, kIOReportCopyChannelData, result);
fe8ab488 6865 dest->appendBytes(data2cpy, size2cpy);
39236c6e
A
6866
6867 default:
6868 break;
6869
6870 }
6871
6872 PM_UNLOCK();
6873
6874 return rc;
6875
6876}
6877
6878//*********************************************************************************
6879// configureSimplePowerReport
6880//
fe8ab488 6881// Configures the IOSimpleReport for given channel id
39236c6e
A
6882//*********************************************************************************
6883IOReturn IOService::configureSimplePowerReport(IOReportConfigureAction action, void *result )
6884{
6885
6886 IOReturn rc = kIOReturnSuccess;
6887
fe8ab488 6888 if ( !pwrMgt )
39236c6e
A
6889 return kIOReturnUnsupported;
6890
fe8ab488 6891 if ( !fNumberOfPowerStates )
39236c6e
A
6892 return rc;
6893
fe8ab488 6894 switch (action)
39236c6e
A
6895 {
6896 case kIOReportEnable:
6897 case kIOReportDisable:
6898 break;
6899
6900 case kIOReportGetDimensions:
6901 SIMPLEREPORT_UPDATERES(kIOReportGetDimensions, result);
6902 break;
6903 }
6904
6905
6906 return rc;
6907}
6908
6909//*********************************************************************************
6910// updateSimplePowerReport
6911//
fe8ab488 6912// Updates the IOSimpleReport for the given chanel id
39236c6e
A
6913//*********************************************************************************
6914IOReturn IOService::updateSimplePowerReport( IOReportConfigureAction action, void *result, void *destination )
6915{
6916 uint32_t size2cpy;
6917 void *data2cpy;
fe8ab488 6918 uint64_t buf[SIMPLEREPORT_BUFSIZE/sizeof(uint64_t)+1]; // Force a 8-byte alignment
39236c6e
A
6919 IOBufferMemoryDescriptor *dest = OSDynamicCast(IOBufferMemoryDescriptor, (OSObject *)destination);
6920 IOReturn rc = kIOReturnSuccess;
6921 unsigned bits = 0;
6922
6923
fe8ab488 6924 if ( !pwrMgt )
39236c6e
A
6925 return kIOReturnUnsupported;
6926 if ( !result || !dest ) return kIOReturnBadArgument;
6927
fe8ab488 6928 if ( !fNumberOfPowerStates )
39236c6e
A
6929 return rc;
6930 PM_LOCK();
6931
6932 switch (action) {
fe8ab488 6933 case kIOReportCopyChannelData:
39236c6e
A
6934
6935 SIMPLEREPORT_INIT(buf, sizeof(buf), getRegistryEntryID(), kPMCurrStateChID, kIOReportCategoryPower);
6936
6937 if (fPowerStates[fCurrentPowerState].capabilityFlags & kIOPMPowerOn)
6938 bits |= kPMReportPowerOn;
6939 if (fPowerStates[fCurrentPowerState].capabilityFlags & kIOPMDeviceUsable)
6940 bits |= kPMReportDeviceUsable;
6941 if (fPowerStates[fCurrentPowerState].capabilityFlags & kIOPMLowPower)
6942 bits |= kPMReportLowPower;
6943
6944
fe8ab488 6945 SIMPLEREPORT_SETVALUE(buf, ((bits & 0xff) << 8) | ((StateOrder(fMaxPowerState) & 0xf) << 4) |
39236c6e
A
6946 (StateOrder(fCurrentPowerState) & 0xf));
6947
6948 SIMPLEREPORT_UPDATEPREP(buf, data2cpy, size2cpy);
6949 if (size2cpy > (dest->getCapacity() - dest->getLength())) {
6950 rc = kIOReturnOverrun;
6951 break;
6952 }
6953
6954 SIMPLEREPORT_UPDATERES(kIOReportCopyChannelData, result);
fe8ab488 6955 dest->appendBytes(data2cpy, size2cpy);
39236c6e
A
6956
6957 default:
6958 break;
6959
6960 }
6961
6962 PM_UNLOCK();
6963
6964 return kIOReturnSuccess;
6965
6966}
6967
6968
6969
6d2010ae
A
6970// MARK: -
6971// MARK: Driver Overrides
6972
1c79356b 6973//*********************************************************************************
b0d623f7 6974// [public] setPowerState
1c79356b
A
6975//
6976// Does nothing here. This should be implemented in a subclass driver.
6977//*********************************************************************************
6978
39236c6e 6979IOReturn IOService::setPowerState(
fe8ab488 6980 unsigned long powerStateOrdinal, IOService * whatDevice )
1c79356b
A
6981{
6982 return IOPMNoErr;
6983}
6984
1c79356b 6985//*********************************************************************************
b0d623f7 6986// [public] maxCapabilityForDomainState
1c79356b 6987//
39236c6e
A
6988// Finds the highest power state in the array whose input power requirement
6989// is equal to the input parameter. Where a more intelligent decision is
6990// possible, override this in the subclassed driver.
1c79356b
A
6991//*********************************************************************************
6992
39236c6e 6993IOPMPowerStateIndex IOService::getPowerStateForDomainFlags( IOPMPowerFlags flags )
1c79356b 6994{
39236c6e
A
6995 IOPMPowerStateIndex stateIndex;
6996
6997 if (!fNumberOfPowerStates)
6998 return kPowerStateZero;
6999
7000 for ( int order = fNumberOfPowerStates - 1; order >= 0; order-- )
7001 {
7002 stateIndex = fPowerStates[order].stateOrderToIndex;
7003
7004 if ( (flags & fPowerStates[stateIndex].inputPowerFlags) ==
7005 fPowerStates[stateIndex].inputPowerFlags )
7006 {
7007 return stateIndex;
7008 }
7009 }
7010 return kPowerStateZero;
7011}
1c79356b 7012
39236c6e
A
7013unsigned long IOService::maxCapabilityForDomainState( IOPMPowerFlags domainState )
7014{
7015 return getPowerStateForDomainFlags(domainState);
1c79356b
A
7016}
7017
1c79356b 7018//*********************************************************************************
b0d623f7 7019// [public] initialPowerStateForDomainState
1c79356b 7020//
39236c6e 7021// Called to query the power state for the initial power transition.
1c79356b
A
7022//*********************************************************************************
7023
39236c6e 7024unsigned long IOService::initialPowerStateForDomainState( IOPMPowerFlags domainState )
1c79356b 7025{
bd504ef0
A
7026 if (fResetPowerStateOnWake && (domainState & kIOPMRootDomainState))
7027 {
7028 // Return lowest power state for any root power domain changes
39236c6e 7029 return kPowerStateZero;
bd504ef0
A
7030 }
7031
39236c6e 7032 return getPowerStateForDomainFlags(domainState);
1c79356b
A
7033}
7034
1c79356b 7035//*********************************************************************************
b0d623f7 7036// [public] powerStateForDomainState
1c79356b 7037//
39236c6e 7038// This method is not called from PM.
1c79356b
A
7039//*********************************************************************************
7040
39236c6e 7041unsigned long IOService::powerStateForDomainState( IOPMPowerFlags domainState )
1c79356b 7042{
39236c6e 7043 return getPowerStateForDomainFlags(domainState);
1c79356b
A
7044}
7045
b0d623f7 7046#ifndef __LP64__
1c79356b 7047//*********************************************************************************
b0d623f7 7048// [deprecated] didYouWakeSystem
1c79356b
A
7049//
7050// Does nothing here. This should be implemented in a subclass driver.
7051//*********************************************************************************
7052
39236c6e 7053bool IOService::didYouWakeSystem( void )
1c79356b
A
7054{
7055 return false;
7056}
b0d623f7 7057#endif /* !__LP64__ */
1c79356b 7058
1c79356b 7059//*********************************************************************************
b0d623f7 7060// [public] powerStateWillChangeTo
1c79356b
A
7061//
7062// Does nothing here. This should be implemented in a subclass driver.
7063//*********************************************************************************
7064
39236c6e 7065IOReturn IOService::powerStateWillChangeTo( IOPMPowerFlags, unsigned long, IOService * )
1c79356b 7066{
2d21ac55 7067 return kIOPMAckImplied;
1c79356b
A
7068}
7069
1c79356b 7070//*********************************************************************************
b0d623f7 7071// [public] powerStateDidChangeTo
1c79356b
A
7072//
7073// Does nothing here. This should be implemented in a subclass driver.
7074//*********************************************************************************
7075
39236c6e 7076IOReturn IOService::powerStateDidChangeTo( IOPMPowerFlags, unsigned long, IOService * )
1c79356b 7077{
2d21ac55 7078 return kIOPMAckImplied;
1c79356b
A
7079}
7080
1c79356b 7081//*********************************************************************************
b0d623f7 7082// [protected] powerChangeDone
1c79356b 7083//
2d21ac55 7084// Called from PM work loop thread.
1c79356b
A
7085// Does nothing here. This should be implemented in a subclass policy-maker.
7086//*********************************************************************************
7087
39236c6e 7088void IOService::powerChangeDone( unsigned long )
1c79356b
A
7089{
7090}
7091
b0d623f7 7092#ifndef __LP64__
1c79356b 7093//*********************************************************************************
b0d623f7 7094// [deprecated] newTemperature
1c79356b
A
7095//
7096// Does nothing here. This should be implemented in a subclass driver.
7097//*********************************************************************************
7098
39236c6e 7099IOReturn IOService::newTemperature( long currentTemp, IOService * whichZone )
1c79356b
A
7100{
7101 return IOPMNoErr;
7102}
b0d623f7 7103#endif /* !__LP64__ */
1c79356b 7104
2d21ac55 7105//*********************************************************************************
b0d623f7 7106// [public] systemWillShutdown
2d21ac55
A
7107//
7108// System shutdown and restart notification.
7109//*********************************************************************************
1c79356b 7110
2d21ac55
A
7111void IOService::systemWillShutdown( IOOptionBits specifier )
7112{
fe8ab488
A
7113 IOPMrootDomain * rootDomain = IOService::getPMRootDomain();
7114 if (rootDomain)
7115 rootDomain->acknowledgeSystemWillShutdown( this );
2d21ac55 7116}
1c79356b 7117
6d2010ae
A
7118// MARK: -
7119// MARK: PM State Machine
7120
1c79356b 7121//*********************************************************************************
2d21ac55
A
7122// [private static] acquirePMRequest
7123//*********************************************************************************
7124
7125IOPMRequest *
b0d623f7
A
7126IOService::acquirePMRequest( IOService * target, IOOptionBits requestType,
7127 IOPMRequest * active )
2d21ac55 7128{
fe8ab488 7129 IOPMRequest * request;
2d21ac55 7130
fe8ab488 7131 assert(target);
2d21ac55 7132
fe8ab488
A
7133 request = IOPMRequest::create();
7134 if (request)
7135 {
7136 request->init( target, requestType );
b0d623f7
A
7137 if (active)
7138 {
7139 IOPMRequest * root = active->getRootRequest();
7140 if (root) request->attachRootRequest(root);
7141 }
7142 }
fe8ab488
A
7143 else
7144 {
b0d623f7
A
7145 PM_ERROR("%s: No memory for PM request type 0x%x\n",
7146 target->getName(), (uint32_t) requestType);
fe8ab488
A
7147 }
7148 return request;
2d21ac55
A
7149}
7150
7151//*********************************************************************************
7152// [private static] releasePMRequest
7153//*********************************************************************************
7154
7155void IOService::releasePMRequest( IOPMRequest * request )
7156{
fe8ab488
A
7157 if (request)
7158 {
7159 request->reset();
7160 request->release();
7161 }
2d21ac55
A
7162}
7163
7164//*********************************************************************************
3e170ce0 7165// [private static] submitPMRequest
2d21ac55
A
7166//*********************************************************************************
7167
7168void IOService::submitPMRequest( IOPMRequest * request )
7169{
fe8ab488
A
7170 assert( request );
7171 assert( gIOPMReplyQueue );
7172 assert( gIOPMRequestQueue );
2d21ac55 7173
fe8ab488
A
7174 PM_LOG1("[+ %02lx] %p [%p %s] %p %p %p\n",
7175 (long)request->getType(), OBFUSCATE(request),
7176 OBFUSCATE(request->getTarget()), request->getTarget()->getName(),
7177 OBFUSCATE(request->fArg0),
39236c6e 7178 OBFUSCATE(request->fArg1), OBFUSCATE(request->fArg2));
2d21ac55 7179
fe8ab488
A
7180 if (request->isReplyType())
7181 gIOPMReplyQueue->queuePMRequest( request );
7182 else
7183 gIOPMRequestQueue->queuePMRequest( request );
2d21ac55
A
7184}
7185
3e170ce0 7186void IOService::submitPMRequests( IOPMRequest ** requests, IOItemCount count )
2d21ac55 7187{
fe8ab488
A
7188 assert( requests );
7189 assert( count > 0 );
7190 assert( gIOPMRequestQueue );
7191
7192 for (IOItemCount i = 0; i < count; i++)
7193 {
7194 IOPMRequest * req = requests[i];
7195 PM_LOG1("[+ %02lx] %p [%p %s] %p %p %p\n",
7196 (long)req->getType(), OBFUSCATE(req),
7197 OBFUSCATE(req->getTarget()), req->getTarget()->getName(),
7198 OBFUSCATE(req->fArg0),
39236c6e 7199 OBFUSCATE(req->fArg1), OBFUSCATE(req->fArg2));
fe8ab488 7200 }
2d21ac55 7201
fe8ab488 7202 gIOPMRequestQueue->queuePMRequestChain( requests, count );
2d21ac55
A
7203}
7204
7205//*********************************************************************************
3e170ce0 7206// [private] actionPMRequestQueue
6d2010ae 7207//
3e170ce0 7208// IOPMRequestQueue::checkForWork() passing a new request to the request target.
2d21ac55
A
7209//*********************************************************************************
7210
3e170ce0 7211bool IOService::actionPMRequestQueue(
fe8ab488
A
7212 IOPMRequest * request,
7213 IOPMRequestQueue * queue )
2d21ac55 7214{
6d2010ae 7215 bool more;
2d21ac55 7216
6d2010ae
A
7217 if (initialized)
7218 {
3e170ce0
A
7219 // Work queue will immediately execute the request if the per-service
7220 // request queue is empty. Note pwrMgt is the target's IOServicePM.
2d21ac55 7221
6d2010ae 7222 more = gIOPMWorkQueue->queuePMRequest(request, pwrMgt);
6d2010ae 7223 }
3e170ce0
A
7224 else
7225 {
7226 // Calling PM without PMinit() is not allowed, fail the request.
7227 // Need to signal more when completing attached requests.
2d21ac55 7228
3e170ce0
A
7229 PM_LOG("%s: PM not initialized\n", getName());
7230 PM_LOG1("[- %02x] %p [%p %s] !initialized\n",
7231 request->getType(), OBFUSCATE(request),
7232 OBFUSCATE(this), getName());
7233
7234 more = gIOPMCompletionQueue->queuePMRequest(request);
7235 if (more) gIOPMWorkQueue->incrementProducerCount();
7236 }
2d21ac55 7237
fe8ab488 7238 return more;
2d21ac55
A
7239}
7240
7241//*********************************************************************************
3e170ce0 7242// [private] actionPMCompletionQueue
2d21ac55 7243//
3e170ce0
A
7244// IOPMCompletionQueue::checkForWork() passing a completed request to the
7245// request target.
2d21ac55
A
7246//*********************************************************************************
7247
3e170ce0 7248bool IOService::actionPMCompletionQueue(
fe8ab488
A
7249 IOPMRequest * request,
7250 IOPMCompletionQueue * queue )
2d21ac55 7251{
3e170ce0 7252 bool more = (request->getNextRequest() != 0);
b0d623f7
A
7253 IOPMRequest * root = request->getRootRequest();
7254
7255 if (root && (root != request))
7256 more = true;
6d2010ae
A
7257 if (more)
7258 gIOPMWorkQueue->incrementProducerCount();
060df5ea 7259
fe8ab488
A
7260 releasePMRequest( request );
7261 return more;
2d21ac55
A
7262}
7263
7264//*********************************************************************************
3e170ce0 7265// [private] actionPMWorkQueueRetire
1c79356b 7266//
3e170ce0 7267// IOPMWorkQueue::checkForWork() passing a retired request to the request target.
1c79356b 7268//*********************************************************************************
2d21ac55 7269
3e170ce0 7270bool IOService::actionPMWorkQueueRetire( IOPMRequest * request, IOPMWorkQueue * queue )
1c79356b 7271{
fe8ab488 7272 assert(request && queue);
1c79356b 7273
fe8ab488
A
7274 PM_LOG1("[- %02x] %p [%p %s] state %d, busy %d\n",
7275 request->getType(), OBFUSCATE(request),
39236c6e 7276 OBFUSCATE(this), getName(),
3e170ce0 7277 fMachineState, gIOPMBusyRequestCount);
1c79356b 7278
3e170ce0 7279 // Catch requests created by idleTimerExpired()
fe8ab488
A
7280 if (request->getType() == kIOPMRequestTypeActivityTickle)
7281 {
7282 uint32_t tickleFlags = (uint32_t)(uintptr_t) request->fArg1;
7283
7284 if ((tickleFlags & kTickleTypePowerDrop) && fIdleTimerPeriod)
7285 {
7286 restartIdleTimer();
7287 }
7288 else if (tickleFlags == (kTickleTypeActivity | kTickleTypePowerRise))
7289 {
7290 // Invalidate any idle power drop that got queued while
7291 // processing this request.
7292 fIdleTimerGeneration++;
7293 }
db609669 7294 }
3e170ce0
A
7295
7296 // When the completed request is linked, tell work queue there is
7297 // more work pending.
1c79356b 7298
3e170ce0 7299 return (gIOPMCompletionQueue->queuePMRequest( request ));
2d21ac55 7300}
1c79356b 7301
2d21ac55
A
7302//*********************************************************************************
7303// [private] isPMBlocked
7304//
7305// Check if machine state transition is blocked.
7306//*********************************************************************************
1c79356b 7307
39236c6e 7308bool IOService::isPMBlocked( IOPMRequest * request, int count )
2d21ac55 7309{
fe8ab488 7310 int reason = 0;
2d21ac55 7311
fe8ab488
A
7312 do {
7313 if (kIOPM_Finished == fMachineState)
7314 break;
2d21ac55 7315
fe8ab488
A
7316 if (kIOPM_DriverThreadCallDone == fMachineState)
7317 {
2d21ac55
A
7318 // 5 = kDriverCallInformPreChange
7319 // 6 = kDriverCallInformPostChange
7320 // 7 = kDriverCallSetPowerState
39236c6e 7321 // 8 = kRootDomainInformPreChange
fe8ab488 7322 if (fDriverCallBusy)
6d2010ae 7323 reason = 5 + fDriverCallReason;
fe8ab488
A
7324 break;
7325 }
7326
7327 // Waiting on driver's setPowerState() timeout.
7328 if (fDriverTimer)
7329 {
7330 reason = 1; break;
7331 }
7332
7333 // Child or interested driver acks pending.
7334 if (fHeadNotePendingAcks)
7335 {
7336 reason = 2; break;
7337 }
7338
7339 // Waiting on apps or priority power interest clients.
7340 if (fResponseArray)
7341 {
7342 reason = 3; break;
7343 }
7344
7345 // Waiting on settle timer expiration.
7346 if (fSettleTimeUS)
7347 {
7348 reason = 4; break;
7349 }
7350 } while (false);
7351
7352 fWaitReason = reason;
7353
7354 if (reason)
7355 {
7356 if (count)
7357 {
7358 PM_LOG1("[B %02x] %p [%p %s] state %d, reason %d\n",
7359 request->getType(), OBFUSCATE(request),
39236c6e 7360 OBFUSCATE(this), getName(),
fe8ab488
A
7361 fMachineState, reason);
7362 }
2d21ac55 7363
fe8ab488
A
7364 return true;
7365 }
1c79356b 7366
fe8ab488 7367 return false;
1c79356b
A
7368}
7369
2d21ac55 7370//*********************************************************************************
3e170ce0 7371// [private] actionPMWorkQueueInvoke
2d21ac55 7372//
3e170ce0
A
7373// IOPMWorkQueue::checkForWork() passing a request to the
7374// request target for execution.
2d21ac55
A
7375//*********************************************************************************
7376
3e170ce0 7377bool IOService::actionPMWorkQueueInvoke( IOPMRequest * request, IOPMWorkQueue * queue )
2d21ac55 7378{
fe8ab488
A
7379 bool done = false;
7380 int loop = 0;
2d21ac55 7381
fe8ab488 7382 assert(request && queue);
2d21ac55 7383
fe8ab488
A
7384 while (isPMBlocked(request, loop++) == false)
7385 {
7386 PM_LOG1("[W %02x] %p [%p %s] state %d\n",
7387 request->getType(), OBFUSCATE(request),
39236c6e 7388 OBFUSCATE(this), getName(), fMachineState);
2d21ac55 7389
fe8ab488 7390 gIOPMRequest = request;
3e170ce0 7391 gIOPMWorkInvokeCount++;
2d21ac55 7392
fe8ab488 7393 // Every PM machine states must be handled in one of the cases below.
2d21ac55 7394
fe8ab488
A
7395 switch ( fMachineState )
7396 {
7397 case kIOPM_Finished:
39236c6e
A
7398 start_watchdog_timer();
7399
fe8ab488
A
7400 executePMRequest( request );
7401 break;
2d21ac55 7402
fe8ab488 7403 case kIOPM_OurChangeTellClientsPowerDown:
6d2010ae
A
7404 // Root domain might self cancel due to assertions.
7405 if (IS_ROOT_DOMAIN)
7406 {
7407 bool cancel = (bool) fDoNotPowerDown;
7408 getPMRootDomain()->askChangeDownDone(
7409 &fHeadNoteChangeFlags, &cancel);
7410 fDoNotPowerDown = cancel;
7411 }
7412
7413 // askChangeDown() done, was it vetoed?
fe8ab488
A
7414 if (!fDoNotPowerDown)
7415 {
7416 // no, we can continue
7417 OurChangeTellClientsPowerDown();
7418 }
7419 else
7420 {
7421 OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
7422 PM_ERROR("%s: idle cancel, state %u\n", fName, fMachineState);
7423 // yes, rescind the warning
7424 tellNoChangeDown(fHeadNotePowerState);
7425 // mark the change note un-actioned
7426 fHeadNoteChangeFlags |= kIOPMNotDone;
7427 // and we're done
7428 OurChangeFinish();
7429 }
7430 break;
6d2010ae 7431
fe8ab488 7432 case kIOPM_OurChangeTellUserPMPolicyPowerDown:
39236c6e 7433 // PMRD: tellChangeDown/kNotifyApps done, was it cancelled?
fe8ab488
A
7434 if (fDoNotPowerDown)
7435 {
7436 OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
7437 PM_ERROR("%s: idle cancel, state %u\n", fName, fMachineState);
7438 // yes, rescind the warning
7439 tellNoChangeDown(fHeadNotePowerState);
7440 // mark the change note un-actioned
7441 fHeadNoteChangeFlags |= kIOPMNotDone;
7442 // and we're done
7443 OurChangeFinish();
7444 }
7445 else
7446 OurChangeTellUserPMPolicyPowerDown();
7447 break;
7448
7449 case kIOPM_OurChangeTellPriorityClientsPowerDown:
7450 // PMRD: LastCallBeforeSleep notify done
39236c6e 7451 // Non-PMRD: tellChangeDown/kNotifyApps done
fe8ab488
A
7452 if (fDoNotPowerDown)
7453 {
7454 OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
7455 PM_ERROR("%s: idle revert, state %u\n", fName, fMachineState);
7456 // no, tell clients we're back in the old state
7457 tellChangeUp(fCurrentPowerState);
7458 // mark the change note un-actioned
7459 fHeadNoteChangeFlags |= kIOPMNotDone;
7460 // and we're done
7461 OurChangeFinish();
7462 }
7463 else
7464 {
7465 // yes, we can continue
7466 OurChangeTellPriorityClientsPowerDown();
7467 }
7468 break;
2d21ac55 7469
fe8ab488
A
7470 case kIOPM_OurChangeNotifyInterestedDriversWillChange:
7471 OurChangeNotifyInterestedDriversWillChange();
7472 break;
2d21ac55 7473
fe8ab488
A
7474 case kIOPM_OurChangeSetPowerState:
7475 OurChangeSetPowerState();
7476 break;
2d21ac55 7477
fe8ab488
A
7478 case kIOPM_OurChangeWaitForPowerSettle:
7479 OurChangeWaitForPowerSettle();
7480 break;
2d21ac55 7481
fe8ab488
A
7482 case kIOPM_OurChangeNotifyInterestedDriversDidChange:
7483 OurChangeNotifyInterestedDriversDidChange();
7484 break;
2d21ac55 7485
6d2010ae
A
7486 case kIOPM_OurChangeTellCapabilityDidChange:
7487 OurChangeTellCapabilityDidChange();
7488 break;
7489
fe8ab488
A
7490 case kIOPM_OurChangeFinish:
7491 OurChangeFinish();
7492 break;
2d21ac55 7493
fe8ab488
A
7494 case kIOPM_ParentChangeTellPriorityClientsPowerDown:
7495 ParentChangeTellPriorityClientsPowerDown();
7496 break;
2d21ac55 7497
fe8ab488
A
7498 case kIOPM_ParentChangeNotifyInterestedDriversWillChange:
7499 ParentChangeNotifyInterestedDriversWillChange();
7500 break;
2d21ac55 7501
fe8ab488
A
7502 case kIOPM_ParentChangeSetPowerState:
7503 ParentChangeSetPowerState();
7504 break;
2d21ac55 7505
fe8ab488
A
7506 case kIOPM_ParentChangeWaitForPowerSettle:
7507 ParentChangeWaitForPowerSettle();
7508 break;
2d21ac55 7509
fe8ab488
A
7510 case kIOPM_ParentChangeNotifyInterestedDriversDidChange:
7511 ParentChangeNotifyInterestedDriversDidChange();
7512 break;
2d21ac55 7513
6d2010ae
A
7514 case kIOPM_ParentChangeTellCapabilityDidChange:
7515 ParentChangeTellCapabilityDidChange();
7516 break;
2d21ac55 7517
fe8ab488
A
7518 case kIOPM_ParentChangeAcknowledgePowerChange:
7519 ParentChangeAcknowledgePowerChange();
7520 break;
2d21ac55 7521
fe8ab488 7522 case kIOPM_DriverThreadCallDone:
39236c6e
A
7523 switch (fDriverCallReason)
7524 {
7525 case kDriverCallInformPreChange:
7526 case kDriverCallInformPostChange:
7527 notifyInterestedDriversDone();
7528 break;
7529 case kDriverCallSetPowerState:
7530 notifyControllingDriverDone();
7531 break;
7532 case kRootDomainInformPreChange:
7533 notifyRootDomainDone();
7534 break;
7535 default:
7536 panic("%s: bad call reason %x",
7537 getName(), fDriverCallReason);
7538 }
fe8ab488 7539 break;
2d21ac55 7540
fe8ab488
A
7541 case kIOPM_NotifyChildrenOrdered:
7542 notifyChildrenOrdered();
7543 break;
6d2010ae 7544
fe8ab488
A
7545 case kIOPM_NotifyChildrenDelayed:
7546 notifyChildrenDelayed();
7547 break;
6d2010ae
A
7548
7549 case kIOPM_NotifyChildrenStart:
39236c6e
A
7550 // pop notifyAll() state saved by notifyInterestedDriversDone()
7551 MS_POP();
7552 notifyRootDomain();
6d2010ae
A
7553 break;
7554
7555 case kIOPM_SyncTellClientsPowerDown:
7556 // Root domain might self cancel due to assertions.
7557 if (IS_ROOT_DOMAIN)
7558 {
7559 bool cancel = (bool) fDoNotPowerDown;
7560 getPMRootDomain()->askChangeDownDone(
7561 &fHeadNoteChangeFlags, &cancel);
7562 fDoNotPowerDown = cancel;
39236c6e 7563 }
fe8ab488
A
7564 if (!fDoNotPowerDown)
7565 {
6d2010ae
A
7566 fMachineState = kIOPM_SyncTellPriorityClientsPowerDown;
7567 fOutOfBandParameter = kNotifyApps;
7568 tellChangeDown(fHeadNotePowerState);
fe8ab488
A
7569 }
7570 else
7571 {
39236c6e
A
7572 // Cancelled by IOPMrootDomain::askChangeDownDone() or
7573 // askChangeDown/kNotifyApps
fe8ab488
A
7574 OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
7575 PM_ERROR("%s: idle cancel, state %u\n", fName, fMachineState);
7576 tellNoChangeDown(fHeadNotePowerState);
7577 fHeadNoteChangeFlags |= kIOPMNotDone;
7578 OurChangeFinish();
7579 }
6d2010ae
A
7580 break;
7581
7582 case kIOPM_SyncTellPriorityClientsPowerDown:
39236c6e 7583 // PMRD: tellChangeDown/kNotifyApps done, was it cancelled?
fe8ab488
A
7584 if (!fDoNotPowerDown)
7585 {
6d2010ae
A
7586 fMachineState = kIOPM_SyncNotifyWillChange;
7587 fOutOfBandParameter = kNotifyPriority;
7588 tellChangeDown(fHeadNotePowerState);
7589 }
7590 else
7591 {
fe8ab488
A
7592 OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
7593 PM_ERROR("%s: idle revert, state %u\n", fName, fMachineState);
7594 tellChangeUp(fCurrentPowerState);
7595 fHeadNoteChangeFlags |= kIOPMNotDone;
7596 OurChangeFinish();
7597 }
7598 break;
2d21ac55 7599
6d2010ae
A
7600 case kIOPM_SyncNotifyWillChange:
7601 if (kIOPMSyncNoChildNotify & fHeadNoteChangeFlags)
7602 {
7603 fMachineState = kIOPM_SyncFinish;
7604 continue;
7605 }
7606 fMachineState = kIOPM_SyncNotifyDidChange;
7607 fDriverCallReason = kDriverCallInformPreChange;
7608 notifyChildren();
7609 break;
7610
b0d623f7 7611 case kIOPM_SyncNotifyDidChange:
6d2010ae
A
7612 fIsPreChange = false;
7613
7614 if (fHeadNoteChangeFlags & kIOPMParentInitiated)
bd504ef0 7615 {
6d2010ae 7616 fMachineState = kIOPM_SyncFinish;
bd504ef0 7617 }
6d2010ae 7618 else
bd504ef0
A
7619 {
7620 assert(IS_ROOT_DOMAIN);
6d2010ae 7621 fMachineState = kIOPM_SyncTellCapabilityDidChange;
bd504ef0 7622 }
6d2010ae 7623
b0d623f7
A
7624 fDriverCallReason = kDriverCallInformPostChange;
7625 notifyChildren();
7626 break;
7627
6d2010ae
A
7628 case kIOPM_SyncTellCapabilityDidChange:
7629 tellSystemCapabilityChange( kIOPM_SyncFinish );
7630 break;
7631
b0d623f7 7632 case kIOPM_SyncFinish:
6d2010ae
A
7633 if (fHeadNoteChangeFlags & kIOPMParentInitiated)
7634 ParentChangeAcknowledgePowerChange();
b0d623f7
A
7635 else
7636 OurChangeFinish();
6d2010ae
A
7637 break;
7638
7639 case kIOPM_TellCapabilityChangeDone:
7640 if (fIsPreChange)
7641 {
7642 if (fOutOfBandParameter == kNotifyCapabilityChangePriority)
7643 {
7644 MS_POP(); // tellSystemCapabilityChange()
7645 continue;
7646 }
7647 fOutOfBandParameter = kNotifyCapabilityChangePriority;
7648 }
7649 else
7650 {
7651 if (fOutOfBandParameter == kNotifyCapabilityChangeApps)
7652 {
7653 MS_POP(); // tellSystemCapabilityChange()
7654 continue;
7655 }
7656 fOutOfBandParameter = kNotifyCapabilityChangeApps;
7657 }
7658 tellClientsWithResponse( fOutOfBandMessage );
b0d623f7
A
7659 break;
7660
fe8ab488 7661 default:
3e170ce0 7662 panic("PMWorkQueueInvoke: unknown machine state %x",
b0d623f7 7663 fMachineState);
fe8ab488 7664 }
2d21ac55 7665
fe8ab488 7666 gIOPMRequest = 0;
2d21ac55 7667
fe8ab488
A
7668 if (fMachineState == kIOPM_Finished)
7669 {
39236c6e 7670 stop_watchdog_timer();
fe8ab488
A
7671 done = true;
7672 break;
7673 }
7674 }
1c79356b 7675
fe8ab488 7676 return done;
2d21ac55 7677}
1c79356b 7678
1c79356b 7679//*********************************************************************************
2d21ac55
A
7680// [private] executePMRequest
7681//*********************************************************************************
7682
7683void IOService::executePMRequest( IOPMRequest * request )
7684{
fe8ab488 7685 assert( kIOPM_Finished == fMachineState );
2d21ac55 7686
fe8ab488
A
7687 switch (request->getType())
7688 {
7689 case kIOPMRequestTypePMStop:
7690 handlePMstop( request );
7691 break;
2d21ac55 7692
fe8ab488
A
7693 case kIOPMRequestTypeAddPowerChild1:
7694 addPowerChild1( request );
7695 break;
2d21ac55 7696
fe8ab488
A
7697 case kIOPMRequestTypeAddPowerChild2:
7698 addPowerChild2( request );
7699 break;
2d21ac55 7700
fe8ab488
A
7701 case kIOPMRequestTypeAddPowerChild3:
7702 addPowerChild3( request );
7703 break;
2d21ac55 7704
fe8ab488
A
7705 case kIOPMRequestTypeRegisterPowerDriver:
7706 handleRegisterPowerDriver( request );
7707 break;
2d21ac55 7708
fe8ab488
A
7709 case kIOPMRequestTypeAdjustPowerState:
7710 fAdjustPowerScheduled = false;
7711 adjustPowerState();
7712 break;
2d21ac55 7713
fe8ab488
A
7714 case kIOPMRequestTypePowerDomainWillChange:
7715 handlePowerDomainWillChangeTo( request );
7716 break;
2d21ac55 7717
fe8ab488
A
7718 case kIOPMRequestTypePowerDomainDidChange:
7719 handlePowerDomainDidChangeTo( request );
7720 break;
2d21ac55 7721
fe8ab488 7722 case kIOPMRequestTypeRequestPowerState:
b0d623f7 7723 case kIOPMRequestTypeRequestPowerStateOverride:
fe8ab488
A
7724 handleRequestPowerState( request );
7725 break;
2d21ac55 7726
fe8ab488
A
7727 case kIOPMRequestTypePowerOverrideOnPriv:
7728 case kIOPMRequestTypePowerOverrideOffPriv:
7729 handlePowerOverrideChanged( request );
7730 break;
2d21ac55 7731
fe8ab488
A
7732 case kIOPMRequestTypeActivityTickle:
7733 handleActivityTickle( request );
7734 break;
2d21ac55 7735
b0d623f7 7736 case kIOPMRequestTypeSynchronizePowerTree:
fe8ab488
A
7737 handleSynchronizePowerTree( request );
7738 break;
b0d623f7
A
7739
7740 case kIOPMRequestTypeSetIdleTimerPeriod:
7741 {
b0d623f7 7742 fIdleTimerPeriod = (uintptr_t) request->fArg0;
fe8ab488 7743 fNextIdleTimerPeriod = fIdleTimerPeriod;
6d2010ae 7744 if ((false == fLockedFlags.PMStop) && (fIdleTimerPeriod > 0))
bd504ef0 7745 restartIdleTimer();
b0d623f7
A
7746 }
7747 break;
2d21ac55 7748
7ddcb079
A
7749 case kIOPMRequestTypeIgnoreIdleTimer:
7750 fIdleTimerIgnored = request->fArg0 ? 1 : 0;
7751 break;
7752
3e170ce0
A
7753 case kIOPMRequestTypeQuiescePowerTree:
7754 gIOPMWorkQueue->finishQuiesceRequest(request);
7755 break;
7756
fe8ab488
A
7757 default:
7758 panic("executePMRequest: unknown request type %x", request->getType());
7759 }
2d21ac55
A
7760}
7761
7762//*********************************************************************************
3e170ce0
A
7763// [private] actionPMReplyQueue
7764//
7765// IOPMRequestQueue::checkForWork() passing a reply-type request to the
7766// request target.
2d21ac55
A
7767//*********************************************************************************
7768
3e170ce0 7769bool IOService::actionPMReplyQueue( IOPMRequest * request, IOPMRequestQueue * queue )
2d21ac55 7770{
fe8ab488 7771 bool more = false;
2d21ac55 7772
fe8ab488
A
7773 assert( request && queue );
7774 assert( request->isReplyType() );
2d21ac55 7775
fe8ab488
A
7776 PM_LOG1("[A %02x] %p [%p %s] state %d\n",
7777 request->getType(), OBFUSCATE(request),
39236c6e 7778 OBFUSCATE(this), getName(), fMachineState);
2d21ac55 7779
fe8ab488
A
7780 switch ( request->getType() )
7781 {
7782 case kIOPMRequestTypeAllowPowerChange:
7783 case kIOPMRequestTypeCancelPowerChange:
7784 // Check if we are expecting this response.
7785 if (responseValid((uint32_t)(uintptr_t) request->fArg0,
6d2010ae 7786 (int)(uintptr_t) request->fArg1))
fe8ab488
A
7787 {
7788 if (kIOPMRequestTypeCancelPowerChange == request->getType())
b0d623f7 7789 {
6d2010ae
A
7790 // Clients are not allowed to cancel when kIOPMSkipAskPowerDown
7791 // flag is set. Only root domain will set this flag.
39236c6e
A
7792 // However, there is one exception to this rule. User-space PM
7793 // policy may choose to cancel sleep even after all clients have
7794 // been notified that we will lower power.
6d2010ae 7795
39236c6e
A
7796 if ((fMachineState == kIOPM_OurChangeTellUserPMPolicyPowerDown)
7797 || (fMachineState == kIOPM_OurChangeTellPriorityClientsPowerDown)
7798 || ((fHeadNoteChangeFlags & kIOPMSkipAskPowerDown) == 0))
6d2010ae
A
7799 {
7800 fDoNotPowerDown = true;
b0d623f7 7801
6d2010ae
A
7802 OSString * name = (OSString *) request->fArg2;
7803 getPMRootDomain()->pmStatsRecordApplicationResponse(
7804 gIOPMStatsApplicationResponseCancel,
7805 name ? name->getCStringNoCopy() : "", 0,
fe8ab488 7806 0, (int)(uintptr_t) request->fArg1, 0);
6d2010ae 7807 }
b0d623f7 7808 }
2d21ac55 7809
fe8ab488
A
7810 if (checkForDone())
7811 {
7812 stop_ack_timer();
6d2010ae 7813 cleanClientResponses(false);
fe8ab488
A
7814 more = true;
7815 }
7816 }
b0d623f7
A
7817 // OSString containing app name in Arg2 must be released.
7818 if (request->getType() == kIOPMRequestTypeCancelPowerChange)
7819 {
7820 OSObject * obj = (OSObject *) request->fArg2;
7821 if (obj) obj->release();
7822 }
fe8ab488
A
7823 break;
7824
7825 case kIOPMRequestTypeAckPowerChange:
7826 more = handleAcknowledgePowerChange( request );
7827 break;
7828
7829 case kIOPMRequestTypeAckSetPowerState:
7830 if (fDriverTimer == -1)
7831 {
7832 // driver acked while setPowerState() call is in-flight.
7833 // take this ack, return value from setPowerState() is irrelevant.
7834 OUR_PMLog(kPMLogDriverAcknowledgeSet,
7835 (uintptr_t) this, fDriverTimer);
7836 fDriverTimer = 0;
7837 }
7838 else if (fDriverTimer > 0)
7839 {
7840 // expected ack, stop the timer
7841 stop_ack_timer();
2d21ac55
A
7842
7843#if LOG_SETPOWER_TIMES
7844 uint64_t nsec = computeTimeDeltaNS(&fDriverCallStartTime);
fe8ab488
A
7845 if (nsec > LOG_SETPOWER_TIMES) {
7846 getPMRootDomain()->pmStatsRecordApplicationResponse(
7847 gIOPMStatsDriverPSChangeSlow,
7848 fName, kDriverCallSetPowerState, NS_TO_MS(nsec), 0, NULL, fHeadNotePowerState);
7849 }
2d21ac55 7850#endif
fe8ab488
A
7851 OUR_PMLog(kPMLogDriverAcknowledgeSet, (uintptr_t) this, fDriverTimer);
7852 fDriverTimer = 0;
7853 more = true;
7854 }
7855 else
7856 {
7857 // unexpected ack
7858 OUR_PMLog(kPMLogAcknowledgeErr4, (uintptr_t) this, 0);
7859 }
7860 break;
7861
7862 case kIOPMRequestTypeInterestChanged:
7863 handleInterestChanged( request );
7864 more = true;
7865 break;
7866
7867 case kIOPMRequestTypeIdleCancel:
7868 if ((fMachineState == kIOPM_OurChangeTellClientsPowerDown)
39236c6e 7869 || (fMachineState == kIOPM_OurChangeTellUserPMPolicyPowerDown)
fe8ab488 7870 || (fMachineState == kIOPM_OurChangeTellPriorityClientsPowerDown)
6d2010ae
A
7871 || (fMachineState == kIOPM_SyncTellClientsPowerDown)
7872 || (fMachineState == kIOPM_SyncTellPriorityClientsPowerDown))
fe8ab488
A
7873 {
7874 OUR_PMLog(kPMLogIdleCancel, (uintptr_t) this, fMachineState);
6d2010ae
A
7875 PM_LOG2("%s: cancel from machine state %d\n",
7876 getName(), fMachineState);
fe8ab488 7877 fDoNotPowerDown = true;
6d2010ae 7878 // Stop waiting for app replys.
fe8ab488
A
7879 if ((fMachineState == kIOPM_OurChangeTellPriorityClientsPowerDown) ||
7880 (fMachineState == kIOPM_OurChangeTellUserPMPolicyPowerDown) ||
3e170ce0
A
7881 (fMachineState == kIOPM_SyncTellPriorityClientsPowerDown) ||
7882 (fMachineState == kIOPM_SyncTellClientsPowerDown) )
fe8ab488
A
7883 cleanClientResponses(false);
7884 more = true;
7885 }
7886 break;
593a1d5f 7887
6d2010ae
A
7888 case kIOPMRequestTypeChildNotifyDelayCancel:
7889 if (fMachineState == kIOPM_NotifyChildrenDelayed)
7890 {
fe8ab488 7891 PM_LOG2("%s: delay notify cancelled\n", getName());
6d2010ae
A
7892 notifyChildrenDelayed();
7893 }
7894 break;
7895
fe8ab488 7896 default:
3e170ce0 7897 panic("PMReplyQueue: unknown reply type %x", request->getType());
fe8ab488 7898 }
2d21ac55 7899
3e170ce0 7900 more |= gIOPMCompletionQueue->queuePMRequest(request);
6d2010ae
A
7901 if (more)
7902 gIOPMWorkQueue->incrementProducerCount();
7903
fe8ab488 7904 return more;
2d21ac55
A
7905}
7906
b0d623f7 7907//*********************************************************************************
6d2010ae 7908// [private] assertPMDriverCall / deassertPMDriverCall
b0d623f7
A
7909//*********************************************************************************
7910
6d2010ae
A
7911bool IOService::assertPMDriverCall(
7912 IOPMDriverCallEntry * entry,
7913 IOOptionBits options,
7914 IOPMinformee * inform )
b0d623f7 7915{
6d2010ae
A
7916 IOService * target = 0;
7917 bool ok = false;
7918
b0d623f7
A
7919 if (!initialized)
7920 return false;
7921
b0d623f7 7922 PM_LOCK();
6d2010ae 7923
b0d623f7
A
7924 if (fLockedFlags.PMStop)
7925 {
6d2010ae
A
7926 goto fail;
7927 }
fe8ab488 7928
6d2010ae
A
7929 if (((options & kIOPMADC_NoInactiveCheck) == 0) && isInactive())
7930 {
7931 goto fail;
7932 }
7933
7934 if (inform)
7935 {
7936 if (!inform->active)
7937 {
7938 goto fail;
7939 }
7940 target = inform->whatObject;
7941 if (target->isInactive())
7942 {
7943 goto fail;
7944 }
b0d623f7
A
7945 }
7946
6d2010ae
A
7947 entry->thread = current_thread();
7948 entry->target = target;
7949 queue_enter(&fPMDriverCallQueue, entry, IOPMDriverCallEntry *, link);
7950 ok = true;
7951
7952fail:
b0d623f7
A
7953 PM_UNLOCK();
7954
6d2010ae 7955 return ok;
b0d623f7
A
7956}
7957
6d2010ae 7958void IOService::deassertPMDriverCall( IOPMDriverCallEntry * entry )
b0d623f7 7959{
6d2010ae
A
7960 bool wakeup = false;
7961
b0d623f7 7962 PM_LOCK();
6d2010ae
A
7963
7964 assert( !queue_empty(&fPMDriverCallQueue) );
7965 queue_remove(&fPMDriverCallQueue, entry, IOPMDriverCallEntry *, link);
7966 if (fLockedFlags.PMDriverCallWait)
b0d623f7 7967 {
6d2010ae 7968 wakeup = true;
b0d623f7 7969 }
6d2010ae 7970
b0d623f7 7971 PM_UNLOCK();
6d2010ae
A
7972
7973 if (wakeup)
7974 PM_LOCK_WAKEUP(&fPMDriverCallQueue);
7975}
7976
7977void IOService::waitForPMDriverCall( IOService * target )
7978{
7979 const IOPMDriverCallEntry * entry;
7980 thread_t thread = current_thread();
7981 AbsoluteTime deadline;
7982 int waitResult;
7983 bool log = true;
7984 bool wait;
7985
7986 do {
7987 wait = false;
7988 queue_iterate(&fPMDriverCallQueue, entry, const IOPMDriverCallEntry *, link)
7989 {
7990 // Target of interested driver call
7991 if (target && (target != entry->target))
7992 continue;
7993
7994 if (entry->thread == thread)
7995 {
7996 if (log)
7997 {
7998 PM_LOG("%s: %s(%s) on PM thread\n",
7999 fName, __FUNCTION__, target ? target->getName() : "");
8000 OSReportWithBacktrace("%s: %s(%s) on PM thread\n",
8001 fName, __FUNCTION__, target ? target->getName() : "");
8002 log = false;
8003 }
8004 continue;
8005 }
fe8ab488 8006
6d2010ae
A
8007 wait = true;
8008 break;
8009 }
8010
8011 if (wait)
8012 {
8013 fLockedFlags.PMDriverCallWait = true;
8014 clock_interval_to_deadline(15, kSecondScale, &deadline);
8015 waitResult = PM_LOCK_SLEEP(&fPMDriverCallQueue, deadline);
8016 fLockedFlags.PMDriverCallWait = false;
8017 if (THREAD_TIMED_OUT == waitResult)
8018 {
8019 PM_ERROR("%s: waitForPMDriverCall timeout\n", fName);
8020 wait = false;
8021 }
8022 }
8023 } while (wait);
8024}
8025
8026//*********************************************************************************
8027// [private] Debug helpers
8028//*********************************************************************************
8029
8030const char * IOService::getIOMessageString( uint32_t msg )
8031{
39236c6e 8032#define MSG_ENTRY(x) {(int) x, #x}
6d2010ae 8033
fe8ab488 8034 static const IONamedValue msgNames[] = {
6d2010ae
A
8035 MSG_ENTRY( kIOMessageCanDevicePowerOff ),
8036 MSG_ENTRY( kIOMessageDeviceWillPowerOff ),
8037 MSG_ENTRY( kIOMessageDeviceWillNotPowerOff ),
8038 MSG_ENTRY( kIOMessageDeviceHasPoweredOn ),
8039 MSG_ENTRY( kIOMessageCanSystemPowerOff ),
8040 MSG_ENTRY( kIOMessageSystemWillPowerOff ),
8041 MSG_ENTRY( kIOMessageSystemWillNotPowerOff ),
8042 MSG_ENTRY( kIOMessageCanSystemSleep ),
8043 MSG_ENTRY( kIOMessageSystemWillSleep ),
8044 MSG_ENTRY( kIOMessageSystemWillNotSleep ),
8045 MSG_ENTRY( kIOMessageSystemHasPoweredOn ),
8046 MSG_ENTRY( kIOMessageSystemWillRestart ),
8047 MSG_ENTRY( kIOMessageSystemWillPowerOn ),
39236c6e
A
8048 MSG_ENTRY( kIOMessageSystemCapabilityChange ),
8049 MSG_ENTRY( kIOPMMessageLastCallBeforeSleep )
6d2010ae
A
8050 };
8051
8052 return IOFindNameForValue(msg, msgNames);
b0d623f7
A
8053}
8054
39236c6e 8055
7e4a7d39
A
8056// MARK: -
8057// MARK: IOPMRequest
8058
2d21ac55
A
8059//*********************************************************************************
8060// IOPMRequest Class
8061//
8062// Requests from PM clients, and also used for inter-object messaging within PM.
8063//*********************************************************************************
8064
8065OSDefineMetaClassAndStructors( IOPMRequest, IOCommand );
8066
8067IOPMRequest * IOPMRequest::create( void )
8068{
fe8ab488
A
8069 IOPMRequest * me = OSTypeAlloc(IOPMRequest);
8070 if (me && !me->init(0, kIOPMRequestTypeInvalid))
8071 {
8072 me->release();
8073 me = 0;
8074 }
8075 return me;
2d21ac55
A
8076}
8077
8078bool IOPMRequest::init( IOService * target, IOOptionBits type )
8079{
fe8ab488
A
8080 if (!IOCommand::init())
8081 return false;
2d21ac55 8082
3e170ce0
A
8083 fRequestType = type;
8084 fTarget = target;
2d21ac55 8085
fe8ab488
A
8086 if (fTarget)
8087 fTarget->retain();
2d21ac55 8088
3e170ce0
A
8089 // Root node and root domain requests does not prevent the power tree from
8090 // becoming quiescent.
8091
8092 fIsQuiesceBlocker = ((fTarget != gIOPMRootNode) &&
8093 (fTarget != IOService::getPMRootDomain()));
8094
fe8ab488 8095 return true;
2d21ac55
A
8096}
8097
8098void IOPMRequest::reset( void )
8099{
fe8ab488
A
8100 assert( fWorkWaitCount == 0 );
8101 assert( fFreeWaitCount == 0 );
b0d623f7 8102
fe8ab488 8103 detachNextRequest();
b0d623f7 8104 detachRootRequest();
2d21ac55 8105
3e170ce0 8106 if (fCompletionAction && (fRequestType == kIOPMRequestTypeQuiescePowerTree))
fe8ab488 8107 {
3e170ce0
A
8108 // Call the completion on PM work loop context
8109 fCompletionAction(fCompletionTarget, fCompletionParam);
8110 fCompletionAction = 0;
b0d623f7 8111 }
3e170ce0
A
8112
8113 fRequestType = kIOPMRequestTypeInvalid;
2d21ac55 8114
fe8ab488
A
8115 if (fTarget)
8116 {
8117 fTarget->release();
8118 fTarget = 0;
8119 }
b0d623f7
A
8120}
8121
6d2010ae 8122bool IOPMRequest::attachNextRequest( IOPMRequest * next )
b0d623f7 8123{
6d2010ae
A
8124 bool ok = false;
8125
b0d623f7
A
8126 if (!fRequestNext)
8127 {
8128 // Postpone the execution of the next request after
8129 // this request.
8130 fRequestNext = next;
8131 fRequestNext->fWorkWaitCount++;
8132#if LOG_REQUEST_ATTACH
bd504ef0 8133 PM_LOG("Attached next: %p [0x%x] -> %p [0x%x, %u] %s\n",
3e170ce0
A
8134 OBFUSCATE(this), fRequestType, OBFUSCATE(fRequestNext),
8135 fRequestNext->fRequestType,
b0d623f7
A
8136 (uint32_t) fRequestNext->fWorkWaitCount,
8137 fTarget->getName());
8138#endif
6d2010ae 8139 ok = true;
b0d623f7 8140 }
6d2010ae 8141 return ok;
b0d623f7
A
8142}
8143
6d2010ae 8144bool IOPMRequest::detachNextRequest( void )
b0d623f7 8145{
6d2010ae
A
8146 bool ok = false;
8147
b0d623f7
A
8148 if (fRequestNext)
8149 {
8150 assert(fRequestNext->fWorkWaitCount);
8151 if (fRequestNext->fWorkWaitCount)
8152 fRequestNext->fWorkWaitCount--;
8153#if LOG_REQUEST_ATTACH
bd504ef0 8154 PM_LOG("Detached next: %p [0x%x] -> %p [0x%x, %u] %s\n",
3e170ce0
A
8155 OBFUSCATE(this), fRequestType, OBFUSCATE(fRequestNext),
8156 fRequestNext->fRequestType,
b0d623f7
A
8157 (uint32_t) fRequestNext->fWorkWaitCount,
8158 fTarget->getName());
8159#endif
8160 fRequestNext = 0;
6d2010ae 8161 ok = true;
b0d623f7 8162 }
6d2010ae 8163 return ok;
b0d623f7
A
8164}
8165
6d2010ae 8166bool IOPMRequest::attachRootRequest( IOPMRequest * root )
b0d623f7 8167{
6d2010ae
A
8168 bool ok = false;
8169
b0d623f7
A
8170 if (!fRequestRoot)
8171 {
8172 // Delay the completion of the root request after
8173 // this request.
8174 fRequestRoot = root;
8175 fRequestRoot->fFreeWaitCount++;
8176#if LOG_REQUEST_ATTACH
bd504ef0 8177 PM_LOG("Attached root: %p [0x%x] -> %p [0x%x, %u] %s\n",
39236c6e 8178 OBFUSCATE(this), (uint32_t) fType, OBFUSCATE(fRequestRoot),
b0d623f7
A
8179 (uint32_t) fRequestRoot->fType,
8180 (uint32_t) fRequestRoot->fFreeWaitCount,
8181 fTarget->getName());
8182#endif
6d2010ae 8183 ok = true;
b0d623f7 8184 }
6d2010ae 8185 return ok;
b0d623f7
A
8186}
8187
6d2010ae 8188bool IOPMRequest::detachRootRequest( void )
b0d623f7 8189{
6d2010ae
A
8190 bool ok = false;
8191
b0d623f7
A
8192 if (fRequestRoot)
8193 {
8194 assert(fRequestRoot->fFreeWaitCount);
8195 if (fRequestRoot->fFreeWaitCount)
8196 fRequestRoot->fFreeWaitCount--;
8197#if LOG_REQUEST_ATTACH
bd504ef0 8198 PM_LOG("Detached root: %p [0x%x] -> %p [0x%x, %u] %s\n",
39236c6e 8199 OBFUSCATE(this), (uint32_t) fType, OBFUSCATE(fRequestRoot),
b0d623f7
A
8200 (uint32_t) fRequestRoot->fType,
8201 (uint32_t) fRequestRoot->fFreeWaitCount,
8202 fTarget->getName());
8203#endif
8204 fRequestRoot = 0;
6d2010ae 8205 ok = true;
b0d623f7 8206 }
6d2010ae 8207 return ok;
2d21ac55
A
8208}
8209
7e4a7d39
A
8210// MARK: -
8211// MARK: IOPMRequestQueue
8212
2d21ac55
A
8213//*********************************************************************************
8214// IOPMRequestQueue Class
1c79356b 8215//
6d2010ae 8216// Global queues. Queues are created once and never released.
1c79356b 8217//*********************************************************************************
2d21ac55
A
8218
8219OSDefineMetaClassAndStructors( IOPMRequestQueue, IOEventSource );
8220
8221IOPMRequestQueue * IOPMRequestQueue::create( IOService * inOwner, Action inAction )
1c79356b 8222{
fe8ab488
A
8223 IOPMRequestQueue * me = OSTypeAlloc(IOPMRequestQueue);
8224 if (me && !me->init(inOwner, inAction))
8225 {
8226 me->release();
8227 me = 0;
8228 }
8229 return me;
2d21ac55 8230}
1c79356b 8231
2d21ac55
A
8232bool IOPMRequestQueue::init( IOService * inOwner, Action inAction )
8233{
fe8ab488 8234 if (!inAction || !IOEventSource::init(inOwner, (IOEventSourceAction)inAction))
1c79356b
A
8235 return false;
8236
fe8ab488
A
8237 queue_init(&fQueue);
8238 fLock = IOLockAlloc();
8239 return (fLock != 0);
2d21ac55 8240}
1c79356b 8241
2d21ac55
A
8242void IOPMRequestQueue::free( void )
8243{
fe8ab488
A
8244 if (fLock)
8245 {
8246 IOLockFree(fLock);
8247 fLock = 0;
8248 }
8249 return IOEventSource::free();
2d21ac55 8250}
1c79356b 8251
2d21ac55
A
8252void IOPMRequestQueue::queuePMRequest( IOPMRequest * request )
8253{
fe8ab488
A
8254 assert(request);
8255 IOLockLock(fLock);
3e170ce0 8256 queue_enter(&fQueue, request, typeof(request), fCommandChain);
fe8ab488
A
8257 IOLockUnlock(fLock);
8258 if (workLoop) signalWorkAvailable();
2d21ac55 8259}
1c79356b 8260
2d21ac55
A
8261void
8262IOPMRequestQueue::queuePMRequestChain( IOPMRequest ** requests, IOItemCount count )
8263{
fe8ab488 8264 IOPMRequest * next;
2d21ac55 8265
fe8ab488
A
8266 assert(requests && count);
8267 IOLockLock(fLock);
8268 while (count--)
8269 {
8270 next = *requests;
8271 requests++;
3e170ce0 8272 queue_enter(&fQueue, next, typeof(next), fCommandChain);
fe8ab488
A
8273 }
8274 IOLockUnlock(fLock);
8275 if (workLoop) signalWorkAvailable();
2d21ac55
A
8276}
8277
8278bool IOPMRequestQueue::checkForWork( void )
8279{
fe8ab488
A
8280 Action dqAction = (Action) action;
8281 IOPMRequest * request;
8282 IOService * target;
3e170ce0 8283 int dequeueCount = 0;
fe8ab488 8284 bool more = false;
2d21ac55 8285
fe8ab488 8286 IOLockLock( fLock );
2d21ac55 8287
fe8ab488
A
8288 while (!queue_empty(&fQueue))
8289 {
3e170ce0
A
8290 if (dequeueCount++ >= kMaxDequeueCount)
8291 {
8292 // Allow other queues a chance to work
8293 more = true;
8294 break;
8295 }
8296
8297 queue_remove_first(&fQueue, request, typeof(request), fCommandChain);
8298 IOLockUnlock(fLock);
fe8ab488
A
8299 target = request->getTarget();
8300 assert(target);
8301 more |= (*dqAction)( target, request, this );
8302 IOLockLock( fLock );
8303 }
2d21ac55 8304
fe8ab488
A
8305 IOLockUnlock( fLock );
8306 return more;
2d21ac55
A
8307}
8308
7e4a7d39
A
8309// MARK: -
8310// MARK: IOPMWorkQueue
8311
2d21ac55
A
8312//*********************************************************************************
8313// IOPMWorkQueue Class
8314//
3e170ce0
A
8315// Queue of IOServicePM objects, each with a queue of IOPMRequest sharing the
8316// same target.
2d21ac55 8317//*********************************************************************************
1c79356b 8318
2d21ac55 8319OSDefineMetaClassAndStructors( IOPMWorkQueue, IOEventSource );
1c79356b 8320
2d21ac55 8321IOPMWorkQueue *
3e170ce0 8322IOPMWorkQueue::create( IOService * inOwner, Action invoke, Action retire )
2d21ac55 8323{
fe8ab488 8324 IOPMWorkQueue * me = OSTypeAlloc(IOPMWorkQueue);
3e170ce0 8325 if (me && !me->init(inOwner, invoke, retire))
fe8ab488
A
8326 {
8327 me->release();
8328 me = 0;
8329 }
8330 return me;
2d21ac55
A
8331}
8332
3e170ce0 8333bool IOPMWorkQueue::init( IOService * inOwner, Action invoke, Action retire )
2d21ac55 8334{
3e170ce0 8335 if (!invoke || !retire ||
fe8ab488
A
8336 !IOEventSource::init(inOwner, (IOEventSourceAction)0))
8337 return false;
2d21ac55 8338
fe8ab488 8339 queue_init(&fWorkQueue);
2d21ac55 8340
3e170ce0 8341 fInvokeAction = invoke;
fe8ab488 8342 fRetireAction = retire;
6d2010ae 8343 fConsumerCount = fProducerCount = 0;
2d21ac55 8344
fe8ab488 8345 return true;
2d21ac55
A
8346}
8347
6d2010ae 8348bool IOPMWorkQueue::queuePMRequest( IOPMRequest * request, IOServicePM * pwrMgt )
2d21ac55 8349{
3e170ce0
A
8350 queue_head_t * requestQueue;
8351 bool more = false;
8352 bool empty;
6d2010ae 8353
fe8ab488 8354 assert( request );
6d2010ae 8355 assert( pwrMgt );
fe8ab488 8356 assert( onThread() );
6d2010ae
A
8357 assert( queue_next(&request->fCommandChain) ==
8358 queue_prev(&request->fCommandChain) );
2d21ac55 8359
3e170ce0
A
8360 gIOPMBusyRequestCount++;
8361
8362 if (request->isQuiesceType())
8363 {
8364 if ((request->getTarget() == gIOPMRootNode) && !fQuiesceStartTime)
8365 {
8366 // Attach new quiesce request to all quiesce blockers in the queue
8367 fQuiesceStartTime = mach_absolute_time();
8368 attachQuiesceRequest(request);
8369 fQuiesceRequest = request;
8370 }
8371 }
8372 else if (fQuiesceRequest && request->isQuiesceBlocker())
8373 {
8374 // Attach the new quiesce blocker to the blocked quiesce request
8375 request->attachNextRequest(fQuiesceRequest);
8376 }
6d2010ae
A
8377
8378 // Add new request to the tail of the per-service request queue.
8379 // Then immediately check the request queue to minimize latency
8380 // if the queue was empty.
8381
3e170ce0
A
8382 requestQueue = &pwrMgt->RequestHead;
8383 empty = queue_empty(requestQueue);
8384 queue_enter(requestQueue, request, typeof(request), fCommandChain);
6d2010ae
A
8385 if (empty)
8386 {
3e170ce0 8387 more = checkRequestQueue(requestQueue, &empty);
6d2010ae
A
8388 if (!empty)
8389 {
3e170ce0
A
8390 // Request just added is blocked, add its target IOServicePM
8391 // to the work queue.
6d2010ae
A
8392 assert( queue_next(&pwrMgt->WorkChain) ==
8393 queue_prev(&pwrMgt->WorkChain) );
8394
3e170ce0 8395 queue_enter(&fWorkQueue, pwrMgt, typeof(pwrMgt), WorkChain);
6d2010ae
A
8396 fQueueLength++;
8397 PM_LOG3("IOPMWorkQueue: [%u] added %s@%p to queue\n",
39236c6e 8398 fQueueLength, pwrMgt->Name, OBFUSCATE(pwrMgt));
6d2010ae
A
8399 }
8400 }
8401
8402 return more;
2d21ac55
A
8403}
8404
3e170ce0 8405bool IOPMWorkQueue::checkRequestQueue( queue_head_t * requestQueue, bool * empty )
2d21ac55 8406{
fe8ab488
A
8407 IOPMRequest * request;
8408 IOService * target;
6d2010ae 8409 bool more = false;
fe8ab488 8410 bool done = false;
2d21ac55 8411
3e170ce0 8412 assert(!queue_empty(requestQueue));
6d2010ae 8413 do {
3e170ce0 8414 request = (typeof(request)) queue_first(requestQueue);
fe8ab488 8415 if (request->isWorkBlocked())
3e170ce0 8416 break; // request dispatch blocked on attached request
2d21ac55 8417
fe8ab488 8418 target = request->getTarget();
3e170ce0
A
8419 if (fInvokeAction)
8420 {
8421 done = (*fInvokeAction)( target, request, this );
8422 }
8423 else
8424 {
8425 PM_LOG("PM request 0x%x dropped\n", request->getType());
8426 done = true;
8427 }
fe8ab488 8428 if (!done)
3e170ce0 8429 break; // PM state machine blocked
6d2010ae 8430
3e170ce0
A
8431 assert(gIOPMBusyRequestCount > 0);
8432 if (gIOPMBusyRequestCount)
8433 gIOPMBusyRequestCount--;
6d2010ae 8434
3e170ce0
A
8435 if (request == fQuiesceRequest)
8436 {
8437 fQuiesceRequest = 0;
8438 }
8439
8440 queue_remove_first(requestQueue, request, typeof(request), fCommandChain);
6d2010ae 8441 more |= (*fRetireAction)( target, request, this );
3e170ce0 8442 done = queue_empty(requestQueue);
6d2010ae
A
8443 } while (!done);
8444
8445 *empty = done;
8446
8447 if (more)
8448 {
3e170ce0
A
8449 // Retired a request that may unblock a previously visited request
8450 // that is still waiting on the work queue. Must trigger another
8451 // queue check.
6d2010ae
A
8452 fProducerCount++;
8453 }
8454
8455 return more;
8456}
8457
8458bool IOPMWorkQueue::checkForWork( void )
8459{
fe8ab488
A
8460 IOServicePM * entry;
8461 IOServicePM * next;
8462 bool more = false;
6d2010ae
A
8463 bool empty;
8464
8465#if WORK_QUEUE_STATS
8466 fStatCheckForWork++;
8467#endif
8468
3e170ce0
A
8469 // Iterate over all IOServicePM entries in the work queue,
8470 // and check each entry's request queue.
6d2010ae
A
8471
8472 while (fConsumerCount != fProducerCount)
8473 {
8474 PM_LOG3("IOPMWorkQueue: checkForWork %u %u\n",
8475 fProducerCount, fConsumerCount);
8476
8477 fConsumerCount = fProducerCount;
8478
fe8ab488 8479#if WORK_QUEUE_STATS
6d2010ae
A
8480 if (queue_empty(&fWorkQueue))
8481 {
8482 fStatQueueEmpty++;
8483 break;
8484 }
8485 fStatScanEntries++;
3e170ce0 8486 uint32_t cachedWorkCount = gIOPMWorkInvokeCount;
6d2010ae
A
8487#endif
8488
3e170ce0 8489 __IGNORE_WCASTALIGN(entry = (typeof(entry)) queue_first(&fWorkQueue));
6d2010ae
A
8490 while (!queue_end(&fWorkQueue, (queue_entry_t) entry))
8491 {
8492 more |= checkRequestQueue(&entry->RequestHead, &empty);
8493
8494 // Get next entry, points to head if current entry is last.
3e170ce0 8495 __IGNORE_WCASTALIGN(next = (typeof(next)) queue_next(&entry->WorkChain));
6d2010ae 8496
3e170ce0 8497 // if request queue is empty, remove IOServicePM from work queue.
6d2010ae
A
8498 if (empty)
8499 {
8500 assert(fQueueLength);
8501 if (fQueueLength) fQueueLength--;
8502 PM_LOG3("IOPMWorkQueue: [%u] removed %s@%p from queue\n",
39236c6e 8503 fQueueLength, entry->Name, OBFUSCATE(entry));
3e170ce0 8504 queue_remove(&fWorkQueue, entry, typeof(entry), WorkChain);
6d2010ae
A
8505 }
8506 entry = next;
8507 }
8508
8509#if WORK_QUEUE_STATS
3e170ce0 8510 if (cachedWorkCount == gIOPMWorkInvokeCount)
6d2010ae
A
8511 fStatNoWorkDone++;
8512#endif
8513 }
8514
8515 return more;
8516}
8517
8518void IOPMWorkQueue::signalWorkAvailable( void )
8519{
8520 fProducerCount++;
fe8ab488 8521 IOEventSource::signalWorkAvailable();
6d2010ae
A
8522}
8523
8524void IOPMWorkQueue::incrementProducerCount( void )
8525{
8526 fProducerCount++;
2d21ac55
A
8527}
8528
3e170ce0
A
8529void IOPMWorkQueue::attachQuiesceRequest( IOPMRequest * quiesceRequest )
8530{
8531 IOServicePM * entry;
8532 IOPMRequest * request;
8533
8534 if (queue_empty(&fWorkQueue))
8535 {
8536 return;
8537 }
8538
8539 queue_iterate(&fWorkQueue, entry, typeof(entry), WorkChain)
8540 {
8541 queue_iterate(&entry->RequestHead, request, typeof(request), fCommandChain)
8542 {
8543 // Attach the quiesce request to any request in the queue that
8544 // is not linked to a next request. These requests will block
8545 // the quiesce request.
8546
8547 if (request->isQuiesceBlocker())
8548 {
8549 request->attachNextRequest(quiesceRequest);
8550 }
8551 }
8552 }
8553}
8554
8555void IOPMWorkQueue::finishQuiesceRequest( IOPMRequest * quiesceRequest )
8556{
8557 if (fQuiesceRequest && (quiesceRequest == fQuiesceRequest) &&
8558 (fQuiesceStartTime != 0))
8559 {
8560 fInvokeAction = 0;
8561 fQuiesceFinishTime = mach_absolute_time();
8562 }
8563}
8564
7e4a7d39
A
8565// MARK: -
8566// MARK: IOPMCompletionQueue
8567
b0d623f7
A
8568//*********************************************************************************
8569// IOPMCompletionQueue Class
8570//*********************************************************************************
8571
8572OSDefineMetaClassAndStructors( IOPMCompletionQueue, IOEventSource );
8573
6d2010ae
A
8574IOPMCompletionQueue *
8575IOPMCompletionQueue::create( IOService * inOwner, Action inAction )
b0d623f7 8576{
fe8ab488
A
8577 IOPMCompletionQueue * me = OSTypeAlloc(IOPMCompletionQueue);
8578 if (me && !me->init(inOwner, inAction))
8579 {
8580 me->release();
8581 me = 0;
8582 }
8583 return me;
b0d623f7
A
8584}
8585
8586bool IOPMCompletionQueue::init( IOService * inOwner, Action inAction )
8587{
fe8ab488 8588 if (!inAction || !IOEventSource::init(inOwner, (IOEventSourceAction)inAction))
b0d623f7
A
8589 return false;
8590
fe8ab488
A
8591 queue_init(&fQueue);
8592 return true;
b0d623f7
A
8593}
8594
6d2010ae 8595bool IOPMCompletionQueue::queuePMRequest( IOPMRequest * request )
b0d623f7 8596{
6d2010ae
A
8597 bool more;
8598
fe8ab488 8599 assert(request);
6d2010ae
A
8600 // unblock dependent request
8601 more = request->detachNextRequest();
3e170ce0 8602 queue_enter(&fQueue, request, typeof(request), fCommandChain);
6d2010ae 8603 return more;
b0d623f7
A
8604}
8605
8606bool IOPMCompletionQueue::checkForWork( void )
8607{
fe8ab488
A
8608 Action dqAction = (Action) action;
8609 IOPMRequest * request;
8610 IOPMRequest * next;
8611 IOService * target;
8612 bool more = false;
b0d623f7 8613
3e170ce0 8614 request = (typeof(request)) queue_first(&fQueue);
6d2010ae
A
8615 while (!queue_end(&fQueue, (queue_entry_t) request))
8616 {
3e170ce0 8617 next = (typeof(next)) queue_next(&request->fCommandChain);
fe8ab488 8618 if (!request->isFreeBlocked())
6d2010ae 8619 {
3e170ce0 8620 queue_remove(&fQueue, request, typeof(request), fCommandChain);
6d2010ae
A
8621 target = request->getTarget();
8622 assert(target);
8623 more |= (*dqAction)( target, request, this );
8624 }
8625 request = next;
8626 }
b0d623f7 8627
6d2010ae 8628 return more;
b0d623f7
A
8629}
8630
7e4a7d39
A
8631// MARK: -
8632// MARK: IOServicePM
8633
2d21ac55
A
8634OSDefineMetaClassAndStructors(IOServicePM, OSObject)
8635
8636//*********************************************************************************
8637// serialize
8638//
8639// Serialize IOServicePM for debugging.
8640//*********************************************************************************
8641
8642static void
b0d623f7 8643setPMProperty( OSDictionary * dict, const char * key, uint64_t value )
2d21ac55
A
8644{
8645 OSNumber * num = OSNumber::withNumber(value, sizeof(value) * 8);
8646 if (num)
8647 {
8648 dict->setObject(key, num);
8649 num->release();
8650 }
1c79356b
A
8651}
8652
39236c6e 8653IOReturn IOServicePM::gatedSerialize( OSSerialize * s ) const
2d21ac55 8654{
fe8ab488
A
8655 OSDictionary * dict;
8656 bool ok = false;
39236c6e 8657 int powerClamp = -1;
fe8ab488 8658 int dictSize = 6;
b0d623f7 8659
fe8ab488
A
8660 if (IdleTimerPeriod)
8661 dictSize += 4;
b0d623f7 8662
39236c6e
A
8663 if (PMActions.parameter & kPMActionsFlagLimitPower)
8664 {
8665 dictSize += 1;
8666 powerClamp = 0;
8667 if (PMActions.parameter &
8668 (kPMActionsFlagIsDisplayWrangler | kPMActionsFlagIsGraphicsDevice))
8669 powerClamp++;
8670 }
8671
6d2010ae
A
8672#if WORK_QUEUE_STATS
8673 if (gIOPMRootNode == ControllingDriver)
8674 dictSize += 4;
8675#endif
8676
b0d623f7
A
8677 if (PowerClients)
8678 dict = OSDictionary::withDictionary(
8679 PowerClients, PowerClients->getCount() + dictSize);
8680 else
8681 dict = OSDictionary::withCapacity(dictSize);
2d21ac55 8682
fe8ab488
A
8683 if (dict)
8684 {
b0d623f7 8685 setPMProperty(dict, "CurrentPowerState", CurrentPowerState);
fe8ab488 8686 setPMProperty(dict, "CapabilityFlags", CurrentCapabilityFlags);
6d2010ae
A
8687 if (NumberOfPowerStates)
8688 setPMProperty(dict, "MaxPowerState", NumberOfPowerStates-1);
2d21ac55 8689 if (DesiredPowerState != CurrentPowerState)
b0d623f7 8690 setPMProperty(dict, "DesiredPowerState", DesiredPowerState);
2d21ac55 8691 if (kIOPM_Finished != MachineState)
b0d623f7 8692 setPMProperty(dict, "MachineState", MachineState);
6d2010ae 8693 if (DeviceOverrideEnabled)
b0d623f7 8694 dict->setObject("PowerOverrideOn", kOSBooleanTrue);
39236c6e
A
8695 if (powerClamp >= 0)
8696 setPMProperty(dict, "PowerClamp", powerClamp);
b0d623f7 8697
fe8ab488
A
8698 if (IdleTimerPeriod)
8699 {
b0d623f7
A
8700 AbsoluteTime now;
8701 AbsoluteTime delta;
8702 uint64_t nsecs;
8703
8704 clock_get_uptime(&now);
8705
fe8ab488
A
8706 // The idle timer period in milliseconds
8707 setPMProperty(dict, "IdleTimerPeriod", NextIdleTimerPeriod * 1000ULL);
b0d623f7 8708
fe8ab488 8709 // Number of tickles since the last idle timer expiration
b0d623f7
A
8710 setPMProperty(dict, "ActivityTickles", ActivityTickleCount);
8711
8712 if (AbsoluteTime_to_scalar(&DeviceActiveTimestamp))
8713 {
fe8ab488 8714 // Milliseconds since the last activity tickle
b0d623f7
A
8715 delta = now;
8716 SUB_ABSOLUTETIME(&delta, &DeviceActiveTimestamp);
8717 absolutetime_to_nanoseconds(delta, &nsecs);
6d2010ae 8718 setPMProperty(dict, "TimeSinceLastTickle", NS_TO_MS(nsecs));
b0d623f7
A
8719 }
8720
fe8ab488 8721 if (!IdleTimerStopped && AbsoluteTime_to_scalar(&IdleTimerStartTime))
b0d623f7 8722 {
fe8ab488 8723 // Idle timer elapsed time in milliseconds
b0d623f7
A
8724 delta = now;
8725 SUB_ABSOLUTETIME(&delta, &IdleTimerStartTime);
8726 absolutetime_to_nanoseconds(delta, &nsecs);
fe8ab488 8727 setPMProperty(dict, "IdleTimerElapsedTime", NS_TO_MS(nsecs));
b0d623f7 8728 }
fe8ab488 8729 }
2d21ac55 8730
6d2010ae
A
8731#if WORK_QUEUE_STATS
8732 if (gIOPMRootNode == Owner)
8733 {
8734 setPMProperty(dict, "WQ-CheckForWork",
8735 gIOPMWorkQueue->fStatCheckForWork);
8736 setPMProperty(dict, "WQ-ScanEntries",
8737 gIOPMWorkQueue->fStatScanEntries);
8738 setPMProperty(dict, "WQ-QueueEmpty",
8739 gIOPMWorkQueue->fStatQueueEmpty);
8740 setPMProperty(dict, "WQ-NoWorkDone",
8741 gIOPMWorkQueue->fStatNoWorkDone);
8742 }
8743#endif
8744
db609669
A
8745 if (HasAdvisoryDesire && !gIOPMAdvisoryTickleEnabled)
8746 {
8747 // Don't report advisory tickle when it has no influence
8748 dict->removeObject(gIOPMPowerClientAdvisoryTickle);
8749 }
8750
fe8ab488
A
8751 ok = dict->serialize(s);
8752 dict->release();
8753 }
2d21ac55 8754
fe8ab488 8755 return (ok ? kIOReturnSuccess : kIOReturnNoMemory);
b0d623f7
A
8756}
8757
8758bool IOServicePM::serialize( OSSerialize * s ) const
8759{
8760 IOReturn ret = kIOReturnNotReady;
8761
39236c6e
A
8762 if (gIOPMWatchDogThread == current_thread())
8763 {
8764 // Calling without lock as this data is collected for debug purpose, before reboot.
8765 // The workloop is probably already hung in state machine.
8766 ret = gatedSerialize(s);
8767 }
8768 else if (gIOPMWorkLoop)
fe8ab488
A
8769 {
8770 ret = gIOPMWorkLoop->runAction(
b0d623f7
A
8771 OSMemberFunctionCast(IOWorkLoop::Action, this, &IOServicePM::gatedSerialize),
8772 (OSObject *) this, (void *) s);
fe8ab488 8773 }
b0d623f7
A
8774
8775 return (kIOReturnSuccess == ret);
2d21ac55 8776}
6d2010ae 8777
4b17d6b6
A
8778void IOServicePM::pmPrint(
8779 uint32_t event,
8780 uintptr_t param1,
8781 uintptr_t param2 ) const
8782{
8783 gPlatform->PMLog(Name, event, param1, param2);
8784}
8785
8786void IOServicePM::pmTrace(
8787 uint32_t event,
8788 uintptr_t param1,
8789 uintptr_t param2 ) const
8790{
8791 const char * who = Name;
8792 uint64_t regId = Owner->getRegistryEntryID();
8793 uintptr_t name = 0;
8794
8795 static const uint32_t sStartStopBitField[] =
8796 { 0x00000000, 0x00000040 }; // Only Program Hardware so far
8797
8798 // Arcane formula from Hacker's Delight by Warren
8799 // abs(x) = ((int) x >> 31) ^ (x + ((int) x >> 31))
8800 uint32_t sgnevent = ((int) event >> 31);
8801 uint32_t absevent = sgnevent ^ (event + sgnevent);
8802 uint32_t code = IODBG_POWER(absevent);
8803
8804 uint32_t bit = 1 << (absevent & 0x1f);
8805 if ((absevent < (sizeof(sStartStopBitField) * 8)) &&
8806 (sStartStopBitField[absevent >> 5] & bit))
8807 {
8808 // Or in the START or END bits, Start = 1 & END = 2
8809 // If sgnevent == 0 then START - 0 => START
8810 // else if sgnevent == -1 then START - -1 => END
8811 code |= DBG_FUNC_START - sgnevent;
8812 }
8813
8814 // Copy the first characters of the name into an uintptr_t
8815 for (uint32_t i = 0; (i < sizeof(uintptr_t) && who[i] != 0); i++)
8816 {
8817 ((char *) &name)[sizeof(uintptr_t) - i - 1] = who[i];
8818 }
8819
8820 IOTimeStampConstant(code, name, (uintptr_t) regId, param1, param2);
8821}
8822