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