xref: /xnu-12377.81.4/iokit/IOKit/pwr_mgt/RootDomain.h (revision 043036a2b3718f7f0be807e2870f8f47d3fa0796)
1 /*
2  * Copyright (c) 1998-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
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.
14  *
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
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
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.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 #ifndef _IOKIT_ROOTDOMAIN_H
29 #define _IOKIT_ROOTDOMAIN_H
30 
31 #include <libkern/c++/OSPtr.h>
32 #include <IOKit/IOService.h>
33 #include <IOKit/pwr_mgt/IOPM.h>
34 #include <IOKit/IOBufferMemoryDescriptor.h>
35 #include <sys/vnode.h>
36 
37 #ifdef XNU_KERNEL_PRIVATE
38 
39 #include <IOKit/pwr_mgt/IOPMPrivate.h>
40 
41 struct AggressivesRecord;
42 struct IOPMMessageFilterContext;
43 struct IOPMActions;
44 struct IOPMSystemSleepParameters;
45 class PMSettingObject;
46 class PMTraceWorker;
47 class IOPMPowerStateQueue;
48 class RootDomainUserClient;
49 class PMAssertionsTracker;
50 class IOTimerEventSource;
51 
52 #define OBFUSCATE(x) (void *)VM_KERNEL_UNSLIDE_OR_PERM(x)
53 
54 #endif
55 
56 /*!
57  * Types for PM Assertions
58  * For creating, releasing, and getting PM assertion levels.
59  */
60 
61 /*! IOPMDriverAssertionType
62  * A bitfield describing a set of assertions. May be used to specify which assertions
63  * to set with <link>IOPMrootDomain::createPMAssertion</link>; or to query which
64  * assertions are set with <link>IOPMrootDomain::releasePMAssertion</link>.
65  */
66 typedef uint64_t IOPMDriverAssertionType;
67 
68 /* IOPMDriverAssertionID
69  * Drivers may create PM assertions to request system behavior (keep the system awake,
70  *  or keep the display awake). When a driver creates an assertion via
71  *  <link>IOPMrootDomain::createPMAssertion</link>, PM returns a handle to
72  *  the assertion of type IOPMDriverAssertionID.
73  */
74 typedef uint64_t IOPMDriverAssertionID;
75 #define kIOPMUndefinedDriverAssertionID       0
76 
77 /* IOPMDriverAssertionLevel
78  * Possible values for IOPMDriverAssertionLevel are <link>kIOPMDriverAssertionLevelOff</link>
79  * and <link>kIOPMDriverAssertionLevelOn</link>
80  */
81 typedef uint32_t IOPMDriverAssertionLevel;
82 #define kIOPMDriverAssertionLevelOff          0
83 #define kIOPMDriverAssertionLevelOn           255
84 
85 /*
86  * Flags for get/setSleepSupported()
87  */
88 enum {
89 	kRootDomainSleepNotSupported    = 0x00000000,
90 	kRootDomainSleepSupported         = 0x00000001,
91 	kFrameBufferDeepSleepSupported    = 0x00000002,
92 	kPCICantSleep                   = 0x00000004
93 };
94 
95 /*
96  * IOPMrootDomain registry property keys
97  */
98 #define kRootDomainSupportedFeatures        "Supported Features"
99 #define kRootDomainSleepReasonKey           "Last Sleep Reason"
100 #define kRootDomainSleepOptionsKey          "Last Sleep Options"
101 #define kIOPMRootDomainWakeReasonKey        "Wake Reason"
102 #define kIOPMRootDomainWakeTypeKey          "Wake Type"
103 #define kIOPMRootDomainPowerStatusKey       "Power Status"
104 
105 /*
106  * Possible sleep reasons found under kRootDomainSleepReasonsKey
107  */
108 #define kIOPMClamshellSleepKey              "Clamshell Sleep"
109 #define kIOPMPowerButtonSleepKey            "Power Button Sleep"
110 #define kIOPMSoftwareSleepKey               "Software Sleep"
111 #define kIOPMOSSwitchHibernationKey         "OS Switch Sleep"
112 #define kIOPMIdleSleepKey                   "Idle Sleep"
113 #define kIOPMLowPowerSleepKey               "Low Power Sleep"
114 #define kIOPMThermalEmergencySleepKey       "Thermal Emergency Sleep"
115 #define kIOPMMaintenanceSleepKey            "Maintenance Sleep"
116 
117 /*
118  * String constants for communication with PM CPU
119  */
120 #define kIOPMRootDomainLidCloseCString      "LidClose"
121 #define kIOPMRootDomainBatPowerCString      "BatPower"
122 
123 /*
124  * String constants to use as keys for a dictionary passed to IOPMRootDomain::claimSystemShutdownEvent
125  */
126 #define kIOPMRootDomainShutdownTime         "IOPMShutdownTime"
127 
128 /*
129  * Supported Feature bitfields for IOPMrootDomain::publishFeature()
130  */
131 enum {
132 	kIOPMSupportedOnAC      = (1 << 0),
133 	kIOPMSupportedOnBatt    = (1 << 1),
134 	kIOPMSupportedOnUPS     = (1 << 2)
135 };
136 
137 /*
138  * Supported run mode bitfields for IOPMrootDomain::requestRunMode()
139  */
140 enum {
141 	kIOPMRunModeFullWake = UINT64_MAX,
142 };
143 
144 typedef IOReturn (*IOPMSettingControllerCallback)
145 (OSObject *target, const OSSymbol *type,
146     OSObject *val, uintptr_t refcon);
147 
148 __BEGIN_DECLS
149 IONotifier *    registerSleepWakeInterest(
150 	IOServiceInterestHandler, void *, void * = NULL);
151 
152 IONotifier *    registerPrioritySleepWakeInterest(
153 	IOServiceInterestHandler handler,
154 	void * self, void * ref = NULL);
155 
156 IOReturn        acknowledgeSleepWakeNotification(void * );
157 
158 IOReturn        vetoSleepWakeNotification(void * PMrefcon);
159 __END_DECLS
160 
161 #define IOPM_ROOTDOMAIN_REV        2
162 
163 class IOPMrootDomain : public IOService
164 {
165 	OSDeclareFinalStructors(IOPMrootDomain);
166 
167 public:
168 	static IOPMrootDomain * construct( void );
169 
170 	virtual bool        start( IOService * provider ) APPLE_KEXT_OVERRIDE;
171 	virtual IOReturn    setAggressiveness( unsigned long, unsigned long ) APPLE_KEXT_OVERRIDE;
172 	virtual IOReturn    getAggressiveness( unsigned long, unsigned long * ) APPLE_KEXT_OVERRIDE;
173 
174 	virtual IOReturn    sleepSystem( void );
175 	IOReturn            sleepSystemOptions( OSDictionary *options );
176 
177 	virtual IOReturn    setProperties( OSObject * ) APPLE_KEXT_OVERRIDE;
178 	virtual bool        serializeProperties( OSSerialize * s ) const APPLE_KEXT_OVERRIDE;
179 	virtual OSPtr<OSObject>  copyProperty( const char * aKey ) const APPLE_KEXT_OVERRIDE;
180 
181 /*! @function systemPowerEventOccurred
182  *    @abstract Other drivers may inform IOPMrootDomain of system PM events
183  *    @discussion systemPowerEventOccurred is a richer alternative to receivePowerNotification()
184  *        Only Apple-owned kexts should have reason to call systemPowerEventOccurred.
185  *    @param event An OSSymbol describing the type of power event.
186  *    @param intValue A 32-bit integer value associated with the event.
187  *    @result kIOReturnSuccess on success */
188 
189 	IOReturn            systemPowerEventOccurred(
190 		const OSSymbol *event,
191 		uint32_t intValue );
192 
193 	IOReturn            systemPowerEventOccurred(
194 		const OSSymbol *event,
195 		OSObject *value );
196 
197 #ifdef XNU_KERNEL_PRIVATE   // Hide doc from public headers
198 /*! @function claimSystemWakeEvent
199  *   @abstract   Apple-internal SPI to describe system wake events.
200  *   @discussion IOKit drivers may call claimSystemWakeEvent() during system wakeup to
201  *               provide human readable debug information describing the event(s) that
202  *               caused the system to wake.
203  *
204  *               - Drivers should call claimSystemWakeEvent before completing
205  *                 their setPowerState() acknowledgement. IOPMrootDomain stops
206  *                 collecting wake events when driver wake is complete.
207  *
208  *               - It is only appropriate to claim a wake event when the driver
209  *                 can positively identify its hardware has generated an event
210  *                 that can wake the system.
211  *
212  *               - This call tracks wake events from a non-S0 state (S0i, S3, S4) into S0.
213  *               - This call does not track wake events from DarkWake(S0) to FullWake(S0).
214  *
215  *       Examples:
216  *               (reason  = "WiFi.TCPData",
217  *        details = "TCPKeepAlive packet arrived from IP 16.2.1.1")
218  *               (reason  = "WiFi.ScanOffload",
219  *        details = "WiFi station 'AppleWiFi' signal dropped below threshold")
220  *               (reason  = "Enet.LinkToggle",
221  *        details = "Ethernet attached")
222  *
223  *   @param device   The device/nub that is associated with the wake event.
224  *
225  *   @param flags    Pass kIOPMWakeEventSource if the device is the source
226  *                   of the wake event. Pass zero if the device is forwarding or
227  *                   aggregating wake events from multiple sources, e.g. an USB or
228  *                   Thunderbolt host controller.
229  *
230  *   @param reason   Caller should pass a human readable C string describing the
231  *                   wake reason. Please use a string from the list below, or create
232  *                   your own string matching this format:
233  *                             [Hardware].[Event]
234  *                             WiFi.MagicPacket
235  *                             WiFi.ScanOffload
236  *                             WiFi.mDNSConflict
237  *                             WiFi.mDNSService
238  *                             WiFi.TCPData
239  *                             WiFi.TCPTimeout
240  *                             WiFi.FirmwareCrash
241  *                             Enet.MagicPacket
242  *                             Enet.mDNSConflict
243  *                             Enet.mDNSService
244  *                             Enet.TCPData
245  *                             Enet.TCPTimeout
246  *                             Enet.Service
247  *                             Enet.LinkToggle
248  *                             Enet.ConflictResolution
249  *                             Enet.PatternMatch
250  *                             Enet.Timer
251  *                             Enet.LinkUpTimeout
252  *                             Enet.LinkDown
253  *                             USB.DeviceAttach
254  *                             USB.DeviceDetach
255  *
256  *    @param details Optional details further describing the wake event.
257  *                   Please pass an OSString defining the event.
258  */
259 #endif
260 	void                claimSystemWakeEvent(
261 		IOService     *device,
262 		IOOptionBits  flags,
263 		const char    *reason,
264 		OSObject      *details = NULL );
265 
266 	void                claimSystemBootEvent(
267 		IOService     *device,
268 		IOOptionBits  flags,
269 		const char    *reason,
270 		OSObject      *details = NULL );
271 
272 	void                claimSystemShutdownEvent(
273 		IOService     *device,
274 		IOOptionBits  flags,
275 		const char    *reason,
276 		OSObject      *details = NULL );
277 
278 	virtual IOReturn    receivePowerNotification( UInt32 msg );
279 
280 	virtual void        setSleepSupported( IOOptionBits flags );
281 
282 	virtual IOOptionBits getSleepSupported( void );
283 
284 	void                wakeFromDoze( void );
285 
286 	void                requestUserActive(IOService *driver, const char *reason);
287 
288 // KEXT driver announces support of power management feature
289 
290 	void                publishFeature( const char *feature );
291 
292 // KEXT driver announces support of power management feature
293 // And specifies power sources with kIOPMSupportedOn{AC/Batt/UPS} bitfield.
294 // Returns a unique uint32_t identifier for later removing support for this
295 // feature.
296 // NULL is acceptable for uniqueFeatureID for kexts without plans to unload.
297 
298 	void                publishFeature( const char *feature,
299 	    uint32_t supportedWhere,
300 	    uint32_t *uniqueFeatureID);
301 
302 // KEXT driver announces removal of a previously published power management
303 // feature. Pass 'uniqueFeatureID' returned from publishFeature()
304 
305 	IOReturn            removePublishedFeature( uint32_t removeFeatureID );
306 
307 /*! @function copyPMSetting
308  *   @abstract Copy the current value for a PM setting. Returns an OSNumber or
309  *       OSData depending on the setting.
310  *   @param whichSetting Name of the desired setting.
311  *   @result OSObject value if valid, NULL otherwise. */
312 
313 	OSPtr<OSObject>           copyPMSetting( OSSymbol *whichSetting );
314 
315 /*! @function registerPMSettingController
316  *   @abstract Register for callbacks on changes to certain PM settings.
317  *   @param settings NULL terminated array of C strings, each string for a PM
318  *       setting that the caller is interested in and wants to get callbacks for.
319  *   @param callout C function ptr or member function cast as such.
320  *   @param target The target of the callback, usually 'this'
321  *   @param refcon Will be passed to caller in callback; for caller's use.
322  *   @param handle Caller should keep the OSObject * returned here. If non-NULL,
323  *       handle will have a retain count of 1 on return. To deregister, pass to
324  *       unregisterPMSettingController()
325  *   @result kIOReturnSuccess on success. */
326 
327 	IOReturn            registerPMSettingController(
328 		const OSSymbol *settings[],
329 		IOPMSettingControllerCallback callout,
330 		OSObject   *target,
331 		uintptr_t  refcon,
332 		OSObject   **handle);                     // out param
333 
334 /*! @function registerPMSettingController
335  *   @abstract Register for callbacks on changes to certain PM settings.
336  *   @param settings NULL terminated array of C strings, each string for a PM
337  *       setting that the caller is interested in and wants to get callbacks for.
338  *   @param supportedPowerSources bitfield indicating which power sources these
339  *       settings are supported for (kIOPMSupportedOnAC, etc.)
340  *   @param callout C function ptr or member function cast as such.
341  *   @param target The target of the callback, usually 'this'
342  *   @param refcon Will be passed to caller in callback; for caller's use.
343  *   @param handle Caller should keep the OSObject * returned here. If non-NULL,
344  *       handle will have a retain count of 1 on return. To deregister, pass to
345  *       unregisterPMSettingController()
346  *   @result kIOReturnSuccess on success. */
347 
348 	IOReturn            registerPMSettingController(
349 		const OSSymbol *settings[],
350 		uint32_t   supportedPowerSources,
351 		IOPMSettingControllerCallback callout,
352 		OSObject   *target,
353 		uintptr_t  refcon,
354 		OSObject   **handle);                     // out param
355 
356 	virtual OSPtr<IONotifier> registerInterest(
357 		const OSSymbol * typeOfInterest,
358 		IOServiceInterestHandler handler,
359 		void * target, void * ref = NULL ) APPLE_KEXT_OVERRIDE;
360 
361 	virtual IOReturn    callPlatformFunction(
362 		const OSSymbol *functionName,
363 		bool waitForFunction,
364 		void *param1, void *param2,
365 		void *param3, void *param4 ) APPLE_KEXT_OVERRIDE;
366 
367 /*! @function createPMAssertion
368  *   @abstract Creates an assertion to influence system power behavior.
369  *   @param whichAssertionsBits A bitfield specify the assertion that the caller requests.
370  *   @param assertionLevel An integer detailing the initial assertion level, kIOPMDriverAssertionLevelOn
371  *       or kIOPMDriverAssertionLevelOff.
372  *   @param ownerService A pointer to the caller's IOService class, for tracking.
373  *   @param ownerDescription A reverse-DNS string describing the caller's identity and reason.
374  *   @result On success, returns a new assertion of type IOPMDriverAssertionID
375  */
376 	IOPMDriverAssertionID createPMAssertion(
377 		IOPMDriverAssertionType whichAssertionsBits,
378 		IOPMDriverAssertionLevel assertionLevel,
379 		IOService *ownerService,
380 		const char *ownerDescription);
381 
382 /* @function setPMAssertionLevel
383  *  @abstract Modify the level of a pre-existing assertion.
384  *  @discussion Change the value of a PM assertion to influence system behavior,
385  *   without undergoing the work required to create or destroy an assertion. Suggested
386  *   for clients who will assert and de-assert needs for PM behavior several times over
387  *   their lifespan.
388  *  @param assertionID An assertion ID previously returned by <link>createPMAssertion</link>
389  *  @param assertionLevel The new assertion level.
390  *  @result kIOReturnSuccess if it worked; kIOReturnNotFound or other IOReturn error on failure.
391  */
392 	IOReturn setPMAssertionLevel(IOPMDriverAssertionID assertionID, IOPMDriverAssertionLevel assertionLevel);
393 
394 /*! @function getPMAssertionLevel
395  *   @absract Returns the active level of the specified assertion(s).
396  *   @discussion Returns <link>kIOPMDriverAssertionLevelOff</link> or
397  *       <link>kIOPMDriverAssertionLevelOn</link>. If multiple assertions are specified
398  *       in the bitfield, only returns <link>kIOPMDriverAssertionLevelOn</link>
399  *       if all assertions are active.
400  *   @param whichAssertionBits Bits defining the assertion or assertions the caller is interested in
401  *       the level of. If in doubt, pass <link>kIOPMDriverAssertionCPUBit</link> as the argument.
402  *   @result Returns <link>kIOPMDriverAssertionLevelOff</link> or
403  *       <link>kIOPMDriverAssertionLevelOn</link> indicating the specified assertion's levels, if available.
404  *       If the assertions aren't supported on this machine, or aren't recognized by the OS, the
405  *       result is undefined.
406  */
407 	IOPMDriverAssertionLevel getPMAssertionLevel(IOPMDriverAssertionType whichAssertionBits);
408 
409 /*! @function releasePMAssertion
410  *   @abstract Removes an assertion to influence system power behavior.
411  *   @result On success, returns a new assertion of type IOPMDriverAssertionID *
412  */
413 	IOReturn releasePMAssertion(IOPMDriverAssertionID releaseAssertion);
414 
415 /*! @function restartWithStackshot
416  *   @abstract Take a stackshot of the system and restart the system.
417  *   @result Return kIOReturnSuccess if it work, kIOReturnError if the service is not available.
418  */
419 	IOReturn restartWithStackshot();
420 
421 #ifdef KERNEL_PRIVATE
422 	IOReturn    setWakeTime(uint64_t wakeContinuousTime);
423 	bool        isAOTMode(void);
424 	bool        isLPWMode(void);
425 #endif /* KERNEL_PRIVATE */
426 
427 #if XNU_KERNEL_PRIVATE
428 	IOReturn     _setWakeTime(uint64_t wakeContinuousTime);
429 	IOReturn acquireDriverKitMatchingAssertion();
430 	void releaseDriverKitMatchingAssertion();
431 	IOReturn acquireDriverKitSyncedAssertion(IOService * from, IOPMDriverAssertionID * assertionID);
432 	void releaseDriverKitSyncedAssertion(IOPMDriverAssertionID assertionID);
433 	int32_t considerRunMode(IOService * service, uint64_t pmDriverClass);
434 #endif
435 
436 	void        copyWakeReasonString( char * outBuf, size_t bufSize );
437 
438 private:
439 	unsigned long getRUN_STATE(void);
440 
441 	virtual IOReturn    changePowerStateTo( unsigned long ordinal ) APPLE_KEXT_COMPATIBILITY_OVERRIDE;
442 	virtual IOReturn    changePowerStateToPriv( unsigned long ordinal );
443 	virtual IOReturn    requestPowerDomainState( IOPMPowerFlags, IOPowerConnection *, unsigned long ) APPLE_KEXT_OVERRIDE;
444 	virtual void        powerChangeDone( unsigned long ) APPLE_KEXT_OVERRIDE;
445 	virtual bool        tellChangeDown( unsigned long ) APPLE_KEXT_OVERRIDE;
446 	virtual bool        askChangeDown( unsigned long ) APPLE_KEXT_OVERRIDE;
447 	virtual void        tellChangeUp( unsigned long ) APPLE_KEXT_OVERRIDE;
448 	virtual void        tellNoChangeDown( unsigned long ) APPLE_KEXT_OVERRIDE;
449 	virtual IOReturn configureReport(IOReportChannelList   *channels,
450 	    IOReportConfigureAction action,
451 	    void                    *result,
452 	    void                    *destination) APPLE_KEXT_OVERRIDE;
453 	virtual IOReturn updateReport(IOReportChannelList      *channels,
454 	    IOReportUpdateAction     action,
455 	    void                     *result,
456 	    void                     *destination) APPLE_KEXT_OVERRIDE;
457 
458 	void             configureReportGated(uint64_t channel_id,
459 	    uint64_t action,
460 	    void     *result);
461 	IOReturn         updateReportGated(uint64_t ch_id,
462 	    void *result,
463 	    IOBufferMemoryDescriptor *dest);
464 
465 #ifdef XNU_KERNEL_PRIVATE
466 /* Root Domain internals */
467 public:
468 	void        tagPowerPlaneService(
469 		IOService *             service,
470 		IOPMActions *           actions,
471 		IOPMPowerStateIndex     maxPowerState );
472 
473 	void        overrideOurPowerChange(
474 		IOService *             service,
475 		IOPMActions *           actions,
476 		const IOPMRequest *     request,
477 		IOPMPowerStateIndex *   inOutPowerState,
478 		IOPMPowerChangeFlags *  inOutChangeFlags );
479 
480 	void        handleOurPowerChangeStart(
481 		IOService *             service,
482 		IOPMActions *           actions,
483 		const IOPMRequest *     request,
484 		IOPMPowerStateIndex     powerState,
485 		IOPMPowerChangeFlags *  inOutChangeFlags );
486 
487 	void        handleOurPowerChangeDone(
488 		IOService *             service,
489 		IOPMActions *           actions,
490 		const IOPMRequest *     request,
491 		IOPMPowerStateIndex     powerState,
492 		IOPMPowerChangeFlags    changeFlags );
493 
494 	void        overridePowerChangeForService(
495 		IOService *             service,
496 		IOPMActions *           actions,
497 		const IOPMRequest *     request,
498 		IOPMPowerStateIndex *   inOutPowerState,
499 		IOPMPowerChangeFlags *  inOutChangeFlags );
500 
501 	void        handleActivityTickleForDisplayWrangler(
502 		IOService *             service,
503 		IOPMActions *           actions );
504 
505 	void        handleUpdatePowerClientForDisplayWrangler(
506 		IOService *             service,
507 		IOPMActions *           actions,
508 		const OSSymbol *        powerClient,
509 		IOPMPowerStateIndex     oldPowerState,
510 		IOPMPowerStateIndex     newPowerState );
511 
512 	bool        shouldDelayChildNotification(
513 		IOService *     service );
514 
515 	void        handlePowerChangeStartForPCIDevice(
516 		IOService *             service,
517 		IOPMActions *           actions,
518 		const IOPMRequest *     request,
519 		IOPMPowerStateIndex     powerState,
520 		IOPMPowerChangeFlags *  inOutChangeFlags );
521 
522 	void        handlePowerChangeDoneForPCIDevice(
523 		IOService *             service,
524 		IOPMActions *           actions,
525 		const IOPMRequest *     request,
526 		IOPMPowerStateIndex     powerState,
527 		IOPMPowerChangeFlags    changeFlags );
528 
529 	void        askChangeDownDone(
530 		IOPMPowerChangeFlags * inOutChangeFlags,
531 		bool * cancel );
532 
533 	void        handlePublishSleepWakeUUID(
534 		bool shouldPublish);
535 
536 	void        handleQueueSleepWakeUUID(
537 		OSObject *obj);
538 
539 	void        willTellSystemCapabilityDidChange(void);
540 
541 	void        handleSetDisplayPowerOn(bool powerOn);
542 
543 	void        willNotifyPowerChildren( IOPMPowerStateIndex newPowerState );
544 	void        willNotifyInterested( IOPMPowerStateIndex newPowerState );
545 
546 	IOReturn    setMaintenanceWakeCalendar(
547 		const IOPMCalendarStruct * calendar );
548 
549 	IOReturn    getSystemSleepType(uint32_t * sleepType, uint32_t * standbyTimer);
550 
551 // Handle callbacks from IOService::systemWillShutdown()
552 	void        acknowledgeSystemWillShutdown( IOService * from );
553 
554 // Handle platform halt and restart notifications
555 	void        handlePlatformHaltRestart( UInt32 pe_type );
556 
557 	IOReturn    shutdownSystem( void );
558 	IOReturn    restartSystem( void );
559 	void        handleSleepTimerExpiration( void );
560 	void        setIdleSleepRevertible( bool revertible );
561 
562 	bool        activitySinceSleep(void);
563 	bool        abortHibernation(void);
564 	void        updateConsoleUsers(void);
565 
566 	IOReturn    joinAggressiveness( IOService * service );
567 	void        handleAggressivesRequests( void );
568 
569 	void        kdebugTrace(uint32_t event, uint64_t regId,
570 	    uintptr_t param1, uintptr_t param2, uintptr_t param3 = 0);
571 	void        tracePoint(uint8_t point);
572 	void        traceDetail(uint32_t msgType, uint32_t msgIndex, uint32_t delay);
573 	void        traceNotification(OSObject *notifier, bool start, uint64_t ts = 0, uint32_t msgIndex = UINT_MAX);
574 	void        traceNotificationAck(OSObject *notifier, uint32_t delay_ms);
575 	void        traceNotificationResponse(OSObject *object, uint32_t delay_ms, uint32_t ack_time_us);
576 	void        traceFilteredNotification(OSObject *notifier);
577 	const char * getNotificationClientName(OSObject *notifier);
578 
579 	void        startSpinDump(uint32_t spindumpKind);
580 
581 	bool        systemMessageFilter(
582 		void * object, void * arg1, void * arg2, void * arg3 );
583 
584 	bool        updatePreventIdleSleepList(
585 		IOService * service, bool addNotRemove );
586 	void        updatePreventSystemSleepList(
587 		IOService * service, bool addNotRemove );
588 
589 	bool        updatePreventIdleSleepListInternal(
590 		IOService * service, bool addNotRemove, unsigned int oldCount);
591 	unsigned int idleSleepPreventersCount();
592 
593 	void        publishPMSetting(
594 		const OSSymbol * feature, uint32_t where, uint32_t * featureID );
595 
596 	void        pmStatsRecordEvent(
597 		int             eventIndex,
598 		AbsoluteTime    timestamp);
599 
600 	void        pmStatsRecordApplicationResponse(
601 		const OSSymbol      *response,
602 		const char          *name,
603 		int                 messageType,
604 		uint32_t            delay_ms,
605 		uint64_t            id,
606 		OSObject            *object,
607 		IOPMPowerStateIndex ps = 0,
608 		bool                async = false);
609 
610 	void        copyShutdownReasonString( char * outBuf, size_t bufSize );
611 	void        copyShutdownTime(uint64_t *time);
612 	void        lowLatencyAudioNotify(uint64_t time, boolean_t state);
613 
614 #if HIBERNATION
615 	bool        getHibernateSettings(
616 		uint32_t *  hibernateMode,
617 		uint32_t *  hibernateFreeRatio,
618 		uint32_t *  hibernateFreeTime );
619 	bool        mustHibernate( void );
620 #endif
621 	void        takeStackshot(bool restart);
622 	void        sleepWakeDebugTrig(bool restart);
623 	void        sleepWakeDebugEnableWdog();
624 	bool        sleepWakeDebugIsWdogEnabled();
625 	void        sleepWakeDebugSaveSpinDumpFile();
626 	bool        checkShutdownTimeout();
627 	void        panicWithShutdownLog(uint32_t timeoutInMs) __abortlike;
628 	uint32_t    getWatchdogTimeout();
629 	void        deleteStackshot();
630 
631 	IOReturn    createPMAssertionSafe(
632 		IOPMDriverAssertionID *assertionID,
633 		IOPMDriverAssertionType whichAssertionsBits,
634 		IOPMDriverAssertionLevel assertionLevel,
635 		IOService *ownerService,
636 		const char *ownerDescription);
637 	IOReturn    requestRunMode(uint64_t runModeMask);
638 	IOReturn    handleRequestRunMode(uint64_t runModeMask);
639 private:
640 	friend class PMSettingObject;
641 	friend class RootDomainUserClient;
642 	friend class PMAssertionsTracker;
643 
644 	static IOReturn sysPowerDownHandler( void * target, void * refCon,
645 	    UInt32 messageType, IOService * service,
646 	    void * messageArgument, vm_size_t argSize );
647 
648 	static IOReturn displayWranglerNotification( void * target, void * refCon,
649 	    UInt32 messageType, IOService * service,
650 	    void * messageArgument, vm_size_t argSize );
651 
652 	static IOReturn rootBusyStateChangeHandler( void * target, void * refCon,
653 	    UInt32 messageType, IOService * service,
654 	    void * messageArgument, vm_size_t argSize );
655 
656 	void initializeBootSessionUUID( void );
657 
658 	void fullWakeDelayedWork( void );
659 
660 	OSPtr<IOService>        wrangler;
661 	OSPtr<OSDictionary>     wranglerIdleSettings;
662 
663 	OSPtr<IOCommandGate>    commandGate;
664 	IOLock                  *featuresDictLock;// guards supportedFeatures
665 	IOLock                  *wakeEventLock;
666 	IOPMPowerStateQueue     *pmPowerStateQueue;
667 
668 	OSPtr<OSArray>           allowedPMSettings;
669 	OSPtr<OSArray>           noPublishPMSettings;
670 	OSPtr<PMTraceWorker>     pmTracer;
671 	PMAssertionsTracker     *pmAssertions;
672 
673 // Settings controller info
674 	IOLock                  *settingsCtrlLock;
675 	OSPtr<OSDictionary>      settingsCallbacks;
676 	OSPtr<OSDictionary>      fPMSettingsDict;
677 
678 // Statistics
679 	OSPtr<const OSSymbol>   _statsNameKey;
680 	OSPtr<const OSSymbol>   _statsPIDKey;
681 	OSPtr<const OSSymbol>   _statsTimeMSKey;
682 	OSPtr<const OSSymbol>   _statsResponseTypeKey;
683 	OSPtr<const OSSymbol>   _statsMessageTypeKey;
684 	OSPtr<const OSSymbol>   _statsPowerCapsKey;
685 	uint32_t                sleepCnt;
686 	uint32_t                darkWakeCnt;
687 	uint32_t                displayWakeCnt;
688 
689 	OSPtr<OSString>         queuedSleepWakeUUIDString;
690 	OSPtr<OSArray>          pmStatsAppResponses;
691 	IOLock                  *pmStatsLock;// guards pmStatsAppResponses
692 
693 	void                    *sleepDelaysReport; // report to track time taken to go to sleep
694 	uint32_t                sleepDelaysClientCnt;// Number of interested clients in sleepDelaysReport
695 	uint64_t                ts_sleepStart;
696 	uint64_t                wake2DarkwakeDelay;  // Time taken to change from full wake -> Dark wake
697 
698 	void                    *assertOnWakeReport;// report to track time spent without any assertions held after wake
699 	uint32_t                assertOnWakeClientCnt;// Number of clients interested in assertOnWakeReport
700 	clock_sec_t             assertOnWakeSecs;   // Num of secs after wake for first assertion
701 
702 	bool                    uuidPublished;
703 
704 // Pref: idle time before idle sleep
705 	bool                    idleSleepEnabled;
706 	uint32_t                sleepSlider;
707 	uint32_t                idleMilliSeconds;
708 	bool                    idleSleepRevertible;
709 
710 // Difference between sleepSlider and longestNonSleepSlider
711 	uint32_t                extraSleepDelay;
712 
713 // Used to wait between say display idle and system idle
714 	thread_call_t           extraSleepTimer;
715 	thread_call_t           powerButtonDown;
716 	thread_call_t           powerButtonUp;
717 	thread_call_t           diskSyncCalloutEntry;
718 	thread_call_t           fullWakeThreadCall;
719 	thread_call_t           updateConsoleUsersEntry;
720 
721 // Track system capabilities.
722 	uint32_t                _desiredCapability;
723 	uint32_t                _currentCapability;
724 	uint32_t                _pendingCapability;
725 	uint32_t                _highestCapability;
726 	OSPtr<OSSet>            _joinedCapabilityClients;
727 	uint32_t                _systemStateGeneration;
728 
729 // Type of clients that can receive system messages.
730 	enum {
731 		kSystemMessageClientPowerd    = 0x01,
732 		kSystemMessageClientLegacyApp = 0x02,
733 		kSystemMessageClientKernel    = 0x04,
734 		kSystemMessageClientAll       = 0x07
735 	};
736 	uint32_t                _systemMessageClientMask;
737 
738 	// Power state and capability change transitions.
739 	enum SystemTransitionType {
740 		kSystemTransitionNone         = 0,
741 		kSystemTransitionSleep        = 1,
742 		kSystemTransitionWake         = 2,
743 		kSystemTransitionCapability   = 3,
744 		kSystemTransitionNewCapClient = 4
745 	}                       _systemTransitionType;
746 
747 	// Update the current systemTransitionType and wakeup any waiters blocking on transitions.
748 	void setSystemTransitionTypeGated(SystemTransitionType type);
749 
750 	// Block until no system transitions are in progress and the current power state has reached at a minimum state.
751 	void waitForSystemTransitionToMinPowerState(IOPMRootDomainPowerState state);
752 
753 	unsigned int            systemBooting           :1;
754 	unsigned int            systemShutdown          :1;
755 	unsigned int            systemDarkWake          :1;
756 	unsigned int            clamshellExists         :1;
757 	unsigned int            clamshellClosed         :1;
758 	unsigned int            clamshellDisabled       :1;
759 	unsigned int            desktopMode             :1;
760 	unsigned int            acAdaptorConnected      :1;
761 
762 	unsigned int            clamshellIgnoreClose    :1;
763 	unsigned int            idleSleepTimerPending   :1;
764 	unsigned int            userDisabledAllSleep    :1;
765 	unsigned int            ignoreTellChangeDown    :1;
766 	unsigned int            wranglerAsleep          :1;
767 	unsigned int            darkWakeExit            :1;
768 	unsigned int            _preventUserActive      :1;
769 	unsigned int            darkWakePowerClamped    :1;
770 
771 	unsigned int            capabilityLoss          :1;
772 	unsigned int            pciCantSleepFlag        :1;
773 	unsigned int            pciCantSleepValid       :1;
774 	unsigned int            darkWakeLogClamp        :1;
775 	unsigned int            darkWakeToSleepASAP     :1;
776 	unsigned int            darkWakeMaintenance     :1;
777 	unsigned int            darkWakeSleepService    :1;
778 	unsigned int            darkWakePostTickle      :1;
779 
780 	unsigned int            sleepTimerMaintenance   :1;
781 	unsigned int            sleepToStandby          :1;
782 	unsigned int            lowBatteryCondition     :1;
783 	unsigned int            ldmHibernateDisable     :1;
784 	unsigned int            hibernateDisabled       :1;
785 	unsigned int            hibernateRetry          :1;
786 	unsigned int            wranglerTickled         :1;
787 	unsigned int            userIsActive            :1;
788 	unsigned int            userWasActive           :1;
789 
790 	unsigned int            displayIdleForDemandSleep :1;
791 	unsigned int            darkWakeHibernateError  :1;
792 	unsigned int            thermalWarningState     :1;
793 	unsigned int            toldPowerdCapWillChange :1;
794 	unsigned int            displayPowerOnRequested :1;
795 	unsigned int            isRTCAlarmWake          :1;
796 	unsigned int            wranglerPowerOff        :1;
797 	unsigned int            thermalEmergencyState   :1;
798 
799 	uint8_t                 tasksSuspended;
800 	uint8_t                 tasksSuspendState;
801 	uint32_t                hibernateMode;
802 	AbsoluteTime            userActivityTime;
803 	AbsoluteTime            userActivityTime_prev;
804 	uint32_t                userActivityCount;
805 	uint32_t                userActivityAtSleep;
806 	uint32_t                lastSleepReason;
807 	uint32_t                fullToDarkReason;
808 	uint32_t                hibernateAborted;
809 	uint8_t                 standbyNixed;
810 	uint8_t                 resetTimers;
811 
812 	enum FullWakeReason {
813 		kFullWakeReasonNone = 0,
814 		kFullWakeReasonLocalUser = 1,
815 		kFullWakeReasonDisplayOn = 2,
816 		fFullWakeReasonDisplayOnAndLocalUser = 3
817 	};
818 	uint32_t                fullWakeReason;
819 
820 	enum {
821 		kClamshellSleepDisableInternal = 0x01,
822 		kClamshellSleepDisablePowerd   = 0x02
823 	};
824 	uint32_t                clamshellSleepDisableMask;
825 
826 // Info for communicating system state changes to PMCPU
827 	int32_t                 idxPMCPUClamshell;
828 	int32_t                 idxPMCPULimitedPower;
829 
830 	IOOptionBits            platformSleepSupport;
831 	uint32_t                _debugWakeSeconds;
832 
833 	queue_head_t            aggressivesQueue;
834 	thread_call_t           aggressivesThreadCall;
835 	OSPtr<OSData>                aggressivesData;
836 
837 	AbsoluteTime            userBecameInactiveTime;
838 
839 // PCI top-level PM trace
840 	OSPtr<IOService>        pciHostBridgeDevice;
841 	OSPtr<IOService>        pciHostBridgeDriver;
842 
843 	OSPtr<IONotifier>       systemCapabilityNotifier;
844 
845 	typedef struct {
846 		uint32_t            pid;
847 		uint32_t            refcount;
848 	} PMNotifySuspendedStruct;
849 
850 	uint32_t                pmSuspendedCapacity;
851 	uint32_t                pmSuspendedSize;
852 	PMNotifySuspendedStruct *pmSuspendedPIDS;
853 
854 	OSPtr<OSSet>            preventIdleSleepList;
855 	OSPtr<OSSet>            preventSystemSleepList;
856 
857 	OSPtr<const OSSymbol>   _nextScheduledAlarmType;
858 	clock_sec_t             _nextScheduledAlarmUTC;
859 	clock_sec_t             _calendarWakeAlarmUTC;
860 	UInt32                  _scheduledAlarmMask;
861 	UInt32                  _userScheduledAlarmMask;
862 
863 #if HIBERNATION
864 	clock_sec_t             _standbyTimerResetSeconds;
865 #endif
866 	volatile uint32_t   swd_lock;/* Lock to access swd_buffer & and its header */
867 	void  *             swd_buffer;/* Memory allocated for dumping sleep/wake logs */
868 	uint32_t            swd_flags;/* Flags defined in IOPMPrivate.h */
869 	void *              swd_compressed_buffer;
870 	void  *             swd_spindump_buffer;
871 	thread_t            notifierThread;
872 	OSPtr<OSObject>     notifierObject;
873 
874 	OSPtr<IOBufferMemoryDescriptor>    swd_spindump_memDesc;
875 	OSPtr<IOBufferMemoryDescriptor>    swd_memDesc;
876 
877 // Wake Event Reporting
878 	OSPtr<OSArray>       _systemWakeEventsArray;
879 	bool                 _acceptSystemWakeEvents;
880 
881 	// AOT --
882 	IOPMCalendarStruct   _aotWakeTimeCalendar;
883 	OSPtr<IOTimerEventSource> _aotTimerES;
884 	clock_sec_t          _aotWakeTimeUTC;
885 	uint64_t             _aotTestTime;
886 	uint64_t             _aotTestInterval;
887 	uint64_t             _aotEndTime;
888 	uint32_t             _aotPendingFlags;
889 public:
890 	IOPMAOTMetrics      * _aotMetrics;
891 	uint32_t              _aotMode;
892 private:
893 	uint32_t             _aotLingerTime;
894 	uint8_t              _aotNow;
895 	uint8_t              _aotTasksSuspended;
896 	uint8_t              _aotTimerScheduled;
897 	uint8_t              _aotReadyToFullWake;
898 	uint64_t             _aotLastWakeTime;
899 	uint64_t             _aotWakeTimeContinuous;
900 	uint64_t             _aotWakePreWindow;
901 	uint64_t             _aotWakePostWindow;
902 	uint64_t             _aotRunMode;
903 
904 	size_t               _driverKitMatchingAssertionCount;
905 	IOPMDriverAssertionID _driverKitMatchingAssertion;
906 	size_t               _driverKitSyncedAssertionCount;
907 
908 	bool        aotShouldExit(bool software);
909 	void        aotExit(bool cps);
910 	void        aotEvaluate(IOTimerEventSource * timer);
911 public:
912 	// -- AOT
913 	enum {
914 		kTasksSuspendUnsuspended = 0,
915 		kTasksSuspendSuspended   = 1,
916 		kTasksSuspendNoChange    = -1,
917 	};
918 private:
919 	bool        updateTasksSuspend(int newTasksSuspended, int newAOTTasksSuspended);
920 	int         findSuspendedPID(uint32_t pid, uint32_t *outRefCount);
921 
922 // IOPMrootDomain internal sleep call
923 	IOReturn    privateSleepSystem( uint32_t sleepReason );
924 	void        reportUserInput( void );
925 	void        updateUserActivity( void );
926 	void        setDisableClamShellSleep( bool );
927 	void        setClamShellSleepDisable(bool disable, uint32_t bitmask);
928 	bool        checkSystemSleepAllowed( IOOptionBits options,
929 	    uint32_t sleepReason );
930 	bool        checkSystemSleepEnabled( void );
931 	bool        checkSystemCanSleep( uint32_t sleepReason );
932 	bool        checkSystemCanSustainFullWake( void );
933 	bool        checkSystemCanAbortIdleSleep( void );
934 	void        adjustPowerState( bool sleepASAP = false );
935 	bool        attemptIdleSleepAbort( void );
936 	void        setQuickSpinDownTimeout( void );
937 	void        restoreUserSpinDownTimeout( void );
938 
939 	bool        shouldSleepOnClamshellClosed(void );
940 	bool        shouldSleepOnRTCAlarmWake(void );
941 	void        sendClientClamshellNotification( void );
942 
943 // Inform PMCPU of changes to state like lid, AC vs. battery
944 	void        informCPUStateChange( uint32_t type, uint32_t value );
945 
946 	void        dispatchPowerEvent( uint32_t event, void * arg0, uint64_t arg1 );
947 	void        handlePowerNotification( UInt32 msg );
948 
949 	IOReturn    setPMSetting(const OSSymbol *, OSObject *);
950 
951 	void        startIdleSleepTimer( uint32_t inMilliSeconds );
952 	void        cancelIdleSleepTimer( void );
953 	uint32_t    getTimeToIdleSleep( void );
954 
955 	IOReturn    setAggressiveness(
956 		unsigned long type,
957 		unsigned long value,
958 		IOOptionBits  options );
959 
960 	void        synchronizeAggressives(
961 		queue_head_t * services,
962 		const AggressivesRecord * array,
963 		int count );
964 
965 	void        broadcastAggressives(
966 		const AggressivesRecord * array,
967 		int count );
968 
969 	IOReturn    setPMAssertionUserLevels(IOPMDriverAssertionType);
970 
971 	void        publishSleepWakeUUID( bool shouldPublish );
972 
973 	void        evaluatePolicy( int stimulus, uint32_t arg = 0 );
974 	void        requestFullWake( FullWakeReason reason );
975 	void        willEnterFullWake( void );
976 
977 	void        evaluateAssertions(IOPMDriverAssertionType newAssertions,
978 	    IOPMDriverAssertionType oldAssertions);
979 
980 	void        deregisterPMSettingObject( PMSettingObject * pmso );
981 
982 	uint32_t    checkForValidDebugData(const char *fname, vfs_context_t *ctx,
983 	    void *tmpBuf, struct vnode **vp);
984 	void        getFailureData(thread_t *thread, char *failureStr, size_t strLen);
985 	void        saveFailureData2File();
986 	void        tracePhase2String(uint32_t tracePhase, const char **phaseString, const char **description);
987 	void        sleepWakeDebugMemAlloc();
988 	void        sleepWakeDebugSpinDumpMemAlloc();
989 	errno_t     sleepWakeDebugSaveFile(const char *name, char *buf, int len);
990 
991 	IOReturn    changePowerStateWithOverrideTo( IOPMPowerStateIndex ordinal, IOPMRequestTag tag );
992 	IOReturn    changePowerStateWithTagToPriv( IOPMPowerStateIndex ordinal, IOPMRequestTag tag );
993 	IOReturn    changePowerStateWithTagTo( IOPMPowerStateIndex ordinal, IOPMRequestTag tag );
994 
995 #if HIBERNATION
996 	bool        getSleepOption( const char * key, uint32_t * option );
997 	bool        evaluateSystemSleepPolicy( IOPMSystemSleepParameters * p,
998 	    int phase, uint32_t * hibMode );
999 	void        evaluateSystemSleepPolicyEarly( void );
1000 	void        evaluateSystemSleepPolicyFinal( void );
1001 	void        setLockdownModeHibernation(uint32_t status);
1002 #endif /* HIBERNATION */
1003 
1004 	bool        latchDisplayWranglerTickle( bool latch );
1005 	void        setDisplayPowerOn( uint32_t options );
1006 
1007 	void        acceptSystemWakeEvents( uint32_t control );
1008 	void        systemDidNotSleep( void );
1009 	void        preventTransitionToUserActive( bool prevent );
1010 	void        setThermalState(OSObject *value);
1011 	void        copySleepPreventersList(OSArray  **idleSleepList, OSArray  **systemSleepList);
1012 	void        copySleepPreventersListWithID(OSArray  **idleSleepList, OSArray  **systemSleepList);
1013 	void        recordRTCAlarm(const OSSymbol *type, OSObject *object);
1014 	void        scheduleImmediateDebugWake( void );
1015 
1016 	// Used to inform interested clients about low latency audio activity in the system
1017 	OSPtr<OSDictionary>   lowLatencyAudioNotifierDict;
1018 	OSPtr<OSNumber>       lowLatencyAudioNotifyStateVal;
1019 	OSPtr<OSNumber>       lowLatencyAudioNotifyTimestampVal;
1020 	OSPtr<const OSSymbol> lowLatencyAudioNotifyStateSym;
1021 	OSPtr<const OSSymbol> lowLatencyAudioNotifyTimestampSym;
1022 #endif /* XNU_KERNEL_PRIVATE */
1023 };
1024 
1025 #ifdef XNU_KERNEL_PRIVATE
1026 class IORootParent : public IOService
1027 {
1028 	OSDeclareFinalStructors(IORootParent);
1029 
1030 public:
1031 	static void initialize( void );
1032 	virtual OSPtr<OSObject> copyProperty( const char * aKey ) const APPLE_KEXT_OVERRIDE;
1033 	bool start( IOService * nub ) APPLE_KEXT_OVERRIDE;
1034 	void shutDownSystem( void );
1035 	void restartSystem( void );
1036 	void sleepSystem( void );
1037 	void dozeSystem( void );
1038 	void sleepToDoze( void );
1039 	void wakeSystem( void );
1040 };
1041 
1042 void     IOHibernateSystemInit(IOPMrootDomain * rootDomain);
1043 
1044 IOReturn IOHibernateSystemSleep(void);
1045 IOReturn IOHibernateIOKitSleep(void);
1046 IOReturn IOHibernateSystemHasSlept(void);
1047 IOReturn IOHibernateSystemWake(void);
1048 IOReturn IOHibernateSystemPostWake(bool now);
1049 uint32_t IOHibernateWasScreenLocked(void);
1050 void     IOHibernateSetScreenLocked(uint32_t lockState);
1051 void     IOHibernateSetWakeCapabilities(uint32_t capability);
1052 void     IOHibernateSystemRestart(void);
1053 
1054 #endif /* XNU_KERNEL_PRIVATE */
1055 
1056 #endif /* _IOKIT_ROOTDOMAIN_H */
1057