2 * Copyright (c) 1998-2014 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 #include <IOKit/system.h>
31 #include <IOKit/IOService.h>
32 #include <libkern/OSDebug.h>
33 #include <libkern/c++/OSContainers.h>
34 #include <libkern/c++/OSKext.h>
35 #include <libkern/c++/OSUnserialize.h>
36 #include <IOKit/IOCatalogue.h>
37 #include <IOKit/IOCommand.h>
38 #include <IOKit/IODeviceTreeSupport.h>
39 #include <IOKit/IODeviceMemory.h>
40 #include <IOKit/IOInterrupts.h>
41 #include <IOKit/IOInterruptController.h>
42 #include <IOKit/IOPlatformExpert.h>
43 #include <IOKit/IOMessage.h>
44 #include <IOKit/IOLib.h>
45 #include <IOKit/IOKitKeysPrivate.h>
46 #include <IOKit/IOBSD.h>
47 #include <IOKit/IOUserClient.h>
48 #include <IOKit/IOWorkLoop.h>
49 #include <IOKit/IOTimeStamp.h>
50 #include <IOKit/IOHibernatePrivate.h>
51 #include <IOKit/IOInterruptAccountingPrivate.h>
52 #include <IOKit/IOKernelReporters.h>
53 #include <mach/sync_policy.h>
54 #include <IOKit/assert.h>
55 #include <sys/errno.h>
57 #include <machine/pal_routines.h>
62 #define OBFUSCATE(x) ((void *)(VM_KERNEL_ADDRPERM(x)))
64 #include "IOServicePrivate.h"
65 #include "IOKitKernelInternal.h"
67 // take lockForArbitration before LOCKNOTIFY
69 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
71 #define super IORegistryEntry
73 OSDefineMetaClassAndStructors(IOService
, IORegistryEntry
)
75 OSDefineMetaClassAndStructors(_IOServiceNotifier
, IONotifier
)
77 OSDefineMetaClassAndStructors(_IOServiceInterestNotifier
, IONotifier
)
79 OSDefineMetaClassAndStructors(_IOConfigThread
, OSObject
)
81 OSDefineMetaClassAndStructors(_IOServiceJob
, OSObject
)
83 OSDefineMetaClassAndStructors(IOResources
, IOService
)
85 OSDefineMetaClassAndStructors(_IOOpenServiceIterator
, OSIterator
)
87 OSDefineMetaClassAndAbstractStructors(IONotifier
, OSObject
)
89 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
91 static IOPlatformExpert
* gIOPlatform
;
92 static class IOPMrootDomain
* gIOPMRootDomain
;
93 const IORegistryPlane
* gIOServicePlane
;
94 const IORegistryPlane
* gIOPowerPlane
;
95 const OSSymbol
* gIODeviceMemoryKey
;
96 const OSSymbol
* gIOInterruptControllersKey
;
97 const OSSymbol
* gIOInterruptSpecifiersKey
;
99 const OSSymbol
* gIOResourcesKey
;
100 const OSSymbol
* gIOResourceMatchKey
;
101 const OSSymbol
* gIOProviderClassKey
;
102 const OSSymbol
* gIONameMatchKey
;
103 const OSSymbol
* gIONameMatchedKey
;
104 const OSSymbol
* gIOPropertyMatchKey
;
105 const OSSymbol
* gIOLocationMatchKey
;
106 const OSSymbol
* gIOParentMatchKey
;
107 const OSSymbol
* gIOPathMatchKey
;
108 const OSSymbol
* gIOMatchCategoryKey
;
109 const OSSymbol
* gIODefaultMatchCategoryKey
;
110 const OSSymbol
* gIOMatchedServiceCountKey
;
112 const OSSymbol
* gIOMapperIDKey
;
113 const OSSymbol
* gIOUserClientClassKey
;
114 const OSSymbol
* gIOKitDebugKey
;
116 const OSSymbol
* gIOCommandPoolSizeKey
;
118 const OSSymbol
* gIOConsoleLockedKey
;
119 const OSSymbol
* gIOConsoleUsersKey
;
120 const OSSymbol
* gIOConsoleSessionUIDKey
;
121 const OSSymbol
* gIOConsoleSessionAuditIDKey
;
122 const OSSymbol
* gIOConsoleUsersSeedKey
;
123 const OSSymbol
* gIOConsoleSessionOnConsoleKey
;
124 const OSSymbol
* gIOConsoleSessionLoginDoneKey
;
125 const OSSymbol
* gIOConsoleSessionSecureInputPIDKey
;
126 const OSSymbol
* gIOConsoleSessionScreenLockedTimeKey
;
128 clock_sec_t gIOConsoleLockTime
;
129 static bool gIOConsoleLoggedIn
;
131 static uint32_t gIOScreenLockState
;
133 static IORegistryEntry
* gIOChosenEntry
;
135 static int gIOResourceGenerationCount
;
137 const OSSymbol
* gIOServiceKey
;
138 const OSSymbol
* gIOPublishNotification
;
139 const OSSymbol
* gIOFirstPublishNotification
;
140 const OSSymbol
* gIOMatchedNotification
;
141 const OSSymbol
* gIOFirstMatchNotification
;
142 const OSSymbol
* gIOTerminatedNotification
;
144 const OSSymbol
* gIOGeneralInterest
;
145 const OSSymbol
* gIOBusyInterest
;
146 const OSSymbol
* gIOAppPowerStateInterest
;
147 const OSSymbol
* gIOPriorityPowerStateInterest
;
148 const OSSymbol
* gIOConsoleSecurityInterest
;
150 static OSDictionary
* gNotifications
;
151 static IORecursiveLock
* gNotificationLock
;
153 static IOService
* gIOResources
;
154 static IOService
* gIOServiceRoot
;
156 static OSOrderedSet
* gJobs
;
157 static semaphore_port_t gJobsSemaphore
;
158 static IOLock
* gJobsLock
;
159 static int gOutstandingJobs
;
160 static int gNumConfigThreads
;
161 static int gNumWaitingThreads
;
162 static IOLock
* gIOServiceBusyLock
;
164 static thread_t gIOTerminateThread
;
165 static UInt32 gIOTerminateWork
;
166 static OSArray
* gIOTerminatePhase2List
;
167 static OSArray
* gIOStopList
;
168 static OSArray
* gIOStopProviderList
;
169 static OSArray
* gIOFinalizeList
;
171 static SInt32 gIOConsoleUsersSeed
;
172 static OSData
* gIOConsoleUsersSeedValue
;
174 extern const OSSymbol
* gIODTPHandleKey
;
176 const OSSymbol
* gIOPlatformSleepActionKey
;
177 const OSSymbol
* gIOPlatformWakeActionKey
;
178 const OSSymbol
* gIOPlatformQuiesceActionKey
;
179 const OSSymbol
* gIOPlatformActiveActionKey
;
180 const OSSymbol
* gIOPlatformHaltRestartActionKey
;
182 const OSSymbol
* gIOPlatformFunctionHandlerSet
;
184 static IOLock
* gIOConsoleUsersLock
;
185 static thread_call_t gIOConsoleLockCallout
;
187 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
189 #define LOCKREADNOTIFY() \
190 IORecursiveLockLock( gNotificationLock )
191 #define LOCKWRITENOTIFY() \
192 IORecursiveLockLock( gNotificationLock )
193 #define LOCKWRITE2READNOTIFY()
194 #define UNLOCKNOTIFY() \
195 IORecursiveLockUnlock( gNotificationLock )
196 #define SLEEPNOTIFY(event) \
197 IORecursiveLockSleep( gNotificationLock, (void *)(event), THREAD_UNINT )
198 #define SLEEPNOTIFYTO(event, deadline) \
199 IORecursiveLockSleepDeadline( gNotificationLock, (void *)(event), deadline, THREAD_UNINT )
200 #define WAKEUPNOTIFY(event) \
201 IORecursiveLockWakeup( gNotificationLock, (void *)(event), /* wake one */ false )
203 #define randomDelay() \
204 int del = read_processor_clock(); \
205 del = (((int)IOThreadSelf()) ^ del ^ (del >> 10)) & 0x3ff; \
208 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
210 #define queue_element(entry, element, type, field) do { \
211 vm_address_t __ele = (vm_address_t) (entry); \
212 __ele -= -4 + ((size_t)(&((type) 4)->field)); \
213 (element) = (type) __ele; \
216 #define iterqueue(que, elt) \
217 for (queue_entry_t elt = queue_first(que); \
218 !queue_end(que, elt); \
219 elt = queue_next(elt))
221 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
223 struct IOInterruptAccountingReporter
{
224 IOSimpleReporter
* reporter
; /* Reporter responsible for communicating the statistics */
225 IOInterruptAccountingData
* statistics
; /* The live statistics values, if any */
228 struct ArbitrationLockQueueElement
{
237 static queue_head_t gArbitrationLockQueueActive
;
238 static queue_head_t gArbitrationLockQueueWaiting
;
239 static queue_head_t gArbitrationLockQueueFree
;
240 static IOLock
* gArbitrationLockQueueLock
;
242 bool IOService::isInactive( void ) const
243 { return( 0 != (kIOServiceInactiveState
& getState())); }
245 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
247 #if defined(__i386__) || defined(__x86_64__)
249 // Only used by the intel implementation of
250 // IOService::requireMaxBusStall(UInt32 ns)
251 // IOService::requireMaxInterruptDelay(uint32_t ns)
254 IOService
* fService
;
260 kCpuDelayBusStall
, kCpuDelayInterrupt
,
264 static OSData
*sCpuDelayData
= OSData::withCapacity(8 * sizeof(CpuDelayEntry
));
265 static IORecursiveLock
*sCpuDelayLock
= IORecursiveLockAlloc();
266 static OSArray
*sCpuLatencyHandlers
[kCpuNumDelayTypes
];
267 const OSSymbol
*sCPULatencyFunctionName
[kCpuNumDelayTypes
];
268 static OSNumber
* sCPULatencyHolder
[kCpuNumDelayTypes
];
269 static OSNumber
* sCPULatencySet
[kCpuNumDelayTypes
];
272 requireMaxCpuDelay(IOService
* service
, UInt32 ns
, UInt32 delayType
);
274 setLatencyHandler(UInt32 delayType
, IOService
* target
, bool enable
);
276 #endif /* defined(__i386__) || defined(__x86_64__) */
278 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
280 void IOService::initialize( void )
284 gIOServicePlane
= IORegistryEntry::makePlane( kIOServicePlane
);
285 gIOPowerPlane
= IORegistryEntry::makePlane( kIOPowerPlane
);
287 gIOProviderClassKey
= OSSymbol::withCStringNoCopy( kIOProviderClassKey
);
288 gIONameMatchKey
= OSSymbol::withCStringNoCopy( kIONameMatchKey
);
289 gIONameMatchedKey
= OSSymbol::withCStringNoCopy( kIONameMatchedKey
);
290 gIOPropertyMatchKey
= OSSymbol::withCStringNoCopy( kIOPropertyMatchKey
);
291 gIOPathMatchKey
= OSSymbol::withCStringNoCopy( kIOPathMatchKey
);
292 gIOLocationMatchKey
= OSSymbol::withCStringNoCopy( kIOLocationMatchKey
);
293 gIOParentMatchKey
= OSSymbol::withCStringNoCopy( kIOParentMatchKey
);
295 gIOMatchCategoryKey
= OSSymbol::withCStringNoCopy( kIOMatchCategoryKey
);
296 gIODefaultMatchCategoryKey
= OSSymbol::withCStringNoCopy(
297 kIODefaultMatchCategoryKey
);
298 gIOMatchedServiceCountKey
= OSSymbol::withCStringNoCopy(
299 kIOMatchedServiceCountKey
);
301 gIOUserClientClassKey
= OSSymbol::withCStringNoCopy( kIOUserClientClassKey
);
303 gIOResourcesKey
= OSSymbol::withCStringNoCopy( kIOResourcesClass
);
304 gIOResourceMatchKey
= OSSymbol::withCStringNoCopy( kIOResourceMatchKey
);
306 gIODeviceMemoryKey
= OSSymbol::withCStringNoCopy( "IODeviceMemory" );
307 gIOInterruptControllersKey
308 = OSSymbol::withCStringNoCopy("IOInterruptControllers");
309 gIOInterruptSpecifiersKey
310 = OSSymbol::withCStringNoCopy("IOInterruptSpecifiers");
312 gIOMapperIDKey
= OSSymbol::withCStringNoCopy(kIOMapperIDKey
);
314 gIOKitDebugKey
= OSSymbol::withCStringNoCopy( kIOKitDebugKey
);
316 gIOCommandPoolSizeKey
= OSSymbol::withCStringNoCopy( kIOCommandPoolSizeKey
);
318 gIOGeneralInterest
= OSSymbol::withCStringNoCopy( kIOGeneralInterest
);
319 gIOBusyInterest
= OSSymbol::withCStringNoCopy( kIOBusyInterest
);
320 gIOAppPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOAppPowerStateInterest
);
321 gIOPriorityPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOPriorityPowerStateInterest
);
322 gIOConsoleSecurityInterest
= OSSymbol::withCStringNoCopy( kIOConsoleSecurityInterest
);
324 gNotifications
= OSDictionary::withCapacity( 1 );
325 gIOPublishNotification
= OSSymbol::withCStringNoCopy(
326 kIOPublishNotification
);
327 gIOFirstPublishNotification
= OSSymbol::withCStringNoCopy(
328 kIOFirstPublishNotification
);
329 gIOMatchedNotification
= OSSymbol::withCStringNoCopy(
330 kIOMatchedNotification
);
331 gIOFirstMatchNotification
= OSSymbol::withCStringNoCopy(
332 kIOFirstMatchNotification
);
333 gIOTerminatedNotification
= OSSymbol::withCStringNoCopy(
334 kIOTerminatedNotification
);
335 gIOServiceKey
= OSSymbol::withCStringNoCopy( kIOServiceClass
);
337 gIOConsoleLockedKey
= OSSymbol::withCStringNoCopy( kIOConsoleLockedKey
);
338 gIOConsoleUsersKey
= OSSymbol::withCStringNoCopy( kIOConsoleUsersKey
);
339 gIOConsoleSessionUIDKey
= OSSymbol::withCStringNoCopy( kIOConsoleSessionUIDKey
);
340 gIOConsoleSessionAuditIDKey
= OSSymbol::withCStringNoCopy( kIOConsoleSessionAuditIDKey
);
342 gIOConsoleUsersSeedKey
= OSSymbol::withCStringNoCopy(kIOConsoleUsersSeedKey
);
343 gIOConsoleSessionOnConsoleKey
= OSSymbol::withCStringNoCopy(kIOConsoleSessionOnConsoleKey
);
344 gIOConsoleSessionLoginDoneKey
= OSSymbol::withCStringNoCopy(kIOConsoleSessionLoginDoneKey
);
345 gIOConsoleSessionSecureInputPIDKey
= OSSymbol::withCStringNoCopy(kIOConsoleSessionSecureInputPIDKey
);
346 gIOConsoleSessionScreenLockedTimeKey
= OSSymbol::withCStringNoCopy(kIOConsoleSessionScreenLockedTimeKey
);
348 gIOConsoleUsersSeedValue
= OSData::withBytesNoCopy(&gIOConsoleUsersSeed
, sizeof(gIOConsoleUsersSeed
));
350 gIOPlatformSleepActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformSleepActionKey
);
351 gIOPlatformWakeActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformWakeActionKey
);
352 gIOPlatformQuiesceActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformQuiesceActionKey
);
353 gIOPlatformActiveActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformActiveActionKey
);
354 gIOPlatformHaltRestartActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformHaltRestartActionKey
);
356 gIOPlatformFunctionHandlerSet
= OSSymbol::withCStringNoCopy(kIOPlatformFunctionHandlerSet
);
357 #if defined(__i386__) || defined(__x86_64__)
358 sCPULatencyFunctionName
[kCpuDelayBusStall
] = OSSymbol::withCStringNoCopy(kIOPlatformFunctionHandlerMaxBusDelay
);
359 sCPULatencyFunctionName
[kCpuDelayInterrupt
] = OSSymbol::withCStringNoCopy(kIOPlatformFunctionHandlerMaxInterruptDelay
);
361 for (idx
= 0; idx
< kCpuNumDelayTypes
; idx
++)
363 sCPULatencySet
[idx
] = OSNumber::withNumber(-1U, 32);
364 sCPULatencyHolder
[idx
] = OSNumber::withNumber(0ULL, 64);
365 assert(sCPULatencySet
[idx
] && sCPULatencyHolder
[idx
]);
368 gNotificationLock
= IORecursiveLockAlloc();
370 assert( gIOServicePlane
&& gIODeviceMemoryKey
371 && gIOInterruptControllersKey
&& gIOInterruptSpecifiersKey
372 && gIOResourcesKey
&& gNotifications
&& gNotificationLock
373 && gIOProviderClassKey
&& gIONameMatchKey
&& gIONameMatchedKey
374 && gIOMatchCategoryKey
&& gIODefaultMatchCategoryKey
375 && gIOPublishNotification
&& gIOMatchedNotification
376 && gIOTerminatedNotification
&& gIOServiceKey
377 && gIOConsoleUsersKey
&& gIOConsoleSessionUIDKey
378 && gIOConsoleSessionOnConsoleKey
&& gIOConsoleSessionSecureInputPIDKey
379 && gIOConsoleUsersSeedKey
&& gIOConsoleUsersSeedValue
);
381 gJobsLock
= IOLockAlloc();
382 gJobs
= OSOrderedSet::withCapacity( 10 );
384 gIOServiceBusyLock
= IOLockAlloc();
386 gIOConsoleUsersLock
= IOLockAlloc();
388 err
= semaphore_create(kernel_task
, &gJobsSemaphore
, SYNC_POLICY_FIFO
, 0);
390 gIOConsoleLockCallout
= thread_call_allocate(&IOService::consoleLockTimer
, NULL
);
392 IORegistryEntry::getRegistryRoot()->setProperty(gIOConsoleLockedKey
, kOSBooleanTrue
);
394 assert( gIOServiceBusyLock
&& gJobs
&& gJobsLock
&& gIOConsoleUsersLock
395 && gIOConsoleLockCallout
&& (err
== KERN_SUCCESS
) );
397 gIOResources
= IOResources::resources();
398 assert( gIOResources
);
400 gArbitrationLockQueueLock
= IOLockAlloc();
401 queue_init(&gArbitrationLockQueueActive
);
402 queue_init(&gArbitrationLockQueueWaiting
);
403 queue_init(&gArbitrationLockQueueFree
);
405 assert( gArbitrationLockQueueLock
);
407 gIOTerminatePhase2List
= OSArray::withCapacity( 2 );
408 gIOStopList
= OSArray::withCapacity( 16 );
409 gIOStopProviderList
= OSArray::withCapacity( 16 );
410 gIOFinalizeList
= OSArray::withCapacity( 16 );
411 assert( gIOTerminatePhase2List
&& gIOStopList
&& gIOStopProviderList
&& gIOFinalizeList
);
414 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
417 static UInt64
getDebugFlags( OSDictionary
* props
)
419 OSNumber
* debugProp
;
422 debugProp
= OSDynamicCast( OSNumber
,
423 props
->getObject( gIOKitDebugKey
));
425 debugFlags
= debugProp
->unsigned64BitValue();
427 debugFlags
= gIOKitDebug
;
429 return( debugFlags
);
433 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
435 // Probe a matched service and return an instance to be started.
436 // The default score is from the property table, & may be altered
437 // during probe to change the start order.
439 IOService
* IOService::probe( IOService
* provider
,
445 bool IOService::start( IOService
* provider
)
450 void IOService::stop( IOService
* provider
)
454 bool IOService::init( OSDictionary
* dictionary
)
458 ret
= super::init(dictionary
);
463 reserved
= IONew(ExpansionData
, 1);
470 bzero(reserved
, sizeof(*reserved
));
473 * TODO: Improve on this. Previous efforts to more lazily allocate this
474 * lock based on the presence of specifiers ran into issues as some
475 * platforms set up the specifiers after IOService initialization.
477 * We may be able to get away with a global lock, as this should only be
478 * contended by IOReporting clients and driver start/stop (unless a
479 * driver wants to remove/add handlers in the course of normal operation,
480 * which should be unlikely).
482 reserved
->interruptStatisticsLock
= IOLockAlloc();
484 if (!reserved
->interruptStatisticsLock
) {
493 bool IOService::init( IORegistryEntry
* from
,
494 const IORegistryPlane
* inPlane
)
498 ret
= super::init(from
, inPlane
);
503 reserved
= IONew(ExpansionData
, 1);
510 bzero(reserved
, sizeof(*reserved
));
513 * TODO: Improve on this. Previous efforts to more lazily allocate this
514 * lock based on the presence of specifiers ran into issues as some
515 * platforms set up the specifiers after IOService initialization.
517 * We may be able to get away with a global lock, as this should only be
518 * contended by IOReporting clients and driver start/stop (unless a
519 * driver wants to remove/add handlers in the course of normal operation,
520 * which should be unlikely).
522 reserved
->interruptStatisticsLock
= IOLockAlloc();
524 if (!reserved
->interruptStatisticsLock
) {
533 void IOService::free( void )
536 requireMaxBusStall(0);
537 requireMaxInterruptDelay(0);
538 if( getPropertyTable())
539 unregisterAllInterest();
543 if (reserved
->interruptStatisticsArray
) {
544 for (i
= 0; i
< reserved
->interruptStatisticsArrayCount
; i
++) {
545 if (reserved
->interruptStatisticsArray
[i
].reporter
)
546 reserved
->interruptStatisticsArray
[i
].reporter
->release();
549 IODelete(reserved
->interruptStatisticsArray
, IOInterruptAccountingReporter
, reserved
->interruptStatisticsArrayCount
);
552 if (reserved
->interruptStatisticsLock
)
553 IOLockFree(reserved
->interruptStatisticsLock
);
554 IODelete(reserved
, ExpansionData
, 1);
561 * Attach in service plane
563 bool IOService::attach( IOService
* provider
)
569 if( gIOKitDebug
& kIOLogAttach
)
570 LOG( "%s::attach(%s)\n", getName(),
571 provider
->getName());
573 provider
->lockForArbitration();
574 if( provider
->__state
[0] & kIOServiceInactiveState
)
577 ok
= attachToParent( provider
, gIOServicePlane
);
578 provider
->unlockForArbitration();
581 gIOServiceRoot
= this;
582 ok
= attachToParent( getRegistryRoot(), gIOServicePlane
);
585 if (ok
&& !__provider
) (void) getProvider();
590 IOService
* IOService::getServiceRoot( void )
592 return( gIOServiceRoot
);
595 void IOService::detach( IOService
* provider
)
597 IOService
* newProvider
= 0;
601 if( gIOKitDebug
& kIOLogAttach
)
602 LOG("%s::detach(%s)\n", getName(), provider
->getName());
604 lockForArbitration();
606 adjParent
= ((busy
= (__state
[1] & kIOServiceBusyStateMask
))
607 && (provider
== getProvider()));
609 detachFromParent( provider
, gIOServicePlane
);
612 newProvider
= getProvider();
613 if( busy
&& (__state
[1] & kIOServiceTermPhase3State
) && (0 == newProvider
))
614 _adjustBusy( -busy
);
617 if (kIOServiceInactiveState
& __state
[0]) {
618 getMetaClass()->removeInstance(this);
621 unlockForArbitration();
624 newProvider
->lockForArbitration();
625 newProvider
->_adjustBusy(1);
626 newProvider
->unlockForArbitration();
629 // check for last client detach from a terminated service
630 if( provider
->lockForArbitration( true ))
632 if (kIOServiceStartState
& __state
[1])
634 provider
->scheduleTerminatePhase2();
636 if( adjParent
) provider
->_adjustBusy( -1 );
637 if( (provider
->__state
[1] & kIOServiceTermPhase3State
)
638 && (0 == provider
->getClient())) {
639 provider
->scheduleFinalize();
641 provider
->unlockForArbitration();
646 * Register instance - publish it for matching
649 void IOService::registerService( IOOptionBits options
)
655 enum { kMaxPathLen
= 256 };
656 enum { kMaxChars
= 63 };
658 IORegistryEntry
* parent
= this;
659 IORegistryEntry
* root
= getRegistryRoot();
660 while( parent
&& (parent
!= root
))
661 parent
= parent
->getParentEntry( gIOServicePlane
);
663 if( parent
!= root
) {
664 IOLog("%s: not registry member at registerService()\n", getName());
668 // Allow the Platform Expert to adjust this node.
669 if( gIOPlatform
&& (!gIOPlatform
->platformAdjustService(this)))
672 if( (this != gIOResources
)
673 && (kIOLogRegister
& gIOKitDebug
)) {
675 pathBuf
= (char *) IOMalloc( kMaxPathLen
);
677 IOLog( "Registering: " );
680 if( pathBuf
&& getPath( pathBuf
, &len
, gIOServicePlane
)) {
683 if( len
> kMaxChars
) {
687 if( (skip
= strchr( path
, '/')))
693 IOLog( "%s\n", path
);
696 IOFree( pathBuf
, kMaxPathLen
);
699 startMatching( options
);
702 void IOService::startMatching( IOOptionBits options
)
704 IOService
* provider
;
707 bool needWake
= false;
712 lockForArbitration();
714 sync
= (options
& kIOServiceSynchronous
)
715 || ((provider
= getProvider())
716 && (provider
->__state
[1] & kIOServiceSynchronousState
));
718 if ( options
& kIOServiceAsynchronous
)
721 needConfig
= (0 == (__state
[1] & (kIOServiceNeedConfigState
| kIOServiceConfigState
)))
722 && (0 == (__state
[0] & kIOServiceInactiveState
));
724 __state
[1] |= kIOServiceNeedConfigState
;
726 // __state[0] &= ~kIOServiceInactiveState;
728 // if( sync) LOG("OSKernelStackRemaining = %08x @ %s\n",
729 // OSKernelStackRemaining(), getName());
732 needWake
= (0 != (kIOServiceSyncPubState
& __state
[1]));
736 __state
[1] |= kIOServiceSynchronousState
;
738 __state
[1] &= ~kIOServiceSynchronousState
;
740 if( needConfig
) prevBusy
= _adjustBusy( 1 );
742 unlockForArbitration();
747 IOLockLock( gIOServiceBusyLock
);
748 thread_wakeup( (event_t
) this/*&__state[1]*/ );
749 IOLockUnlock( gIOServiceBusyLock
);
751 } else if( !sync
|| (kIOServiceAsynchronous
& options
)) {
753 ok
= (0 != _IOServiceJob::startJob( this, kMatchNubJob
, options
));
757 if( (__state
[1] & kIOServiceNeedConfigState
))
758 doServiceMatch( options
);
760 lockForArbitration();
761 IOLockLock( gIOServiceBusyLock
);
763 waitAgain
= ((prevBusy
< (__state
[1] & kIOServiceBusyStateMask
))
764 && (0 == (__state
[0] & kIOServiceInactiveState
)));
767 __state
[1] |= kIOServiceSyncPubState
| kIOServiceBusyWaiterState
;
769 __state
[1] &= ~kIOServiceSyncPubState
;
771 unlockForArbitration();
774 assert_wait( (event_t
) this/*&__state[1]*/, THREAD_UNINT
);
776 IOLockUnlock( gIOServiceBusyLock
);
778 thread_block(THREAD_CONTINUE_NULL
);
780 } while( waitAgain
);
784 IOReturn
IOService::catalogNewDrivers( OSOrderedSet
* newTables
)
786 OSDictionary
* table
;
796 while( (table
= (OSDictionary
*) newTables
->getFirstObject())) {
799 set
= (OSSet
*) copyExistingServices( table
,
800 kIOServiceRegisteredState
,
801 kIOServiceExistingSet
);
806 count
+= set
->getCount();
809 allSet
->merge((const OSSet
*) set
);
817 if( getDebugFlags( table
) & kIOLogMatch
)
818 LOG("Matching service count = %ld\n", (long)count
);
820 newTables
->removeObject(table
);
824 while( (service
= (IOService
*) allSet
->getAnyObject())) {
825 service
->startMatching(kIOServiceAsynchronous
);
826 allSet
->removeObject(service
);
831 newTables
->release();
833 return( kIOReturnSuccess
);
836 _IOServiceJob
* _IOServiceJob::startJob( IOService
* nub
, int type
,
837 IOOptionBits options
)
841 job
= new _IOServiceJob
;
842 if( job
&& !job
->init()) {
850 job
->options
= options
;
851 nub
->retain(); // thread will release()
859 * Called on a registered service to see if it matches
863 bool IOService::matchPropertyTable( OSDictionary
* table
, SInt32
* score
)
865 return( matchPropertyTable(table
) );
868 bool IOService::matchPropertyTable( OSDictionary
* table
)
874 * Called on a matched service to allocate resources
875 * before first driver is attached.
878 IOReturn
IOService::getResources( void )
880 return( kIOReturnSuccess
);
884 * Client/provider accessors
887 IOService
* IOService::getProvider( void ) const
889 IOService
* self
= (IOService
*) this;
893 generation
= getGenerationCount();
894 if( __providerGeneration
== generation
)
895 return( __provider
);
897 parent
= (IOService
*) getParentEntry( gIOServicePlane
);
898 if( parent
== IORegistryEntry::getRegistryRoot())
899 /* root is not an IOService */
902 self
->__provider
= parent
;
904 // save the count from before call to getParentEntry()
905 self
->__providerGeneration
= generation
;
910 IOWorkLoop
* IOService::getWorkLoop() const
912 IOService
*provider
= getProvider();
915 return provider
->getWorkLoop();
920 OSIterator
* IOService::getProviderIterator( void ) const
922 return( getParentIterator( gIOServicePlane
));
925 IOService
* IOService::getClient( void ) const
927 return( (IOService
*) getChildEntry( gIOServicePlane
));
930 OSIterator
* IOService::getClientIterator( void ) const
932 return( getChildIterator( gIOServicePlane
));
935 OSIterator
* _IOOpenServiceIterator::iterator( OSIterator
* _iter
,
936 const IOService
* client
,
937 const IOService
* provider
)
939 _IOOpenServiceIterator
* inst
;
944 inst
= new _IOOpenServiceIterator
;
946 if( inst
&& !inst
->init()) {
952 inst
->client
= client
;
953 inst
->provider
= provider
;
959 void _IOOpenServiceIterator::free()
963 last
->unlockForArbitration();
967 OSObject
* _IOOpenServiceIterator::getNextObject()
972 last
->unlockForArbitration();
974 while( (next
= (IOService
*) iter
->getNextObject())) {
976 next
->lockForArbitration();
977 if( (client
&& (next
->isOpen( client
)))
978 || (provider
&& (provider
->isOpen( next
))) )
980 next
->unlockForArbitration();
988 bool _IOOpenServiceIterator::isValid()
990 return( iter
->isValid() );
993 void _IOOpenServiceIterator::reset()
996 last
->unlockForArbitration();
1002 OSIterator
* IOService::getOpenProviderIterator( void ) const
1004 return( _IOOpenServiceIterator::iterator( getProviderIterator(), this, 0 ));
1007 OSIterator
* IOService::getOpenClientIterator( void ) const
1009 return( _IOOpenServiceIterator::iterator( getClientIterator(), 0, this ));
1013 IOReturn
IOService::callPlatformFunction( const OSSymbol
* functionName
,
1014 bool waitForFunction
,
1015 void *param1
, void *param2
,
1016 void *param3
, void *param4
)
1018 IOReturn result
= kIOReturnUnsupported
;
1019 IOService
*provider
;
1021 if (gIOPlatformFunctionHandlerSet
== functionName
)
1023 #if defined(__i386__) || defined(__x86_64__)
1024 const OSSymbol
* functionHandlerName
= (const OSSymbol
*) param1
;
1025 IOService
* target
= (IOService
*) param2
;
1026 bool enable
= (param3
!= 0);
1028 if (sCPULatencyFunctionName
[kCpuDelayBusStall
] == functionHandlerName
)
1029 result
= setLatencyHandler(kCpuDelayBusStall
, target
, enable
);
1030 else if (sCPULatencyFunctionName
[kCpuDelayInterrupt
] == param1
)
1031 result
= setLatencyHandler(kCpuDelayInterrupt
, target
, enable
);
1032 #endif /* defined(__i386__) || defined(__x86_64__) */
1035 if ((kIOReturnUnsupported
== result
) && (provider
= getProvider())) {
1036 result
= provider
->callPlatformFunction(functionName
, waitForFunction
,
1037 param1
, param2
, param3
, param4
);
1043 IOReturn
IOService::callPlatformFunction( const char * functionName
,
1044 bool waitForFunction
,
1045 void *param1
, void *param2
,
1046 void *param3
, void *param4
)
1048 IOReturn result
= kIOReturnNoMemory
;
1049 const OSSymbol
*functionSymbol
= OSSymbol::withCString(functionName
);
1051 if (functionSymbol
!= 0) {
1052 result
= callPlatformFunction(functionSymbol
, waitForFunction
,
1053 param1
, param2
, param3
, param4
);
1054 functionSymbol
->release();
1062 * Accessors for global services
1065 IOPlatformExpert
* IOService::getPlatform( void )
1067 return( gIOPlatform
);
1070 class IOPMrootDomain
* IOService::getPMRootDomain( void )
1072 return( gIOPMRootDomain
);
1075 IOService
* IOService::getResourceService( void )
1077 return( gIOResources
);
1080 void IOService::setPlatform( IOPlatformExpert
* platform
)
1082 gIOPlatform
= platform
;
1083 gIOResources
->attachToParent( gIOServiceRoot
, gIOServicePlane
);
1085 #if defined(__i386__) || defined(__x86_64__)
1087 static const char * keys
[kCpuNumDelayTypes
] = {
1088 kIOPlatformMaxBusDelay
, kIOPlatformMaxInterruptDelay
};
1089 const OSObject
* objs
[2];
1093 for (idx
= 0; idx
< kCpuNumDelayTypes
; idx
++)
1095 objs
[0] = sCPULatencySet
[idx
];
1096 objs
[1] = sCPULatencyHolder
[idx
];
1097 array
= OSArray::withObjects(objs
, 2);
1099 platform
->setProperty(keys
[idx
], array
);
1102 #endif /* defined(__i386__) || defined(__x86_64__) */
1105 void IOService::setPMRootDomain( class IOPMrootDomain
* rootDomain
)
1107 gIOPMRootDomain
= rootDomain
;
1108 publishResource("IOKit");
1115 bool IOService::lockForArbitration( bool isSuccessRequired
)
1119 ArbitrationLockQueueElement
* element
;
1120 ArbitrationLockQueueElement
* active
;
1121 ArbitrationLockQueueElement
* waiting
;
1123 enum { kPutOnFreeQueue
, kPutOnActiveQueue
, kPutOnWaitingQueue
} action
;
1125 // lock global access
1126 IOTakeLock( gArbitrationLockQueueLock
);
1128 // obtain an unused queue element
1129 if( !queue_empty( &gArbitrationLockQueueFree
)) {
1130 queue_remove_first( &gArbitrationLockQueueFree
,
1132 ArbitrationLockQueueElement
*,
1135 element
= IONew( ArbitrationLockQueueElement
, 1 );
1139 // prepare the queue element
1140 element
->thread
= IOThreadSelf();
1141 element
->service
= this;
1143 element
->required
= isSuccessRequired
;
1144 element
->aborted
= false;
1146 // determine whether this object is already locked (ie. on active queue)
1148 queue_iterate( &gArbitrationLockQueueActive
,
1150 ArbitrationLockQueueElement
*,
1153 if( active
->service
== element
->service
) {
1159 if( found
) { // this object is already locked
1161 // determine whether it is the same or a different thread trying to lock
1162 if( active
->thread
!= element
->thread
) { // it is a different thread
1164 ArbitrationLockQueueElement
* victim
= 0;
1166 // before placing this new thread on the waiting queue, we look for
1167 // a deadlock cycle...
1170 // determine whether the active thread holding the object we
1171 // want is waiting for another object to be unlocked
1173 queue_iterate( &gArbitrationLockQueueWaiting
,
1175 ArbitrationLockQueueElement
*,
1178 if( waiting
->thread
== active
->thread
) {
1179 assert( false == waiting
->aborted
);
1185 if( found
) { // yes, active thread waiting for another object
1187 // this may be a candidate for rejection if the required
1188 // flag is not set, should we detect a deadlock later on
1189 if( false == waiting
->required
)
1192 // find the thread that is holding this other object, that
1193 // is blocking the active thread from proceeding (fun :-)
1195 queue_iterate( &gArbitrationLockQueueActive
,
1196 active
, // (reuse active queue element)
1197 ArbitrationLockQueueElement
*,
1200 if( active
->service
== waiting
->service
) {
1206 // someone must be holding it or it wouldn't be waiting
1209 if( active
->thread
== element
->thread
) {
1211 // doh, it's waiting for the thread that originated
1212 // this whole lock (ie. current thread) -> deadlock
1213 if( false == element
->required
) { // willing to fail?
1215 // the originating thread doesn't have the required
1216 // flag, so it can fail
1217 success
= false; // (fail originating lock request)
1218 break; // (out of while)
1220 } else { // originating thread is not willing to fail
1222 // see if we came across a waiting thread that did
1223 // not have the 'required' flag set: we'll fail it
1226 // we do have a willing victim, fail it's lock
1227 victim
->aborted
= true;
1229 // take the victim off the waiting queue
1230 queue_remove( &gArbitrationLockQueueWaiting
,
1232 ArbitrationLockQueueElement
*,
1236 IOLockWakeup( gArbitrationLockQueueLock
,
1238 /* one thread */ true );
1240 // allow this thread to proceed (ie. wait)
1241 success
= true; // (put request on wait queue)
1242 break; // (out of while)
1245 // all the waiting threads we came across in
1246 // finding this loop had the 'required' flag
1247 // set, so we've got a deadlock we can't avoid
1248 panic("I/O Kit: Unrecoverable deadlock.");
1252 // repeat while loop, redefining active thread to be the
1253 // thread holding "this other object" (see above), and
1254 // looking for threads waiting on it; note the active
1255 // variable points to "this other object" already... so
1256 // there nothing to do in this else clause.
1258 } else { // no, active thread is not waiting for another object
1260 success
= true; // (put request on wait queue)
1261 break; // (out of while)
1265 if( success
) { // put the request on the waiting queue?
1266 kern_return_t wait_result
;
1268 // place this thread on the waiting queue and put it to sleep;
1269 // we place it at the tail of the queue...
1270 queue_enter( &gArbitrationLockQueueWaiting
,
1272 ArbitrationLockQueueElement
*,
1275 // declare that this thread will wait for a given event
1276 restart_sleep
: wait_result
= assert_wait( element
,
1277 element
->required
? THREAD_UNINT
1278 : THREAD_INTERRUPTIBLE
);
1280 // unlock global access
1281 IOUnlock( gArbitrationLockQueueLock
);
1283 // put thread to sleep, waiting for our event to fire...
1284 if (wait_result
== THREAD_WAITING
)
1285 wait_result
= thread_block(THREAD_CONTINUE_NULL
);
1288 // ...and we've been woken up; we might be in one of two states:
1289 // (a) we've been aborted and our queue element is not on
1290 // any of the three queues, but is floating around
1291 // (b) we're allowed to proceed with the lock and we have
1292 // already been moved from the waiting queue to the
1294 // ...plus a 3rd state, should the thread have been interrupted:
1295 // (c) we're still on the waiting queue
1297 // determine whether we were interrupted out of our sleep
1298 if( THREAD_INTERRUPTED
== wait_result
) {
1300 // re-lock global access
1301 IOTakeLock( gArbitrationLockQueueLock
);
1303 // determine whether we're still on the waiting queue
1305 queue_iterate( &gArbitrationLockQueueWaiting
,
1306 waiting
, // (reuse waiting queue element)
1307 ArbitrationLockQueueElement
*,
1310 if( waiting
== element
) {
1316 if( found
) { // yes, we're still on the waiting queue
1318 // determine whether we're willing to fail
1319 if( false == element
->required
) {
1321 // mark us as aborted
1322 element
->aborted
= true;
1324 // take us off the waiting queue
1325 queue_remove( &gArbitrationLockQueueWaiting
,
1327 ArbitrationLockQueueElement
*,
1329 } else { // we are not willing to fail
1331 // ignore interruption, go back to sleep
1336 // unlock global access
1337 IOUnlock( gArbitrationLockQueueLock
);
1339 // proceed as though this were a normal wake up
1340 wait_result
= THREAD_AWAKENED
;
1343 assert( THREAD_AWAKENED
== wait_result
);
1345 // determine whether we've been aborted while we were asleep
1346 if( element
->aborted
) {
1347 assert( false == element
->required
);
1349 // re-lock global access
1350 IOTakeLock( gArbitrationLockQueueLock
);
1352 action
= kPutOnFreeQueue
;
1354 } else { // we weren't aborted, so we must be ready to go :-)
1356 // we've already been moved from waiting to active queue
1360 } else { // the lock request is to be failed
1362 // return unused queue element to queue
1363 action
= kPutOnFreeQueue
;
1365 } else { // it is the same thread, recursive access is allowed
1367 // add one level of recursion
1370 // return unused queue element to queue
1371 action
= kPutOnFreeQueue
;
1374 } else { // this object is not already locked, so let this thread through
1375 action
= kPutOnActiveQueue
;
1379 // put the new element on a queue
1380 if( kPutOnActiveQueue
== action
) {
1381 queue_enter( &gArbitrationLockQueueActive
,
1383 ArbitrationLockQueueElement
*,
1385 } else if( kPutOnFreeQueue
== action
) {
1386 queue_enter( &gArbitrationLockQueueFree
,
1388 ArbitrationLockQueueElement
*,
1391 assert( 0 ); // kPutOnWaitingQueue never occurs, handled specially above
1394 // unlock global access
1395 IOUnlock( gArbitrationLockQueueLock
);
1400 void IOService::unlockForArbitration( void )
1403 ArbitrationLockQueueElement
* element
;
1405 // lock global access
1406 IOTakeLock( gArbitrationLockQueueLock
);
1408 // find the lock element for this object (ie. on active queue)
1410 queue_iterate( &gArbitrationLockQueueActive
,
1412 ArbitrationLockQueueElement
*,
1415 if( element
->service
== this ) {
1423 // determine whether the lock has been taken recursively
1424 if( element
->count
> 1 ) {
1425 // undo one level of recursion
1430 // remove it from the active queue
1431 queue_remove( &gArbitrationLockQueueActive
,
1433 ArbitrationLockQueueElement
*,
1436 // put it on the free queue
1437 queue_enter( &gArbitrationLockQueueFree
,
1439 ArbitrationLockQueueElement
*,
1442 // determine whether a thread is waiting for object (head to tail scan)
1444 queue_iterate( &gArbitrationLockQueueWaiting
,
1446 ArbitrationLockQueueElement
*,
1449 if( element
->service
== this ) {
1455 if ( found
) { // we found an interested thread on waiting queue
1457 // remove it from the waiting queue
1458 queue_remove( &gArbitrationLockQueueWaiting
,
1460 ArbitrationLockQueueElement
*,
1463 // put it on the active queue
1464 queue_enter( &gArbitrationLockQueueActive
,
1466 ArbitrationLockQueueElement
*,
1469 // wake the waiting thread
1470 IOLockWakeup( gArbitrationLockQueueLock
,
1472 /* one thread */ true );
1476 // unlock global access
1477 IOUnlock( gArbitrationLockQueueLock
);
1480 void IOService::applyToProviders( IOServiceApplierFunction applier
,
1483 applyToParents( (IORegistryEntryApplierFunction
) applier
,
1484 context
, gIOServicePlane
);
1487 void IOService::applyToClients( IOServiceApplierFunction applier
,
1490 applyToChildren( (IORegistryEntryApplierFunction
) applier
,
1491 context
, gIOServicePlane
);
1500 // send a message to a client or interested party of this service
1501 IOReturn
IOService::messageClient( UInt32 type
, OSObject
* client
,
1502 void * argument
, vm_size_t argSize
)
1505 IOService
* service
;
1506 _IOServiceInterestNotifier
* notify
;
1508 if( (service
= OSDynamicCast( IOService
, client
)))
1509 ret
= service
->message( type
, this, argument
);
1511 else if( (notify
= OSDynamicCast( _IOServiceInterestNotifier
, client
))) {
1513 _IOServiceNotifierInvocation invocation
;
1516 invocation
.thread
= current_thread();
1519 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
1522 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
1523 _IOServiceNotifierInvocation
*, link
);
1529 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
,
1530 type
, this, argument
, argSize
);
1533 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
1534 _IOServiceNotifierInvocation
*, link
);
1535 if( kIOServiceNotifyWaiter
& notify
->state
) {
1536 notify
->state
&= ~kIOServiceNotifyWaiter
;
1537 WAKEUPNOTIFY( notify
);
1542 ret
= kIOReturnSuccess
;
1545 ret
= kIOReturnBadArgument
;
1551 applyToInterestNotifiers(const IORegistryEntry
*target
,
1552 const OSSymbol
* typeOfInterest
,
1553 OSObjectApplierFunction applier
,
1556 OSArray
* copyArray
= 0;
1560 IOCommand
*notifyList
=
1561 OSDynamicCast( IOCommand
, target
->getProperty( typeOfInterest
));
1564 copyArray
= OSArray::withCapacity(1);
1566 // iterate over queue, entry is set to each element in the list
1567 iterqueue(¬ifyList
->fCommandChain
, entry
) {
1568 _IOServiceInterestNotifier
* notify
;
1570 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1571 copyArray
->setObject(notify
);
1580 for( index
= 0; (next
= copyArray
->getObject( index
)); index
++)
1581 (*applier
)(next
, context
);
1582 copyArray
->release();
1586 void IOService::applyToInterested( const OSSymbol
* typeOfInterest
,
1587 OSObjectApplierFunction applier
,
1590 if (gIOGeneralInterest
== typeOfInterest
)
1591 applyToClients( (IOServiceApplierFunction
) applier
, context
);
1592 applyToInterestNotifiers(this, typeOfInterest
, applier
, context
);
1595 struct MessageClientsContext
{
1596 IOService
* service
;
1603 static void messageClientsApplier( OSObject
* object
, void * ctx
)
1606 MessageClientsContext
* context
= (MessageClientsContext
*) ctx
;
1608 ret
= context
->service
->messageClient( context
->type
,
1609 object
, context
->argument
, context
->argSize
);
1610 if( kIOReturnSuccess
!= ret
)
1614 // send a message to all clients
1615 IOReturn
IOService::messageClients( UInt32 type
,
1616 void * argument
, vm_size_t argSize
)
1618 MessageClientsContext context
;
1620 context
.service
= this;
1621 context
.type
= type
;
1622 context
.argument
= argument
;
1623 context
.argSize
= argSize
;
1624 context
.ret
= kIOReturnSuccess
;
1626 applyToInterested( gIOGeneralInterest
,
1627 &messageClientsApplier
, &context
);
1629 return( context
.ret
);
1632 IOReturn
IOService::acknowledgeNotification( IONotificationRef notification
,
1633 IOOptionBits response
)
1635 return( kIOReturnUnsupported
);
1638 IONotifier
* IOService::registerInterest( const OSSymbol
* typeOfInterest
,
1639 IOServiceInterestHandler handler
, void * target
, void * ref
)
1641 _IOServiceInterestNotifier
* notify
= 0;
1642 IOReturn rc
= kIOReturnError
;
1644 notify
= new _IOServiceInterestNotifier
;
1645 if (!notify
) return NULL
;
1647 if(notify
->init()) {
1648 rc
= registerInterestForNotifer(notify
, typeOfInterest
,
1649 handler
, target
, ref
);
1652 if (rc
!= kIOReturnSuccess
) {
1660 IOReturn
IOService::registerInterestForNotifer( IONotifier
*svcNotify
, const OSSymbol
* typeOfInterest
,
1661 IOServiceInterestHandler handler
, void * target
, void * ref
)
1663 IOReturn rc
= kIOReturnSuccess
;
1664 _IOServiceInterestNotifier
*notify
= 0;
1666 if( (typeOfInterest
!= gIOGeneralInterest
)
1667 && (typeOfInterest
!= gIOBusyInterest
)
1668 && (typeOfInterest
!= gIOAppPowerStateInterest
)
1669 && (typeOfInterest
!= gIOConsoleSecurityInterest
)
1670 && (typeOfInterest
!= gIOPriorityPowerStateInterest
))
1671 return( kIOReturnBadArgument
);
1673 if (!svcNotify
|| !(notify
= OSDynamicCast(_IOServiceInterestNotifier
, svcNotify
)))
1674 return( kIOReturnBadArgument
);
1676 lockForArbitration();
1677 if( 0 == (__state
[0] & kIOServiceInactiveState
)) {
1679 notify
->handler
= handler
;
1680 notify
->target
= target
;
1682 notify
->state
= kIOServiceNotifyEnable
;
1688 // Get the head of the notifier linked list
1689 IOCommand
*notifyList
= (IOCommand
*) getProperty( typeOfInterest
);
1690 if (!notifyList
|| !OSDynamicCast(IOCommand
, notifyList
)) {
1691 notifyList
= OSTypeAlloc(IOCommand
);
1694 setProperty( typeOfInterest
, notifyList
);
1695 notifyList
->release();
1700 enqueue(¬ifyList
->fCommandChain
, ¬ify
->chain
);
1701 notify
->retain(); // ref'ed while in list
1707 rc
= kIOReturnNotReady
;
1709 unlockForArbitration();
1714 static void cleanInterestList( OSObject
* head
)
1716 IOCommand
*notifyHead
= OSDynamicCast(IOCommand
, head
);
1721 while ( queue_entry_t entry
= dequeue(¬ifyHead
->fCommandChain
) ) {
1722 queue_next(entry
) = queue_prev(entry
) = 0;
1724 _IOServiceInterestNotifier
* notify
;
1726 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1732 void IOService::unregisterAllInterest( void )
1734 cleanInterestList( getProperty( gIOGeneralInterest
));
1735 cleanInterestList( getProperty( gIOBusyInterest
));
1736 cleanInterestList( getProperty( gIOAppPowerStateInterest
));
1737 cleanInterestList( getProperty( gIOPriorityPowerStateInterest
));
1738 cleanInterestList( getProperty( gIOConsoleSecurityInterest
));
1742 * _IOServiceInterestNotifier
1745 // wait for all threads, other than the current one,
1746 // to exit the handler
1748 void _IOServiceInterestNotifier::wait()
1750 _IOServiceNotifierInvocation
* next
;
1755 queue_iterate( &handlerInvocations
, next
,
1756 _IOServiceNotifierInvocation
*, link
) {
1757 if( next
->thread
!= current_thread() ) {
1763 state
|= kIOServiceNotifyWaiter
;
1770 void _IOServiceInterestNotifier::free()
1772 assert( queue_empty( &handlerInvocations
));
1776 void _IOServiceInterestNotifier::remove()
1780 if( queue_next( &chain
)) {
1782 queue_next( &chain
) = queue_prev( &chain
) = 0;
1786 state
&= ~kIOServiceNotifyEnable
;
1795 bool _IOServiceInterestNotifier::disable()
1801 ret
= (0 != (kIOServiceNotifyEnable
& state
));
1802 state
&= ~kIOServiceNotifyEnable
;
1811 void _IOServiceInterestNotifier::enable( bool was
)
1815 state
|= kIOServiceNotifyEnable
;
1817 state
&= ~kIOServiceNotifyEnable
;
1821 bool _IOServiceInterestNotifier::init()
1823 queue_init( &handlerInvocations
);
1824 return (OSObject::init());
1826 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1832 #define tailQ(o) setObject(o)
1833 #define headQ(o) setObject(0, o)
1834 #define TLOG(fmt, args...) { if(kIOLogYield & gIOKitDebug) { IOLog("[%llx] ", thread_tid(current_thread())); IOLog(fmt, ## args); }}
1836 static void _workLoopAction( IOWorkLoop::Action action
,
1837 IOService
* service
,
1838 void * p0
= 0, void * p1
= 0,
1839 void * p2
= 0, void * p3
= 0 )
1843 if( (wl
= service
->getWorkLoop())) {
1845 wl
->runAction( action
, service
, p0
, p1
, p2
, p3
);
1848 (*action
)( service
, p0
, p1
, p2
, p3
);
1851 bool IOService::requestTerminate( IOService
* provider
, IOOptionBits options
)
1855 // if its our only provider
1856 ok
= isParent( provider
, gIOServicePlane
, true);
1860 provider
->terminateClient( this, options
| kIOServiceRecursing
);
1861 ok
= (0 != (__state
[1] & kIOServiceRecursing
));
1868 bool IOService::terminatePhase1( IOOptionBits options
)
1873 OSArray
* makeInactive
;
1874 int waitResult
= THREAD_AWAKENED
;
1878 bool startPhase2
= false;
1880 TLOG("%s[0x%qx]::terminatePhase1(%08llx)\n", getName(), getRegistryEntryID(), (long long)options
);
1882 uint64_t regID
= getRegistryEntryID();
1884 IOSERVICE_TERMINATE_PHASE1
,
1886 (uintptr_t) (regID
>> 32),
1888 (uintptr_t) options
);
1891 if( options
& kIOServiceRecursing
) {
1892 lockForArbitration();
1893 __state
[0] |= kIOServiceInactiveState
;
1894 __state
[1] |= kIOServiceRecursing
;
1895 unlockForArbitration();
1901 makeInactive
= OSArray::withCapacity( 16 );
1910 didInactive
= victim
->lockForArbitration( true );
1912 didInactive
= (0 == (victim
->__state
[0] & kIOServiceInactiveState
))
1913 || (victim
->__state
[1] & kIOServiceRecursing
);
1915 victim
->__state
[0] |= kIOServiceInactiveState
;
1916 victim
->__state
[0] &= ~(kIOServiceRegisteredState
| kIOServiceMatchedState
1917 | kIOServiceFirstPublishState
| kIOServiceFirstMatchState
);
1918 victim
->__state
[1] &= ~kIOServiceRecursing
;
1922 victim
->__state
[1] |= kIOServiceTermPhase1State
;
1923 if (kIOServiceTerminateNeedWillTerminate
& options
)
1925 victim
->__state
[1] |= kIOServiceNeedWillTerminate
;
1929 victim
->_adjustBusy( 1 );
1931 } else if (victim
!= this) do {
1933 IOLockLock(gIOServiceBusyLock
);
1934 wait
= (victim
->__state
[1] & kIOServiceTermPhase1State
);
1936 TLOG("%s[0x%qx]::waitPhase1(%s[0x%qx])\n",
1937 getName(), getRegistryEntryID(), victim
->getName(), victim
->getRegistryEntryID());
1938 victim
->__state
[1] |= kIOServiceTerm1WaiterState
;
1939 victim
->unlockForArbitration();
1940 assert_wait((event_t
)&victim
->__state
[1], THREAD_UNINT
);
1942 IOLockUnlock(gIOServiceBusyLock
);
1944 waitResult
= thread_block(THREAD_CONTINUE_NULL
);
1945 TLOG("%s[0x%qx]::did waitPhase1(%s[0x%qx])\n",
1946 getName(), getRegistryEntryID(), victim
->getName(), victim
->getRegistryEntryID());
1947 victim
->lockForArbitration();
1949 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
1951 victim
->unlockForArbitration();
1954 startPhase2
= didInactive
;
1957 victim
->deliverNotification( gIOTerminatedNotification
, 0, 0xffffffff );
1958 IOUserClient::destroyUserReferences( victim
);
1960 iter
= victim
->getClientIterator();
1962 while( (client
= (IOService
*) iter
->getNextObject())) {
1963 TLOG("%s[0x%qx]::requestTerminate(%s[0x%qx], %08llx)\n",
1964 client
->getName(), client
->getRegistryEntryID(),
1965 victim
->getName(), victim
->getRegistryEntryID(), (long long)options
);
1966 ok
= client
->requestTerminate( victim
, options
);
1967 TLOG("%s[0x%qx]::requestTerminate(%s[0x%qx], ok = %d)\n",
1968 client
->getName(), client
->getRegistryEntryID(),
1969 victim
->getName(), victim
->getRegistryEntryID(), ok
);
1971 uint64_t regID1
= client
->getRegistryEntryID();
1972 uint64_t regID2
= victim
->getRegistryEntryID();
1974 (ok
? IOSERVICE_TERMINATE_REQUEST_OK
1975 : IOSERVICE_TERMINATE_REQUEST_FAIL
),
1977 (uintptr_t) (regID1
>> 32),
1979 (uintptr_t) (regID2
>> 32));
1982 makeInactive
->setObject( client
);
1988 victim
= (IOService
*) makeInactive
->getObject(0);
1991 makeInactive
->removeObject(0);
1995 makeInactive
->release();
1999 lockForArbitration();
2000 __state
[1] &= ~kIOServiceTermPhase1State
;
2001 if (kIOServiceTerm1WaiterState
& __state
[1])
2003 __state
[1] &= ~kIOServiceTerm1WaiterState
;
2004 TLOG("%s[0x%qx]::wakePhase1\n", getName(), getRegistryEntryID());
2005 IOLockLock( gIOServiceBusyLock
);
2006 thread_wakeup( (event_t
) &__state
[1]);
2007 IOLockUnlock( gIOServiceBusyLock
);
2009 unlockForArbitration();
2010 scheduleTerminatePhase2( options
);
2016 void IOService::setTerminateDefer(IOService
* provider
, bool defer
)
2018 lockForArbitration();
2019 if (defer
) __state
[1] |= kIOServiceStartState
;
2020 else __state
[1] &= ~kIOServiceStartState
;
2021 unlockForArbitration();
2023 if (provider
&& !defer
)
2025 provider
->lockForArbitration();
2026 provider
->scheduleTerminatePhase2();
2027 provider
->unlockForArbitration();
2031 // call with lockForArbitration
2032 void IOService::scheduleTerminatePhase2( IOOptionBits options
)
2034 AbsoluteTime deadline
;
2035 int waitResult
= THREAD_AWAKENED
;
2036 bool wait
, haveDeadline
= false;
2038 if (!(__state
[0] & kIOServiceInactiveState
)
2039 || (__state
[1] & kIOServiceTermPhase1State
)) return;
2041 options
|= kIOServiceRequired
;
2045 IOLockLock( gJobsLock
);
2047 if( (options
& kIOServiceSynchronous
)
2048 && (current_thread() != gIOTerminateThread
)) {
2051 wait
= (gIOTerminateThread
!= 0);
2053 // wait to become the terminate thread
2054 IOLockSleep( gJobsLock
, &gIOTerminateThread
, THREAD_UNINT
);
2058 gIOTerminateThread
= current_thread();
2059 gIOTerminatePhase2List
->setObject( this );
2063 while( gIOTerminateWork
)
2064 terminateWorker( options
);
2065 wait
= (0 != (__state
[1] & kIOServiceBusyStateMask
));
2067 // wait for the victim to go non-busy
2068 if( !haveDeadline
) {
2069 clock_interval_to_deadline( 15, kSecondScale
, &deadline
);
2070 haveDeadline
= true;
2072 waitResult
= IOLockSleepDeadline( gJobsLock
, &gIOTerminateWork
,
2073 deadline
, THREAD_UNINT
);
2074 if( waitResult
== THREAD_TIMED_OUT
) {
2075 IOLog("%s[0x%qx]::terminate(kIOServiceSynchronous) timeout\n", getName(), getRegistryEntryID());
2078 } while(gIOTerminateWork
|| (wait
&& (waitResult
!= THREAD_TIMED_OUT
)));
2080 gIOTerminateThread
= 0;
2081 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
2084 // ! kIOServiceSynchronous
2086 gIOTerminatePhase2List
->setObject( this );
2087 if( 0 == gIOTerminateWork
++) {
2088 if( !gIOTerminateThread
)
2089 kernel_thread_start(&terminateThread
, (void *)(uintptr_t) options
, &gIOTerminateThread
);
2091 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
2095 IOLockUnlock( gJobsLock
);
2100 void IOService::terminateThread( void * arg
, wait_result_t waitResult
)
2102 IOLockLock( gJobsLock
);
2104 while (gIOTerminateWork
)
2105 terminateWorker( (uintptr_t) arg
);
2107 thread_deallocate(gIOTerminateThread
);
2108 gIOTerminateThread
= 0;
2109 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
2111 IOLockUnlock( gJobsLock
);
2114 void IOService::scheduleStop( IOService
* provider
)
2116 uint64_t regID1
= getRegistryEntryID();
2117 uint64_t regID2
= provider
->getRegistryEntryID();
2119 TLOG("%s[0x%qx]::scheduleStop(%s[0x%qx])\n", getName(), regID1
, provider
->getName(), regID2
);
2121 IOSERVICE_TERMINATE_SCHEDULE_STOP
,
2123 (uintptr_t) (regID1
>> 32),
2125 (uintptr_t) (regID2
>> 32));
2127 IOLockLock( gJobsLock
);
2128 gIOStopList
->tailQ( this );
2129 gIOStopProviderList
->tailQ( provider
);
2131 if( 0 == gIOTerminateWork
++) {
2132 if( !gIOTerminateThread
)
2133 kernel_thread_start(&terminateThread
, (void *) 0, &gIOTerminateThread
);
2135 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
2138 IOLockUnlock( gJobsLock
);
2141 void IOService::scheduleFinalize( void )
2143 uint64_t regID1
= getRegistryEntryID();
2145 TLOG("%s[0x%qx]::scheduleFinalize\n", getName(), regID1
);
2147 IOSERVICE_TERMINATE_SCHEDULE_FINALIZE
,
2149 (uintptr_t) (regID1
>> 32),
2152 IOLockLock( gJobsLock
);
2153 gIOFinalizeList
->tailQ( this );
2155 if( 0 == gIOTerminateWork
++) {
2156 if( !gIOTerminateThread
)
2157 kernel_thread_start(&terminateThread
, (void *) 0, &gIOTerminateThread
);
2159 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
2162 IOLockUnlock( gJobsLock
);
2165 bool IOService::willTerminate( IOService
* provider
, IOOptionBits options
)
2170 bool IOService::didTerminate( IOService
* provider
, IOOptionBits options
, bool * defer
)
2172 if( false == *defer
) {
2174 if( lockForArbitration( true )) {
2175 if( false == provider
->handleIsOpen( this ))
2176 scheduleStop( provider
);
2179 message( kIOMessageServiceIsRequestingClose
, provider
, (void *)(uintptr_t) options
);
2180 if( false == provider
->handleIsOpen( this ))
2181 scheduleStop( provider
);
2184 unlockForArbitration();
2191 void IOService::actionWillTerminate( IOService
* victim
, IOOptionBits options
,
2192 OSArray
* doPhase2List
,
2193 void *unused2 __unused
,
2194 void *unused3 __unused
)
2199 uint64_t regID1
, regID2
= victim
->getRegistryEntryID();
2201 iter
= victim
->getClientIterator();
2203 while( (client
= (IOService
*) iter
->getNextObject())) {
2205 regID1
= client
->getRegistryEntryID();
2206 TLOG("%s[0x%qx]::willTerminate(%s[0x%qx], %08llx)\n",
2207 client
->getName(), regID1
,
2208 victim
->getName(), regID2
, (long long)options
);
2210 IOSERVICE_TERMINATE_WILL
,
2212 (uintptr_t) (regID1
>> 32),
2214 (uintptr_t) (regID2
>> 32));
2216 ok
= client
->willTerminate( victim
, options
);
2217 doPhase2List
->tailQ( client
);
2223 void IOService::actionDidTerminate( IOService
* victim
, IOOptionBits options
,
2224 void *unused1 __unused
, void *unused2 __unused
,
2225 void *unused3 __unused
)
2230 uint64_t regID1
, regID2
= victim
->getRegistryEntryID();
2232 victim
->messageClients( kIOMessageServiceIsTerminated
, (void *)(uintptr_t) options
);
2234 iter
= victim
->getClientIterator();
2236 while( (client
= (IOService
*) iter
->getNextObject())) {
2238 regID1
= client
->getRegistryEntryID();
2239 TLOG("%s[0x%qx]::didTerminate(%s[0x%qx], %08llx)\n",
2240 client
->getName(), regID1
,
2241 victim
->getName(), regID2
, (long long)options
);
2242 client
->didTerminate( victim
, options
, &defer
);
2245 (defer
? IOSERVICE_TERMINATE_DID_DEFER
2246 : IOSERVICE_TERMINATE_DID
),
2248 (uintptr_t) (regID1
>> 32),
2250 (uintptr_t) (regID2
>> 32));
2252 TLOG("%s[0x%qx]::didTerminate(%s[0x%qx], defer %d)\n",
2253 client
->getName(), regID1
,
2254 victim
->getName(), regID2
, defer
);
2261 void IOService::actionWillStop( IOService
* victim
, IOOptionBits options
,
2262 void *unused1 __unused
, void *unused2 __unused
,
2263 void *unused3 __unused
)
2266 IOService
* provider
;
2268 uint64_t regID1
, regID2
= victim
->getRegistryEntryID();
2270 iter
= victim
->getProviderIterator();
2272 while( (provider
= (IOService
*) iter
->getNextObject())) {
2274 regID1
= provider
->getRegistryEntryID();
2275 TLOG("%s[0x%qx]::willTerminate(%s[0x%qx], %08llx)\n",
2276 victim
->getName(), regID2
,
2277 provider
->getName(), regID1
, (long long)options
);
2279 IOSERVICE_TERMINATE_WILL
,
2281 (uintptr_t) (regID2
>> 32),
2283 (uintptr_t) (regID1
>> 32));
2285 ok
= victim
->willTerminate( provider
, options
);
2291 void IOService::actionDidStop( IOService
* victim
, IOOptionBits options
,
2292 void *unused1 __unused
, void *unused2 __unused
,
2293 void *unused3 __unused
)
2296 IOService
* provider
;
2298 uint64_t regID1
, regID2
= victim
->getRegistryEntryID();
2300 iter
= victim
->getProviderIterator();
2302 while( (provider
= (IOService
*) iter
->getNextObject())) {
2304 regID1
= provider
->getRegistryEntryID();
2305 TLOG("%s[0x%qx]::didTerminate(%s[0x%qx], %08llx)\n",
2306 victim
->getName(), regID2
,
2307 provider
->getName(), regID1
, (long long)options
);
2308 victim
->didTerminate( provider
, options
, &defer
);
2311 (defer
? IOSERVICE_TERMINATE_DID_DEFER
2312 : IOSERVICE_TERMINATE_DID
),
2314 (uintptr_t) (regID2
>> 32),
2316 (uintptr_t) (regID1
>> 32));
2318 TLOG("%s[0x%qx]::didTerminate(%s[0x%qx], defer %d)\n",
2319 victim
->getName(), regID2
,
2320 provider
->getName(), regID1
, defer
);
2327 void IOService::actionFinalize( IOService
* victim
, IOOptionBits options
,
2328 void *unused1 __unused
, void *unused2 __unused
,
2329 void *unused3 __unused
)
2331 uint64_t regID1
= victim
->getRegistryEntryID();
2332 TLOG("%s[0x%qx]::finalize(%08llx)\n", victim
->getName(), regID1
, (long long)options
);
2334 IOSERVICE_TERMINATE_FINALIZE
,
2336 (uintptr_t) (regID1
>> 32),
2339 victim
->finalize( options
);
2342 void IOService::actionStop( IOService
* provider
, IOService
* client
,
2343 void *unused1 __unused
, void *unused2 __unused
,
2344 void *unused3 __unused
)
2346 uint64_t regID1
= provider
->getRegistryEntryID();
2347 uint64_t regID2
= client
->getRegistryEntryID();
2349 TLOG("%s[0x%qx]::stop(%s[0x%qx])\n", client
->getName(), regID2
, provider
->getName(), regID1
);
2351 IOSERVICE_TERMINATE_STOP
,
2353 (uintptr_t) (regID1
>> 32),
2355 (uintptr_t) (regID2
>> 32));
2357 client
->stop( provider
);
2358 if( provider
->isOpen( client
))
2359 provider
->close( client
);
2361 TLOG("%s[0x%qx]::detach(%s[0x%qx])\n", client
->getName(), regID2
, provider
->getName(), regID1
);
2362 client
->detach( provider
);
2365 void IOService::terminateWorker( IOOptionBits options
)
2367 OSArray
* doPhase2List
;
2368 OSArray
* didPhase2List
;
2374 IOService
* provider
;
2380 options
|= kIOServiceRequired
;
2382 doPhase2List
= OSArray::withCapacity( 16 );
2383 didPhase2List
= OSArray::withCapacity( 16 );
2384 freeList
= OSSet::withCapacity( 16 );
2385 if( (0 == doPhase2List
) || (0 == didPhase2List
) || (0 == freeList
))
2389 workDone
= gIOTerminateWork
;
2391 while( (victim
= (IOService
*) gIOTerminatePhase2List
->getObject(0) )) {
2394 gIOTerminatePhase2List
->removeObject(0);
2395 IOLockUnlock( gJobsLock
);
2399 doPhase2
= victim
->lockForArbitration( true );
2401 doPhase2
= (0 != (kIOServiceInactiveState
& victim
->__state
[0]));
2403 doPhase2
= (0 == (victim
->__state
[1] & kIOServiceTermPhase2State
))
2404 && (0 == (victim
->__state
[1] & kIOServiceConfigState
));
2406 if (doPhase2
&& (iter
= victim
->getClientIterator())) {
2407 while (doPhase2
&& (client
= (IOService
*) iter
->getNextObject())) {
2408 doPhase2
= (0 == (client
->__state
[1] & kIOServiceStartState
));
2410 if (!doPhase2
) TLOG("%s[0x%qx]::defer phase2(%s[0x%qx])\n",
2411 victim
->getName(), victim
->getRegistryEntryID(),
2412 client
->getName(), client
->getRegistryEntryID());
2417 victim
->__state
[1] |= kIOServiceTermPhase2State
;
2419 victim
->unlockForArbitration();
2423 if (kIOServiceNeedWillTerminate
& victim
->__state
[1]) {
2424 _workLoopAction( (IOWorkLoop::Action
) &actionWillStop
,
2425 victim
, (void *)(uintptr_t) options
, NULL
);
2428 if( 0 == victim
->getClient()) {
2429 // no clients - will go to finalize
2430 IOLockLock( gJobsLock
);
2431 gIOFinalizeList
->tailQ( victim
);
2432 IOLockUnlock( gJobsLock
);
2434 _workLoopAction( (IOWorkLoop::Action
) &actionWillTerminate
,
2435 victim
, (void *)(uintptr_t) options
, (void *)(uintptr_t) doPhase2List
);
2437 didPhase2List
->headQ( victim
);
2440 victim
= (IOService
*) doPhase2List
->getObject(0);
2443 doPhase2List
->removeObject(0);
2447 while( (victim
= (IOService
*) didPhase2List
->getObject(0)) ) {
2449 if( victim
->lockForArbitration( true )) {
2450 victim
->__state
[1] |= kIOServiceTermPhase3State
;
2451 victim
->unlockForArbitration();
2453 _workLoopAction( (IOWorkLoop::Action
) &actionDidTerminate
,
2454 victim
, (void *)(uintptr_t) options
);
2455 if (kIOServiceNeedWillTerminate
& victim
->__state
[1]) {
2456 _workLoopAction( (IOWorkLoop::Action
) &actionDidStop
,
2457 victim
, (void *)(uintptr_t) options
, NULL
);
2459 didPhase2List
->removeObject(0);
2461 IOLockLock( gJobsLock
);
2468 while( (victim
= (IOService
*) gIOFinalizeList
->getObject(0))) {
2470 IOLockUnlock( gJobsLock
);
2471 _workLoopAction( (IOWorkLoop::Action
) &actionFinalize
,
2472 victim
, (void *)(uintptr_t) options
);
2473 IOLockLock( gJobsLock
);
2475 freeList
->setObject( victim
);
2476 // safe if finalize list is append only
2477 gIOFinalizeList
->removeObject(0);
2481 (!doPhase3
) && (client
= (IOService
*) gIOStopList
->getObject(idx
)); ) {
2483 provider
= (IOService
*) gIOStopProviderList
->getObject(idx
);
2486 uint64_t regID1
= provider
->getRegistryEntryID();
2487 uint64_t regID2
= client
->getRegistryEntryID();
2489 if( !provider
->isChild( client
, gIOServicePlane
)) {
2490 // may be multiply queued - nop it
2491 TLOG("%s[0x%qx]::nop stop(%s[0x%qx])\n", client
->getName(), regID2
, provider
->getName(), regID1
);
2493 IOSERVICE_TERMINATE_STOP_NOP
,
2495 (uintptr_t) (regID1
>> 32),
2497 (uintptr_t) (regID2
>> 32));
2500 // a terminated client is not ready for stop if it has clients, skip it
2501 if( (kIOServiceInactiveState
& client
->__state
[0]) && client
->getClient()) {
2502 TLOG("%s[0x%qx]::defer stop(%s[0x%qx])\n",
2503 client
->getName(), regID2
,
2504 client
->getClient()->getName(), client
->getClient()->getRegistryEntryID());
2506 IOSERVICE_TERMINATE_STOP_DEFER
,
2508 (uintptr_t) (regID1
>> 32),
2510 (uintptr_t) (regID2
>> 32));
2516 IOLockUnlock( gJobsLock
);
2517 _workLoopAction( (IOWorkLoop::Action
) &actionStop
,
2518 provider
, (void *) client
);
2519 IOLockLock( gJobsLock
);
2520 // check the finalize list now
2524 freeList
->setObject( client
);
2525 freeList
->setObject( provider
);
2527 // safe if stop list is append only
2528 gIOStopList
->removeObject( idx
);
2529 gIOStopProviderList
->removeObject( idx
);
2533 } while( doPhase3
);
2535 gIOTerminateWork
-= workDone
;
2536 moreToDo
= (gIOTerminateWork
!= 0);
2539 TLOG("iokit terminate done, %d stops remain\n", gIOStopList
->getCount());
2541 IOSERVICE_TERMINATE_DONE
,
2542 (uintptr_t) gIOStopList
->getCount(), 0, 0, 0);
2545 } while( moreToDo
);
2547 IOLockUnlock( gJobsLock
);
2549 freeList
->release();
2550 doPhase2List
->release();
2551 didPhase2List
->release();
2553 IOLockLock( gJobsLock
);
2556 bool IOService::finalize( IOOptionBits options
)
2559 IOService
* provider
;
2560 uint64_t regID1
, regID2
= getRegistryEntryID();
2562 iter
= getProviderIterator();
2566 while( (provider
= (IOService
*) iter
->getNextObject())) {
2569 if( 0 == (__state
[1] & kIOServiceTermPhase3State
)) {
2570 /* we come down here on programmatic terminate */
2572 regID1
= provider
->getRegistryEntryID();
2573 TLOG("%s[0x%qx]::stop1(%s[0x%qx])\n", getName(), regID2
, provider
->getName(), regID1
);
2575 IOSERVICE_TERMINATE_STOP
,
2577 (uintptr_t) (regID1
>> 32),
2579 (uintptr_t) (regID2
>> 32));
2582 if( provider
->isOpen( this ))
2583 provider
->close( this );
2587 if( provider
->lockForArbitration( true )) {
2588 if( 0 == (provider
->__state
[1] & kIOServiceTermPhase3State
))
2589 scheduleStop( provider
);
2590 provider
->unlockForArbitration();
2607 void IOService::doServiceTerminate( IOOptionBits options
)
2611 // a method in case someone needs to override it
2612 bool IOService::terminateClient( IOService
* client
, IOOptionBits options
)
2616 if( client
->isParent( this, gIOServicePlane
, true))
2617 // we are the clients only provider
2618 ok
= client
->terminate( options
);
2625 bool IOService::terminate( IOOptionBits options
)
2627 options
|= kIOServiceTerminate
;
2629 return( terminatePhase1( options
));
2632 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2638 struct ServiceOpenMessageContext
2640 IOService
* service
;
2642 IOService
* excludeClient
;
2643 IOOptionBits options
;
2646 static void serviceOpenMessageApplier( OSObject
* object
, void * ctx
)
2648 ServiceOpenMessageContext
* context
= (ServiceOpenMessageContext
*) ctx
;
2650 if( object
!= context
->excludeClient
)
2651 context
->service
->messageClient( context
->type
, object
, (void *)(uintptr_t) context
->options
);
2654 bool IOService::open( IOService
* forClient
,
2655 IOOptionBits options
,
2659 ServiceOpenMessageContext context
;
2661 context
.service
= this;
2662 context
.type
= kIOMessageServiceIsAttemptingOpen
;
2663 context
.excludeClient
= forClient
;
2664 context
.options
= options
;
2666 applyToInterested( gIOGeneralInterest
,
2667 &serviceOpenMessageApplier
, &context
);
2669 if( false == lockForArbitration(false) )
2672 ok
= (0 == (__state
[0] & kIOServiceInactiveState
));
2674 ok
= handleOpen( forClient
, options
, arg
);
2676 unlockForArbitration();
2681 void IOService::close( IOService
* forClient
,
2682 IOOptionBits options
)
2687 lockForArbitration();
2689 wasClosed
= handleIsOpen( forClient
);
2691 handleClose( forClient
, options
);
2692 last
= (__state
[1] & kIOServiceTermPhase3State
);
2695 unlockForArbitration();
2698 forClient
->scheduleStop( this );
2700 else if( wasClosed
) {
2702 ServiceOpenMessageContext context
;
2704 context
.service
= this;
2705 context
.type
= kIOMessageServiceWasClosed
;
2706 context
.excludeClient
= forClient
;
2707 context
.options
= options
;
2709 applyToInterested( gIOGeneralInterest
,
2710 &serviceOpenMessageApplier
, &context
);
2714 bool IOService::isOpen( const IOService
* forClient
) const
2716 IOService
* self
= (IOService
*) this;
2719 self
->lockForArbitration();
2721 ok
= handleIsOpen( forClient
);
2723 self
->unlockForArbitration();
2728 bool IOService::handleOpen( IOService
* forClient
,
2729 IOOptionBits options
,
2734 ok
= (0 == __owner
);
2736 __owner
= forClient
;
2738 else if( options
& kIOServiceSeize
) {
2739 ok
= (kIOReturnSuccess
== messageClient( kIOMessageServiceIsRequestingClose
,
2740 __owner
, (void *)(uintptr_t) options
));
2741 if( ok
&& (0 == __owner
))
2742 __owner
= forClient
;
2749 void IOService::handleClose( IOService
* forClient
,
2750 IOOptionBits options
)
2752 if( __owner
== forClient
)
2756 bool IOService::handleIsOpen( const IOService
* forClient
) const
2759 return( __owner
== forClient
);
2761 return( __owner
!= forClient
);
2765 * Probing & starting
2767 static SInt32
IONotifyOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2769 const _IOServiceNotifier
* obj1
= (const _IOServiceNotifier
*) inObj1
;
2770 const _IOServiceNotifier
* obj2
= (const _IOServiceNotifier
*) inObj2
;
2778 val1
= obj1
->priority
;
2781 val2
= obj2
->priority
;
2783 return ( val1
- val2
);
2786 static SInt32
IOServiceObjectOrder( const OSObject
* entry
, void * ref
)
2788 OSDictionary
* dict
;
2789 IOService
* service
;
2790 _IOServiceNotifier
* notify
;
2791 OSSymbol
* key
= (OSSymbol
*) ref
;
2794 if( (dict
= OSDynamicCast( OSDictionary
, entry
)))
2795 offset
= OSDynamicCast(OSNumber
, dict
->getObject( key
));
2796 else if( (notify
= OSDynamicCast( _IOServiceNotifier
, entry
)))
2797 return( notify
->priority
);
2799 else if( (service
= OSDynamicCast( IOService
, entry
)))
2800 offset
= OSDynamicCast(OSNumber
, service
->getProperty( key
));
2807 return( (SInt32
) offset
->unsigned32BitValue());
2809 return( kIODefaultProbeScore
);
2812 SInt32
IOServiceOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2814 const OSObject
* obj1
= (const OSObject
*) inObj1
;
2815 const OSObject
* obj2
= (const OSObject
*) inObj2
;
2823 val1
= IOServiceObjectOrder( obj1
, ref
);
2826 val2
= IOServiceObjectOrder( obj2
, ref
);
2828 return ( val1
- val2
);
2831 IOService
* IOService::copyClientWithCategory( const OSSymbol
* category
)
2833 IOService
* service
= 0;
2835 const OSSymbol
* nextCat
;
2837 iter
= getClientIterator();
2839 while( (service
= (IOService
*) iter
->getNextObject())) {
2840 if( kIOServiceInactiveState
& service
->__state
[0])
2842 nextCat
= (const OSSymbol
*) OSDynamicCast( OSSymbol
,
2843 service
->getProperty( gIOMatchCategoryKey
));
2844 if( category
== nextCat
)
2855 IOService
* IOService::getClientWithCategory( const OSSymbol
* category
)
2858 service
= copyClientWithCategory(category
);
2864 bool IOService::invokeNotifer( _IOServiceNotifier
* notify
)
2866 _IOServiceNotifierInvocation invocation
;
2870 invocation
.thread
= current_thread();
2873 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
2876 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
2877 _IOServiceNotifierInvocation
*, link
);
2883 ret
= (*notify
->handler
)(notify
->target
, notify
->ref
, this, notify
);
2886 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
2887 _IOServiceNotifierInvocation
*, link
);
2888 if( kIOServiceNotifyWaiter
& notify
->state
) {
2889 notify
->state
&= ~kIOServiceNotifyWaiter
;
2890 WAKEUPNOTIFY( notify
);
2899 * Alloc and probe matching classes,
2900 * called on the provider instance
2903 void IOService::probeCandidates( OSOrderedSet
* matches
)
2905 OSDictionary
* match
= 0;
2908 IOService
* newInst
;
2909 OSDictionary
* props
;
2912 OSOrderedSet
* familyMatches
= 0;
2913 OSOrderedSet
* startList
;
2914 OSDictionary
* startDict
= 0;
2915 const OSSymbol
* category
;
2917 _IOServiceNotifier
* notify
;
2918 OSObject
* nextMatch
= 0;
2920 bool needReloc
= false;
2924 IOService
* client
= NULL
;
2928 while( !needReloc
&& (nextMatch
= matches
->getFirstObject())) {
2930 nextMatch
->retain();
2931 matches
->removeObject(nextMatch
);
2933 if( (notify
= OSDynamicCast( _IOServiceNotifier
, nextMatch
))) {
2935 lockForArbitration();
2936 if( 0 == (__state
[0] & kIOServiceInactiveState
))
2937 invokeNotifer( notify
);
2938 unlockForArbitration();
2939 nextMatch
->release();
2943 } else if( !(match
= OSDynamicCast( OSDictionary
, nextMatch
))) {
2944 nextMatch
->release();
2951 debugFlags
= getDebugFlags( match
);
2955 category
= OSDynamicCast( OSSymbol
,
2956 match
->getObject( gIOMatchCategoryKey
));
2958 category
= gIODefaultMatchCategoryKey
;
2960 if( (client
= copyClientWithCategory(category
)) ) {
2962 if( (debugFlags
& kIOLogMatch
) && (this != gIOResources
))
2963 LOG("%s: match category %s exists\n", getName(),
2964 category
->getCStringNoCopy());
2966 nextMatch
->release();
2975 // create a copy now in case its modified during matching
2976 props
= OSDictionary::withDictionary( match
, match
->getCount());
2979 props
->setCapacityIncrement(1);
2981 // check the nub matches
2982 if( false == matchPassive(props
, kIOServiceChangesOK
| kIOServiceClassDone
))
2985 // Check to see if driver reloc has been loaded.
2986 needReloc
= (false == gIOCatalogue
->isModuleLoaded( match
));
2989 if( debugFlags
& kIOLogCatalogue
)
2990 LOG("%s: stalling for module\n", getName());
2992 // If reloc hasn't been loaded, exit;
2993 // reprobing will occur after reloc has been loaded.
2997 // reorder on family matchPropertyTable score.
2998 if( 0 == familyMatches
)
2999 familyMatches
= OSOrderedSet::withCapacity( 1,
3000 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
3002 familyMatches
->setObject( props
);
3007 nextMatch
->release();
3016 if( familyMatches
) {
3019 && (props
= (OSDictionary
*) familyMatches
->getFirstObject())) {
3022 familyMatches
->removeObject( props
);
3027 debugFlags
= getDebugFlags( props
);
3030 symbol
= OSDynamicCast( OSSymbol
,
3031 props
->getObject( gIOClassKey
));
3035 //IOLog("%s alloc (symbol %p props %p)\n", symbol->getCStringNoCopy(), OBFUSCATE(symbol), OBFUSCATE(props));
3037 // alloc the driver instance
3038 inst
= (IOService
*) OSMetaClass::allocClassWithName( symbol
);
3041 IOLog("Couldn't alloc class \"%s\"\n",
3042 symbol
->getCStringNoCopy());
3046 // init driver instance
3047 if( !(inst
->init( props
))) {
3049 if( debugFlags
& kIOLogStart
)
3050 IOLog("%s::init fails\n", symbol
->getCStringNoCopy());
3054 if( __state
[1] & kIOServiceSynchronousState
)
3055 inst
->__state
[1] |= kIOServiceSynchronousState
;
3057 // give the driver the default match category if not specified
3058 category
= OSDynamicCast( OSSymbol
,
3059 props
->getObject( gIOMatchCategoryKey
));
3061 category
= gIODefaultMatchCategoryKey
;
3062 inst
->setProperty( gIOMatchCategoryKey
, (OSObject
*) category
);
3063 // attach driver instance
3064 if( !(inst
->attach( this )))
3067 // pass in score from property table
3068 score
= familyMatches
->orderObject( props
);
3070 // & probe the new driver instance
3072 if( debugFlags
& kIOLogProbe
)
3073 LOG("%s::probe(%s)\n",
3074 inst
->getMetaClass()->getClassName(), getName());
3077 newInst
= inst
->probe( this, &score
);
3078 inst
->detach( this );
3081 if( debugFlags
& kIOLogProbe
)
3082 IOLog("%s::probe fails\n", symbol
->getCStringNoCopy());
3088 newPri
= OSNumber::withNumber( score
, 32 );
3090 newInst
->setProperty( gIOProbeScoreKey
, newPri
);
3094 // add to start list for the match category
3096 startDict
= OSDictionary::withCapacity( 1 );
3097 assert( startDict
);
3098 startList
= (OSOrderedSet
*)
3099 startDict
->getObject( category
);
3100 if( 0 == startList
) {
3101 startList
= OSOrderedSet::withCapacity( 1,
3102 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
3103 if( startDict
&& startList
) {
3104 startDict
->setObject( category
, startList
);
3105 startList
->release();
3108 assert( startList
);
3110 startList
->setObject( newInst
);
3118 familyMatches
->release();
3122 // start the best (until success) of each category
3124 iter
= OSCollectionIterator::withCollection( startDict
);
3126 while( (category
= (const OSSymbol
*) iter
->getNextObject())) {
3128 startList
= (OSOrderedSet
*) startDict
->getObject( category
);
3129 assert( startList
);
3134 while( true // (!started)
3135 && (inst
= (IOService
*)startList
->getFirstObject())) {
3138 startList
->removeObject(inst
);
3141 debugFlags
= getDebugFlags( inst
->getPropertyTable() );
3143 if( debugFlags
& kIOLogStart
) {
3145 LOG( "match category exists, skipping " );
3146 LOG( "%s::start(%s) <%d>\n", inst
->getName(),
3147 getName(), inst
->getRetainCount());
3150 if( false == started
)
3151 started
= startCandidate( inst
);
3153 if( (debugFlags
& kIOLogStart
) && (false == started
))
3154 LOG( "%s::start(%s) <%d> failed\n", inst
->getName(), getName(),
3155 inst
->getRetainCount());
3164 // adjust the busy count by +1 if matching is stalled for a module,
3165 // or -1 if a previously stalled matching is complete.
3166 lockForArbitration();
3168 uint64_t regID
= getRegistryEntryID();
3171 adjBusy
= (__state
[1] & kIOServiceModuleStallState
) ? 0 : 1;
3175 IOSERVICE_MODULESTALL
,
3177 (uintptr_t) (regID
>> 32),
3181 __state
[1] |= kIOServiceModuleStallState
;
3184 } else if( __state
[1] & kIOServiceModuleStallState
) {
3187 IOSERVICE_MODULEUNSTALL
,
3189 (uintptr_t) (regID
>> 32),
3193 __state
[1] &= ~kIOServiceModuleStallState
;
3197 _adjustBusy( adjBusy
);
3198 unlockForArbitration();
3201 startDict
->release();
3205 * Start a previously attached & probed instance,
3206 * called on exporting object instance
3209 bool IOService::startCandidate( IOService
* service
)
3213 ok
= service
->attach( this );
3217 if (this != gIOResources
)
3219 // stall for any nub resources
3221 // stall for any driver resources
3222 service
->checkResources();
3225 AbsoluteTime startTime
;
3226 AbsoluteTime endTime
;
3229 if (kIOLogStart
& gIOKitDebug
)
3230 clock_get_uptime(&startTime
);
3232 ok
= service
->start(this);
3234 if (kIOLogStart
& gIOKitDebug
)
3236 clock_get_uptime(&endTime
);
3238 if (CMP_ABSOLUTETIME(&endTime
, &startTime
) > 0)
3240 SUB_ABSOLUTETIME(&endTime
, &startTime
);
3241 absolutetime_to_nanoseconds(endTime
, &nano
);
3242 if (nano
> 500000000ULL)
3243 IOLog("%s::start took %ld ms\n", service
->getName(), (long)(UInt32
)(nano
/ 1000000ULL));
3247 service
->detach( this );
3252 void IOService::publishResource( const char * key
, OSObject
* value
)
3254 const OSSymbol
* sym
;
3256 if( (sym
= OSSymbol::withCString( key
))) {
3257 publishResource( sym
, value
);
3262 void IOService::publishResource( const OSSymbol
* key
, OSObject
* value
)
3265 value
= (OSObject
*) gIOServiceKey
;
3267 gIOResources
->setProperty( key
, value
);
3269 if( IORecursiveLockHaveLock( gNotificationLock
))
3272 gIOResourceGenerationCount
++;
3273 gIOResources
->registerService();
3276 bool IOService::addNeededResource( const char * key
)
3278 OSObject
* resourcesProp
;
3283 resourcesProp
= getProperty( gIOResourceMatchKey
);
3285 newKey
= OSString::withCString( key
);
3286 if( (0 == resourcesProp
) || (0 == newKey
))
3289 set
= OSDynamicCast( OSSet
, resourcesProp
);
3291 set
= OSSet::withCapacity( 1 );
3293 set
->setObject( resourcesProp
);
3298 set
->setObject( newKey
);
3300 ret
= setProperty( gIOResourceMatchKey
, set
);
3306 bool IOService::checkResource( OSObject
* matching
)
3309 OSDictionary
* table
;
3311 if( (str
= OSDynamicCast( OSString
, matching
))) {
3312 if( gIOResources
->getProperty( str
))
3317 table
= resourceMatching( str
);
3318 else if( (table
= OSDynamicCast( OSDictionary
, matching
)))
3321 IOLog("%s: Can't match using: %s\n", getName(),
3322 matching
->getMetaClass()->getClassName());
3323 /* false would stall forever */
3327 if( gIOKitDebug
& kIOLogConfig
)
3328 LOG("config(%p): stalling %s\n", OBFUSCATE(IOThreadSelf()), getName());
3330 waitForService( table
);
3332 if( gIOKitDebug
& kIOLogConfig
)
3333 LOG("config(%p): waking\n", OBFUSCATE(IOThreadSelf()) );
3338 bool IOService::checkResources( void )
3340 OSObject
* resourcesProp
;
3345 resourcesProp
= getProperty( gIOResourceMatchKey
);
3346 if( 0 == resourcesProp
)
3349 if( (set
= OSDynamicCast( OSSet
, resourcesProp
))) {
3351 iter
= OSCollectionIterator::withCollection( set
);
3353 while( ok
&& (resourcesProp
= iter
->getNextObject()) )
3354 ok
= checkResource( resourcesProp
);
3359 ok
= checkResource( resourcesProp
);
3365 void _IOConfigThread::configThread( void )
3367 _IOConfigThread
* inst
;
3370 if( !(inst
= new _IOConfigThread
))
3375 if (KERN_SUCCESS
!= kernel_thread_start(&_IOConfigThread::main
, inst
, &unused
))
3388 void _IOConfigThread::free( void )
3390 thread_deallocate(current_thread());
3394 void IOService::doServiceMatch( IOOptionBits options
)
3396 _IOServiceNotifier
* notify
;
3398 OSOrderedSet
* matches
;
3399 SInt32 catalogGeneration
;
3400 bool keepGuessing
= true;
3401 bool reRegistered
= true;
3404 // job->nub->deliverNotification( gIOPublishNotification,
3405 // kIOServiceRegisteredState, 0xffffffff );
3407 while( keepGuessing
) {
3409 matches
= gIOCatalogue
->findDrivers( this, &catalogGeneration
);
3410 // the matches list should always be created by findDrivers()
3413 lockForArbitration();
3414 if( 0 == (__state
[0] & kIOServiceFirstPublishState
)) {
3415 getMetaClass()->addInstance(this);
3416 deliverNotification( gIOFirstPublishNotification
,
3417 kIOServiceFirstPublishState
, 0xffffffff );
3420 __state
[1] &= ~kIOServiceNeedConfigState
;
3421 __state
[1] |= kIOServiceConfigState
;
3422 didRegister
= (0 == (kIOServiceRegisteredState
& __state
[0]));
3423 __state
[0] |= kIOServiceRegisteredState
;
3425 keepGuessing
&= (0 == (__state
[0] & kIOServiceInactiveState
));
3426 if (reRegistered
&& keepGuessing
) {
3427 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
3428 gNotifications
->getObject( gIOPublishNotification
) );
3430 while((notify
= (_IOServiceNotifier
*)
3431 iter
->getNextObject())) {
3433 if( matchPassive(notify
->matching
, 0)
3434 && (kIOServiceNotifyEnable
& notify
->state
))
3435 matches
->setObject( notify
);
3442 unlockForArbitration();
3444 if (keepGuessing
&& matches
->getCount() && (kIOReturnSuccess
== getResources()))
3445 probeCandidates( matches
);
3450 lockForArbitration();
3451 reRegistered
= (0 != (__state
[1] & kIOServiceNeedConfigState
));
3453 (reRegistered
|| (catalogGeneration
!=
3454 gIOCatalogue
->getGenerationCount()))
3455 && (0 == (__state
[0] & kIOServiceInactiveState
));
3458 unlockForArbitration();
3461 if( (0 == (__state
[0] & kIOServiceInactiveState
))
3462 && (0 == (__state
[1] & kIOServiceModuleStallState
)) ) {
3463 deliverNotification( gIOMatchedNotification
,
3464 kIOServiceMatchedState
, 0xffffffff );
3465 if( 0 == (__state
[0] & kIOServiceFirstMatchState
))
3466 deliverNotification( gIOFirstMatchNotification
,
3467 kIOServiceFirstMatchState
, 0xffffffff );
3470 __state
[1] &= ~kIOServiceConfigState
;
3471 scheduleTerminatePhase2();
3474 unlockForArbitration();
3477 UInt32
IOService::_adjustBusy( SInt32 delta
)
3482 bool wasQuiet
, nowQuiet
, needWake
;
3485 result
= __state
[1] & kIOServiceBusyStateMask
;
3489 next
->lockForArbitration();
3490 count
= next
->__state
[1] & kIOServiceBusyStateMask
;
3491 wasQuiet
= (0 == count
);
3492 if (((delta
< 0) && wasQuiet
) || ((delta
> 0) && (kIOServiceBusyMax
== count
)))
3493 OSReportWithBacktrace("%s: bad busy count (%d,%d)\n", next
->getName(), count
, delta
);
3496 next
->__state
[1] = (next
->__state
[1] & ~kIOServiceBusyStateMask
) | count
;
3497 nowQuiet
= (0 == count
);
3498 needWake
= (0 != (kIOServiceBusyWaiterState
& next
->__state
[1]));
3501 next
->__state
[1] &= ~kIOServiceBusyWaiterState
;
3502 IOLockLock( gIOServiceBusyLock
);
3503 thread_wakeup( (event_t
) next
);
3504 IOLockUnlock( gIOServiceBusyLock
);
3507 next
->unlockForArbitration();
3509 if( (wasQuiet
|| nowQuiet
) ) {
3510 uint64_t regID
= next
->getRegistryEntryID();
3513 ((wasQuiet
/*nowBusy*/) ? IOSERVICE_BUSY
: IOSERVICE_NONBUSY
),
3515 (uintptr_t) (regID
>> 32),
3521 next
->__timeBusy
= mach_absolute_time();
3525 next
->__accumBusy
+= mach_absolute_time() - next
->__timeBusy
;
3526 next
->__timeBusy
= 0;
3529 MessageClientsContext context
;
3531 context
.service
= next
;
3532 context
.type
= kIOMessageServiceBusyStateChange
;
3533 context
.argument
= (void *) wasQuiet
; /*nowBusy*/
3534 context
.argSize
= 0;
3536 applyToInterestNotifiers( next
, gIOBusyInterest
,
3537 &messageClientsApplier
, &context
);
3540 if( nowQuiet
&& (next
== gIOServiceRoot
)) {
3541 OSKext::considerUnloads();
3542 IOServiceTrace(IOSERVICE_REGISTRY_QUIET
, 0, 0, 0, 0);
3547 delta
= nowQuiet
? -1 : +1;
3549 } while( (wasQuiet
|| nowQuiet
) && (next
= next
->getProvider()));
3554 void IOService::adjustBusy( SInt32 delta
)
3556 lockForArbitration();
3557 _adjustBusy( delta
);
3558 unlockForArbitration();
3561 uint64_t IOService::getAccumulatedBusyTime( void )
3563 uint64_t accumBusy
= __accumBusy
;
3564 uint64_t timeBusy
= __timeBusy
;
3569 accumBusy
= __accumBusy
;
3570 timeBusy
= __timeBusy
;
3572 accumBusy
+= mach_absolute_time() - timeBusy
;
3574 while (timeBusy
!= __timeBusy
);
3576 absolutetime_to_nanoseconds(*(AbsoluteTime
*)&accumBusy
, &nano
);
3581 UInt32
IOService::getBusyState( void )
3583 return( __state
[1] & kIOServiceBusyStateMask
);
3586 IOReturn
IOService::waitForState( UInt32 mask
, UInt32 value
,
3587 mach_timespec_t
* timeout
)
3589 panic("waitForState");
3590 return (kIOReturnUnsupported
);
3593 IOReturn
IOService::waitForState( UInt32 mask
, UInt32 value
,
3597 int waitResult
= THREAD_AWAKENED
;
3598 bool computeDeadline
= true;
3599 AbsoluteTime abstime
;
3602 lockForArbitration();
3603 IOLockLock( gIOServiceBusyLock
);
3604 wait
= (value
!= (__state
[1] & mask
));
3606 __state
[1] |= kIOServiceBusyWaiterState
;
3607 unlockForArbitration();
3608 if( timeout
!= UINT64_MAX
) {
3609 if( computeDeadline
) {
3610 AbsoluteTime nsinterval
;
3611 nanoseconds_to_absolutetime(timeout
, &nsinterval
);
3612 clock_absolutetime_interval_to_deadline(nsinterval
, &abstime
);
3613 computeDeadline
= false;
3615 assert_wait_deadline((event_t
)this, THREAD_UNINT
, __OSAbsoluteTime(abstime
));
3618 assert_wait((event_t
)this, THREAD_UNINT
);
3620 unlockForArbitration();
3621 IOLockUnlock( gIOServiceBusyLock
);
3623 waitResult
= thread_block(THREAD_CONTINUE_NULL
);
3625 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
3627 if( waitResult
== THREAD_TIMED_OUT
)
3628 return( kIOReturnTimeout
);
3630 return( kIOReturnSuccess
);
3633 IOReturn
IOService::waitQuiet( uint64_t timeout
)
3636 ret
= waitForState( kIOServiceBusyStateMask
, 0, timeout
);
3637 if ((kIOReturnTimeout
== ret
) && (timeout
>= 30000000000) && (kIOWaitQuietPanics
& gIOKitDebug
))
3639 panic("IOService 0x%llx (%s) busy timeout", getRegistryEntryID(), getName());
3644 IOReturn
IOService::waitQuiet( mach_timespec_t
* timeout
)
3650 timeoutNS
= timeout
->tv_sec
;
3651 timeoutNS
*= kSecondScale
;
3652 timeoutNS
+= timeout
->tv_nsec
;
3655 timeoutNS
= UINT64_MAX
;
3657 return (waitQuiet(timeoutNS
));
3660 bool IOService::serializeProperties( OSSerialize
* s
) const
3663 ((IOService
*)this)->setProperty( ((IOService
*)this)->__state
,
3664 sizeof( __state
), "__state");
3666 return( super::serializeProperties(s
) );
3670 void _IOConfigThread::main(void * arg
, wait_result_t result
)
3672 _IOConfigThread
* self
= (_IOConfigThread
*) arg
;
3673 _IOServiceJob
* job
;
3677 thread_precedence_policy_data_t precedence
= { -1 };
3679 kr
= thread_policy_set(current_thread(),
3680 THREAD_PRECEDENCE_POLICY
,
3681 (thread_policy_t
) &precedence
,
3682 THREAD_PRECEDENCE_POLICY_COUNT
);
3683 if (KERN_SUCCESS
!= kr
)
3684 IOLog("thread_policy_set(%d)\n", kr
);
3690 semaphore_wait( gJobsSemaphore
);
3692 IOTakeLock( gJobsLock
);
3693 job
= (_IOServiceJob
*) gJobs
->getFirstObject();
3695 gJobs
->removeObject(job
);
3698 // gNumConfigThreads--; // we're out of service
3699 gNumWaitingThreads
--; // we're out of service
3701 IOUnlock( gJobsLock
);
3707 if( gIOKitDebug
& kIOLogConfig
)
3708 LOG("config(%p): starting on %s, %d\n",
3709 OBFUSCATE(IOThreadSelf()), job
->nub
->getName(), job
->type
);
3711 switch( job
->type
) {
3714 nub
->doServiceMatch( job
->options
);
3718 LOG("config(%p): strange type (%d)\n",
3719 OBFUSCATE(IOThreadSelf()), job
->type
);
3726 IOTakeLock( gJobsLock
);
3727 alive
= (gOutstandingJobs
> gNumWaitingThreads
);
3729 gNumWaitingThreads
++; // back in service
3730 // gNumConfigThreads++;
3732 if( 0 == --gNumConfigThreads
) {
3733 // IOLog("MATCH IDLE\n");
3734 IOLockWakeup( gJobsLock
, (event_t
) &gNumConfigThreads
, /* one-thread */ false );
3737 IOUnlock( gJobsLock
);
3742 if( gIOKitDebug
& kIOLogConfig
)
3743 LOG("config(%p): terminating\n", OBFUSCATE(IOThreadSelf()) );
3748 IOReturn
IOService::waitMatchIdle( UInt32 msToWait
)
3751 int waitResult
= THREAD_AWAKENED
;
3752 bool computeDeadline
= true;
3753 AbsoluteTime deadline
;
3755 IOLockLock( gJobsLock
);
3757 wait
= (0 != gNumConfigThreads
);
3760 if( computeDeadline
) {
3761 clock_interval_to_deadline(
3762 msToWait
, kMillisecondScale
, &deadline
);
3763 computeDeadline
= false;
3765 waitResult
= IOLockSleepDeadline( gJobsLock
, &gNumConfigThreads
,
3766 deadline
, THREAD_UNINT
);
3768 waitResult
= IOLockSleep( gJobsLock
, &gNumConfigThreads
,
3772 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
3773 IOLockUnlock( gJobsLock
);
3775 if( waitResult
== THREAD_TIMED_OUT
)
3776 return( kIOReturnTimeout
);
3778 return( kIOReturnSuccess
);
3781 void _IOServiceJob::pingConfig( _IOServiceJob
* job
)
3788 IOTakeLock( gJobsLock
);
3791 gJobs
->setLastObject( job
);
3793 count
= gNumWaitingThreads
;
3794 // if( gNumConfigThreads) count++;// assume we're called from a config thread
3796 create
= ( (gOutstandingJobs
> count
)
3797 && (gNumConfigThreads
< kMaxConfigThreads
) );
3799 gNumConfigThreads
++;
3800 gNumWaitingThreads
++;
3803 IOUnlock( gJobsLock
);
3808 if( gIOKitDebug
& kIOLogConfig
)
3809 LOG("config(%d): creating\n", gNumConfigThreads
- 1);
3810 _IOConfigThread::configThread();
3813 semaphore_signal( gJobsSemaphore
);
3816 struct IOServiceMatchContext
3818 OSDictionary
* table
;
3826 bool IOService::instanceMatch(const OSObject
* entry
, void * context
)
3828 IOServiceMatchContext
* ctx
= (typeof(ctx
)) context
;
3829 IOService
* service
= (typeof(service
)) entry
;
3830 OSDictionary
* table
= ctx
->table
;
3831 uint32_t options
= ctx
->options
;
3832 uint32_t state
= ctx
->state
;
3839 match
= ((state
== (state
& service
->__state
[0]))
3840 && (0 == (service
->__state
[0] & kIOServiceInactiveState
)));
3842 ctx
->count
+= table
->getCount();
3843 match
= service
->matchInternal(table
, options
, &done
);
3850 if ((kIONotifyOnce
& options
) && (ctx
->done
== ctx
->count
))
3853 ctx
->result
= service
;
3856 else if (!ctx
->result
)
3858 ctx
->result
= OSSet::withObjects((const OSObject
**) &service
, 1, 1);
3862 ((OSSet
*)ctx
->result
)->setObject(service
);
3867 // internal - call with gNotificationLock
3868 OSObject
* IOService::copyExistingServices( OSDictionary
* matching
,
3869 IOOptionBits inState
, IOOptionBits options
)
3871 OSObject
* current
= 0;
3873 IOService
* service
;
3881 OSSerialize
* s
= OSSerialize::withCapacity(128);
3882 matching
->serialize(s
);
3885 if((obj
= matching
->getObject(gIOProviderClassKey
))
3887 && gIOResourcesKey
->isEqualTo(obj
)
3888 && (service
= gIOResources
))
3890 if( (inState
== (service
->__state
[0] & inState
))
3891 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3892 && service
->matchPassive(matching
, options
))
3894 if( options
& kIONotifyOnce
)
3900 current
= OSSet::withObjects((const OSObject
**) &service
, 1, 1 );
3905 IOServiceMatchContext ctx
;
3906 ctx
.table
= matching
;
3907 ctx
.state
= inState
;
3910 ctx
.options
= options
;
3913 if ((str
= OSDynamicCast(OSString
, obj
)))
3915 const OSSymbol
* sym
= OSSymbol::withString(str
);
3916 OSMetaClass::applyToInstancesOfClassName(sym
, instanceMatch
, &ctx
);
3921 IOService::gMetaClass
.applyToInstances(instanceMatch
, &ctx
);
3925 current
= ctx
.result
;
3927 options
|= kIOServiceInternalDone
| kIOServiceClassDone
;
3928 if (current
&& (ctx
.done
!= ctx
.count
))
3931 source
= OSDynamicCast(OSSet
, current
);
3933 while ((service
= (IOService
*) source
->getAnyObject()))
3935 if (service
->matchPassive(matching
, options
))
3937 if( options
& kIONotifyOnce
)
3945 ((OSSet
*)current
)->setObject( service
);
3949 current
= OSSet::withObjects(
3950 (const OSObject
**) &service
, 1, 1 );
3953 source
->removeObject(service
);
3961 OSObject
* _current
= 0;
3963 iter
= IORegistryIterator::iterateOver( gIOServicePlane
,
3964 kIORegistryIterateRecursively
);
3968 while( (service
= (IOService
*) iter
->getNextObject())) {
3969 if( (inState
== (service
->__state
[0] & inState
))
3970 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3971 && service
->matchPassive(matching
, 0)) {
3973 if( options
& kIONotifyOnce
) {
3979 ((OSSet
*)_current
)->setObject( service
);
3981 _current
= OSSet::withObjects(
3982 (const OSObject
**) &service
, 1, 1 );
3985 } while( !service
&& !iter
->isValid());
3990 if ( ((current
!= 0) != (_current
!= 0))
3991 || (current
&& _current
&& !current
->isEqualTo(_current
)))
3993 OSSerialize
* s1
= OSSerialize::withCapacity(128);
3994 OSSerialize
* s2
= OSSerialize::withCapacity(128);
3995 current
->serialize(s1
);
3996 _current
->serialize(s2
);
3997 kprintf("**mismatch** %p %p\n%s\n%s\n%s\n", OBFUSCATE(current
),
3998 OBFUSCATE(_current
), s
->text(), s1
->text(), s2
->text());
4003 if (_current
) _current
->release();
4009 if( current
&& (0 == (options
& (kIONotifyOnce
| kIOServiceExistingSet
)))) {
4010 iter
= OSCollectionIterator::withCollection( (OSSet
*)current
);
4019 OSIterator
* IOService::getMatchingServices( OSDictionary
* matching
)
4023 // is a lock even needed?
4026 iter
= (OSIterator
*) copyExistingServices( matching
,
4027 kIOServiceMatchedState
);
4034 IOService
* IOService::copyMatchingService( OSDictionary
* matching
)
4036 IOService
* service
;
4038 // is a lock even needed?
4041 service
= (IOService
*) copyExistingServices( matching
,
4042 kIOServiceMatchedState
, kIONotifyOnce
);
4049 struct _IOServiceMatchingNotificationHandlerRef
4051 IOServiceNotificationHandler handler
;
4055 static bool _IOServiceMatchingNotificationHandler( void * target
, void * refCon
,
4056 IOService
* newService
,
4057 IONotifier
* notifier
)
4059 return ((*((_IOServiceNotifier
*) notifier
)->compatHandler
)(target
, refCon
, newService
));
4062 // internal - call with gNotificationLock
4063 IONotifier
* IOService::setNotification(
4064 const OSSymbol
* type
, OSDictionary
* matching
,
4065 IOServiceMatchingNotificationHandler handler
, void * target
, void * ref
,
4068 _IOServiceNotifier
* notify
= 0;
4074 notify
= new _IOServiceNotifier
;
4075 if( notify
&& !notify
->init()) {
4081 notify
->handler
= handler
;
4082 notify
->target
= target
;
4083 notify
->matching
= matching
;
4085 if (handler
== &_IOServiceMatchingNotificationHandler
)
4087 notify
->compatHandler
= ((_IOServiceMatchingNotificationHandlerRef
*)ref
)->handler
;
4088 notify
->ref
= ((_IOServiceMatchingNotificationHandlerRef
*)ref
)->ref
;
4092 notify
->priority
= priority
;
4093 notify
->state
= kIOServiceNotifyEnable
;
4094 queue_init( ¬ify
->handlerInvocations
);
4098 if( 0 == (set
= (OSOrderedSet
*) gNotifications
->getObject( type
))) {
4099 set
= OSOrderedSet::withCapacity( 1,
4100 IONotifyOrdering
, 0 );
4102 gNotifications
->setObject( type
, set
);
4106 notify
->whence
= set
;
4108 set
->setObject( notify
);
4114 // internal - call with gNotificationLock
4115 IONotifier
* IOService::doInstallNotification(
4116 const OSSymbol
* type
, OSDictionary
* matching
,
4117 IOServiceMatchingNotificationHandler handler
,
4118 void * target
, void * ref
,
4119 SInt32 priority
, OSIterator
** existing
)
4122 IONotifier
* notify
;
4123 IOOptionBits inState
;
4128 if( type
== gIOPublishNotification
)
4129 inState
= kIOServiceRegisteredState
;
4131 else if( type
== gIOFirstPublishNotification
)
4132 inState
= kIOServiceFirstPublishState
;
4134 else if( (type
== gIOMatchedNotification
)
4135 || (type
== gIOFirstMatchNotification
))
4136 inState
= kIOServiceMatchedState
;
4137 else if( type
== gIOTerminatedNotification
)
4142 notify
= setNotification( type
, matching
, handler
, target
, ref
, priority
);
4145 // get the current set
4146 exist
= (OSIterator
*) copyExistingServices( matching
, inState
);
4155 #if !defined(__LP64__)
4156 IONotifier
* IOService::installNotification(const OSSymbol
* type
, OSDictionary
* matching
,
4157 IOServiceNotificationHandler handler
,
4158 void * target
, void * refCon
,
4159 SInt32 priority
, OSIterator
** existing
)
4161 IONotifier
* result
;
4162 _IOServiceMatchingNotificationHandlerRef ref
;
4163 ref
.handler
= handler
;
4166 result
= (_IOServiceNotifier
*) installNotification( type
, matching
,
4167 &_IOServiceMatchingNotificationHandler
,
4168 target
, &ref
, priority
, existing
);
4170 matching
->release();
4174 #endif /* !defined(__LP64__) */
4177 IONotifier
* IOService::installNotification(
4178 const OSSymbol
* type
, OSDictionary
* matching
,
4179 IOServiceMatchingNotificationHandler handler
,
4180 void * target
, void * ref
,
4181 SInt32 priority
, OSIterator
** existing
)
4183 IONotifier
* notify
;
4187 notify
= doInstallNotification( type
, matching
, handler
, target
, ref
,
4188 priority
, existing
);
4195 IONotifier
* IOService::addNotification(
4196 const OSSymbol
* type
, OSDictionary
* matching
,
4197 IOServiceNotificationHandler handler
,
4198 void * target
, void * refCon
,
4201 IONotifier
* result
;
4202 _IOServiceMatchingNotificationHandlerRef ref
;
4204 ref
.handler
= handler
;
4207 result
= addMatchingNotification(type
, matching
, &_IOServiceMatchingNotificationHandler
,
4208 target
, &ref
, priority
);
4211 matching
->release();
4216 IONotifier
* IOService::addMatchingNotification(
4217 const OSSymbol
* type
, OSDictionary
* matching
,
4218 IOServiceMatchingNotificationHandler handler
,
4219 void * target
, void * ref
,
4222 OSIterator
* existing
= NULL
;
4223 _IOServiceNotifier
* notify
;
4226 notify
= (_IOServiceNotifier
*) installNotification( type
, matching
,
4227 handler
, target
, ref
, priority
, &existing
);
4229 // send notifications for existing set
4232 notify
->retain(); // in case handler remove()s
4233 while( (next
= (IOService
*) existing
->getNextObject())) {
4235 next
->lockForArbitration();
4236 if( 0 == (next
->__state
[0] & kIOServiceInactiveState
))
4237 next
->invokeNotifer( notify
);
4238 next
->unlockForArbitration();
4241 existing
->release();
4247 bool IOService::syncNotificationHandler(
4248 void * /* target */, void * ref
,
4249 IOService
* newService
,
4250 IONotifier
* notifier
)
4254 if (!*((IOService
**) ref
))
4256 newService
->retain();
4257 (*(IOService
**) ref
) = newService
;
4265 IOService
* IOService::waitForMatchingService( OSDictionary
* matching
,
4268 IONotifier
* notify
= 0;
4269 // priority doesn't help us much since we need a thread wakeup
4270 SInt32 priority
= 0;
4281 result
= (IOService
*) copyExistingServices( matching
,
4282 kIOServiceMatchedState
, kIONotifyOnce
);
4285 notify
= IOService::setNotification( gIOMatchedNotification
, matching
,
4286 &IOService::syncNotificationHandler
, (void *) 0,
4287 &result
, priority
);
4290 if (UINT64_MAX
!= timeout
)
4292 AbsoluteTime deadline
;
4293 nanoseconds_to_absolutetime(timeout
, &deadline
);
4294 clock_absolutetime_interval_to_deadline(deadline
, &deadline
);
4295 SLEEPNOTIFYTO(&result
, deadline
);
4299 SLEEPNOTIFY(&result
);
4307 notify
->remove(); // dequeues
4312 IOService
* IOService::waitForService( OSDictionary
* matching
,
4313 mach_timespec_t
* timeout
)
4320 timeoutNS
= timeout
->tv_sec
;
4321 timeoutNS
*= kSecondScale
;
4322 timeoutNS
+= timeout
->tv_nsec
;
4325 timeoutNS
= UINT64_MAX
;
4327 result
= waitForMatchingService(matching
, timeoutNS
);
4329 matching
->release();
4336 void IOService::deliverNotification( const OSSymbol
* type
,
4337 IOOptionBits orNewState
, IOOptionBits andNewState
)
4339 _IOServiceNotifier
* notify
;
4341 OSArray
* willSend
= 0;
4343 lockForArbitration();
4345 if( (0 == (__state
[0] & kIOServiceInactiveState
))
4346 || (type
== gIOTerminatedNotification
)) {
4350 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
4351 gNotifications
->getObject( type
) );
4354 while( (notify
= (_IOServiceNotifier
*) iter
->getNextObject())) {
4356 if( matchPassive(notify
->matching
, 0)
4357 && (kIOServiceNotifyEnable
& notify
->state
)) {
4359 willSend
= OSArray::withCapacity(8);
4361 willSend
->setObject( notify
);
4367 __state
[0] = (__state
[0] | orNewState
) & andNewState
;
4373 for( unsigned int idx
= 0;
4374 (notify
= (_IOServiceNotifier
*) willSend
->getObject(idx
));
4376 invokeNotifer( notify
);
4378 willSend
->release();
4380 unlockForArbitration();
4383 IOOptionBits
IOService::getState( void ) const
4385 return( __state
[0] );
4389 * Helpers to make matching objects for simple cases
4392 OSDictionary
* IOService::serviceMatching( const OSString
* name
,
4393 OSDictionary
* table
)
4396 const OSString
* str
;
4398 str
= OSSymbol::withString(name
);
4403 table
= OSDictionary::withCapacity( 2 );
4405 table
->setObject(gIOProviderClassKey
, (OSObject
*)str
);
4411 OSDictionary
* IOService::serviceMatching( const char * name
,
4412 OSDictionary
* table
)
4414 const OSString
* str
;
4416 str
= OSSymbol::withCString( name
);
4420 table
= serviceMatching( str
, table
);
4425 OSDictionary
* IOService::nameMatching( const OSString
* name
,
4426 OSDictionary
* table
)
4429 table
= OSDictionary::withCapacity( 2 );
4431 table
->setObject( gIONameMatchKey
, (OSObject
*)name
);
4436 OSDictionary
* IOService::nameMatching( const char * name
,
4437 OSDictionary
* table
)
4439 const OSString
* str
;
4441 str
= OSSymbol::withCString( name
);
4445 table
= nameMatching( str
, table
);
4450 OSDictionary
* IOService::resourceMatching( const OSString
* str
,
4451 OSDictionary
* table
)
4453 table
= serviceMatching( gIOResourcesKey
, table
);
4455 table
->setObject( gIOResourceMatchKey
, (OSObject
*) str
);
4460 OSDictionary
* IOService::resourceMatching( const char * name
,
4461 OSDictionary
* table
)
4463 const OSSymbol
* str
;
4465 str
= OSSymbol::withCString( name
);
4469 table
= resourceMatching( str
, table
);
4475 OSDictionary
* IOService::propertyMatching( const OSSymbol
* key
, const OSObject
* value
,
4476 OSDictionary
* table
)
4478 OSDictionary
* properties
;
4480 properties
= OSDictionary::withCapacity( 2 );
4483 properties
->setObject( key
, value
);
4486 table
= OSDictionary::withCapacity( 2 );
4488 table
->setObject( gIOPropertyMatchKey
, properties
);
4490 properties
->release();
4495 OSDictionary
* IOService::registryEntryIDMatching( uint64_t entryID
,
4496 OSDictionary
* table
)
4500 num
= OSNumber::withNumber( entryID
, 64 );
4505 table
= OSDictionary::withCapacity( 2 );
4507 table
->setObject( gIORegistryEntryIDKey
, num
);
4517 * _IOServiceNotifier
4520 // wait for all threads, other than the current one,
4521 // to exit the handler
4523 void _IOServiceNotifier::wait()
4525 _IOServiceNotifierInvocation
* next
;
4530 queue_iterate( &handlerInvocations
, next
,
4531 _IOServiceNotifierInvocation
*, link
) {
4532 if( next
->thread
!= current_thread() ) {
4538 state
|= kIOServiceNotifyWaiter
;
4545 void _IOServiceNotifier::free()
4547 assert( queue_empty( &handlerInvocations
));
4551 void _IOServiceNotifier::remove()
4556 whence
->removeObject( (OSObject
*) this );
4560 matching
->release();
4564 state
&= ~kIOServiceNotifyEnable
;
4573 bool _IOServiceNotifier::disable()
4579 ret
= (0 != (kIOServiceNotifyEnable
& state
));
4580 state
&= ~kIOServiceNotifyEnable
;
4589 void _IOServiceNotifier::enable( bool was
)
4593 state
|= kIOServiceNotifyEnable
;
4595 state
&= ~kIOServiceNotifyEnable
;
4603 IOService
* IOResources::resources( void )
4607 inst
= new IOResources
;
4608 if( inst
&& !inst
->init()) {
4616 bool IOResources::init( OSDictionary
* dictionary
)
4618 // Do super init first
4619 if ( !super::init() )
4622 // Allow PAL layer to publish a value
4623 const char *property_name
;
4626 pal_get_resource_property( &property_name
, &property_value
);
4628 if( property_name
) {
4630 const OSSymbol
* sym
;
4632 if( (num
= OSNumber::withNumber(property_value
, 32)) != 0 ) {
4633 if( (sym
= OSSymbol::withCString( property_name
)) != 0 ) {
4634 this->setProperty( sym
, num
);
4644 IOWorkLoop
* IOResources::getWorkLoop() const
4646 // If we are the resource root
4647 // then use the platform's workloop
4648 if (this == (IOResources
*) gIOResources
)
4649 return getPlatform()->getWorkLoop();
4651 return IOService::getWorkLoop();
4654 bool IOResources::matchPropertyTable( OSDictionary
* table
)
4662 prop
= table
->getObject( gIOResourceMatchKey
);
4663 str
= OSDynamicCast( OSString
, prop
);
4665 ok
= (0 != getProperty( str
));
4667 else if( (set
= OSDynamicCast( OSSet
, prop
))) {
4669 iter
= OSCollectionIterator::withCollection( set
);
4671 while( ok
&& (str
= OSDynamicCast( OSString
, iter
->getNextObject()) ))
4672 ok
= (0 != getProperty( str
));
4681 void IOService::consoleLockTimer(thread_call_param_t p0
, thread_call_param_t p1
)
4683 IOService::updateConsoleUsers(NULL
, 0);
4686 void IOService::updateConsoleUsers(OSArray
* consoleUsers
, IOMessage systemMessage
)
4688 IORegistryEntry
* regEntry
;
4689 OSObject
* locked
= kOSBooleanFalse
;
4692 OSDictionary
* user
;
4693 static IOMessage sSystemPower
;
4695 regEntry
= IORegistryEntry::getRegistryRoot();
4697 if (!gIOChosenEntry
)
4698 gIOChosenEntry
= IORegistryEntry::fromPath("/chosen", gIODTPlane
);
4700 IOLockLock(gIOConsoleUsersLock
);
4704 sSystemPower
= systemMessage
;
4706 if ((kIOMessageSystemHasPoweredOn
== systemMessage
) && IOHibernateWasScreenLocked())
4708 locked
= kOSBooleanTrue
;
4710 #endif /* HIBERNATION */
4716 gIOConsoleLoggedIn
= false;
4718 (user
= OSDynamicCast(OSDictionary
, consoleUsers
->getObject(idx
)));
4721 gIOConsoleLoggedIn
|= ((kOSBooleanTrue
== user
->getObject(gIOConsoleSessionOnConsoleKey
))
4722 && (kOSBooleanTrue
== user
->getObject(gIOConsoleSessionLoginDoneKey
)));
4725 num
= OSDynamicCast(OSNumber
, user
->getObject(gIOConsoleSessionScreenLockedTimeKey
));
4728 gIOConsoleLockTime
= num
? num
->unsigned32BitValue() : 0;
4731 if (!gIOConsoleLoggedIn
4732 || (kIOMessageSystemWillSleep
== sSystemPower
)
4733 || (kIOMessageSystemPagingOff
== sSystemPower
))
4735 locked
= kOSBooleanTrue
;
4737 else if (gIOConsoleLockTime
)
4740 clock_usec_t microsecs
;
4742 clock_get_calendar_microtime(&now
, µsecs
);
4743 if (gIOConsoleLockTime
> now
)
4745 AbsoluteTime deadline
;
4746 clock_interval_to_deadline(gIOConsoleLockTime
- now
, kSecondScale
, &deadline
);
4747 thread_call_enter_delayed(gIOConsoleLockCallout
, deadline
);
4751 locked
= kOSBooleanTrue
;
4755 publish
= (consoleUsers
|| (locked
!= regEntry
->getProperty(gIOConsoleLockedKey
)));
4758 regEntry
->setProperty(gIOConsoleLockedKey
, locked
);
4761 regEntry
->setProperty(gIOConsoleUsersKey
, consoleUsers
);
4763 OSIncrementAtomic( &gIOConsoleUsersSeed
);
4769 if (locked
== kOSBooleanTrue
) gIOScreenLockState
= kIOScreenLockLocked
;
4770 else if (gIOConsoleLockTime
) gIOScreenLockState
= kIOScreenLockUnlocked
;
4771 else gIOScreenLockState
= kIOScreenLockNoLock
;
4772 gIOChosenEntry
->setProperty(kIOScreenLockStateKey
, &gIOScreenLockState
, sizeof(gIOScreenLockState
));
4774 #endif /* HIBERNATION */
4776 IOLockUnlock(gIOConsoleUsersLock
);
4780 publishResource( gIOConsoleUsersSeedKey
, gIOConsoleUsersSeedValue
);
4782 MessageClientsContext context
;
4784 context
.service
= getServiceRoot();
4785 context
.type
= kIOMessageConsoleSecurityChange
;
4786 context
.argument
= (void *) regEntry
;
4787 context
.argSize
= 0;
4789 applyToInterestNotifiers(getServiceRoot(), gIOConsoleSecurityInterest
,
4790 &messageClientsApplier
, &context
);
4794 IOReturn
IOResources::setProperties( OSObject
* properties
)
4797 const OSSymbol
* key
;
4798 OSDictionary
* dict
;
4799 OSCollectionIterator
* iter
;
4801 err
= IOUserClient::clientHasPrivilege(current_task(), kIOClientPrivilegeAdministrator
);
4802 if ( kIOReturnSuccess
!= err
)
4805 dict
= OSDynamicCast(OSDictionary
, properties
);
4807 return( kIOReturnBadArgument
);
4809 iter
= OSCollectionIterator::withCollection( dict
);
4811 return( kIOReturnBadArgument
);
4813 while( (key
= OSDynamicCast(OSSymbol
, iter
->getNextObject())))
4815 if (gIOConsoleUsersKey
== key
) do
4817 OSArray
* consoleUsers
;
4818 consoleUsers
= OSDynamicCast(OSArray
, dict
->getObject(key
));
4821 IOService::updateConsoleUsers(consoleUsers
, 0);
4825 publishResource( key
, dict
->getObject(key
) );
4830 return( kIOReturnSuccess
);
4834 * Helpers for matching dictionaries.
4835 * Keys existing in matching are checked in properties.
4836 * Keys may be a string or OSCollection of IOStrings
4839 bool IOService::compareProperty( OSDictionary
* matching
,
4845 value
= matching
->getObject( key
);
4847 ok
= value
->isEqualTo( getProperty( key
));
4855 bool IOService::compareProperty( OSDictionary
* matching
,
4856 const OSString
* key
)
4861 value
= matching
->getObject( key
);
4863 ok
= value
->isEqualTo( getProperty( key
));
4870 bool IOService::compareProperties( OSDictionary
* matching
,
4871 OSCollection
* keys
)
4873 OSCollectionIterator
* iter
;
4874 const OSString
* key
;
4877 if( !matching
|| !keys
)
4880 iter
= OSCollectionIterator::withCollection( keys
);
4883 while( ok
&& (key
= OSDynamicCast( OSString
, iter
->getNextObject())))
4884 ok
= compareProperty( matching
, key
);
4888 keys
->release(); // !! consume a ref !!
4893 /* Helper to add a location matching dict to the table */
4895 OSDictionary
* IOService::addLocation( OSDictionary
* table
)
4897 OSDictionary
* dict
;
4902 dict
= OSDictionary::withCapacity( 1 );
4904 table
->setObject( gIOLocationMatchKey
, dict
);
4912 * Go looking for a provider to match a location dict.
4915 IOService
* IOService::matchLocation( IOService
* /* client */ )
4919 parent
= getProvider();
4922 parent
= parent
->matchLocation( this );
4927 bool IOService::matchInternal(OSDictionary
* table
, uint32_t options
, uint32_t * did
)
4932 IORegistryEntry
* entry
;
4935 bool changesOK
= (0 != (kIOServiceChangesOK
& options
));
4941 count
= table
->getCount();
4943 str
= OSDynamicCast(OSString
, table
->getObject(gIOProviderClassKey
));
4946 match
= ((kIOServiceClassDone
& options
) || (0 != metaCast(str
)));
4948 match
= (0 != metaCast( str
));
4949 if ((kIOServiceClassDone
& options
) && !match
) panic("classDone");
4951 if ((!match
) || (done
== count
)) break;
4954 obj
= table
->getObject( gIONameMatchKey
);
4957 match
= compareNames( obj
, changesOK
? &matched
: 0 );
4959 if( changesOK
&& matched
) {
4960 // leave a hint as to which name matched
4961 table
->setObject( gIONameMatchedKey
, matched
);
4964 if (done
== count
) break;
4967 str
= OSDynamicCast( OSString
, table
->getObject( gIOLocationMatchKey
));
4970 const OSSymbol
* sym
;
4973 sym
= copyLocation();
4975 match
= sym
->isEqualTo( str
);
4978 if ((!match
) || (done
== count
)) break;
4981 obj
= table
->getObject( gIOPropertyMatchKey
);
4984 OSDictionary
* dict
;
4985 OSDictionary
* nextDict
;
4989 dict
= dictionaryWithProperties();
4991 nextDict
= OSDynamicCast( OSDictionary
, obj
);
4995 iter
= OSCollectionIterator::withCollection(
4996 OSDynamicCast(OSCollection
, obj
));
4999 || (iter
&& (0 != (nextDict
= OSDynamicCast(OSDictionary
,
5000 iter
->getNextObject()))))) {
5001 match
= dict
->isEqualTo( nextDict
, nextDict
);
5010 if ((!match
) || (done
== count
)) break;
5013 str
= OSDynamicCast( OSString
, table
->getObject( gIOPathMatchKey
));
5016 entry
= IORegistryEntry::fromPath( str
->getCStringNoCopy() );
5017 match
= (this == entry
);
5020 if ((!match
) || (done
== count
)) break;
5023 num
= OSDynamicCast( OSNumber
, table
->getObject( gIORegistryEntryIDKey
));
5026 match
= (getRegistryEntryID() == num
->unsigned64BitValue());
5027 if ((!match
) || (done
== count
)) break;
5030 num
= OSDynamicCast( OSNumber
, table
->getObject( gIOMatchedServiceCountKey
));
5034 IOService
* service
= 0;
5035 UInt32 serviceCount
= 0;
5038 iter
= getClientIterator();
5040 while( (service
= (IOService
*) iter
->getNextObject())) {
5041 if( kIOServiceInactiveState
& service
->__state
[0])
5043 if( 0 == service
->getProperty( gIOMatchCategoryKey
))
5049 match
= (serviceCount
== num
->unsigned32BitValue());
5050 if ((!match
) || (done
== count
)) break;
5053 #define propMatch(key) \
5054 obj = table->getObject(key); \
5059 prop = copyProperty(key); \
5060 match = obj->isEqualTo(prop); \
5061 if (prop) prop->release(); \
5062 if ((!match) || (done == count)) break; \
5064 propMatch(kIOBSDNameKey
)
5065 propMatch(kIOBSDMajorKey
)
5066 propMatch(kIOBSDMinorKey
)
5067 propMatch(kIOBSDUnitKey
)
5072 if (did
) *did
= done
;
5076 bool IOService::passiveMatch( OSDictionary
* table
, bool changesOK
)
5078 return (matchPassive(table
, changesOK
? kIOServiceChangesOK
: 0));
5081 bool IOService::matchPassive(OSDictionary
* table
, uint32_t options
)
5084 OSDictionary
* nextTable
;
5088 bool matchParent
= false;
5095 OSDictionary
* root
= table
;
5103 count
= table
->getCount();
5104 if (!(kIOServiceInternalDone
& options
))
5106 match
= where
->matchInternal(table
, options
, &done
);
5107 // don't call family if we've done all the entries in the table
5108 if ((!match
) || (done
== count
)) break;
5111 // pass in score from property table
5112 score
= IOServiceObjectOrder( table
, (void *) gIOProbeScoreKey
);
5114 // do family specific matching
5115 match
= where
->matchPropertyTable( table
, &score
);
5119 if( kIOLogMatch
& getDebugFlags( table
))
5120 LOG("%s: family specific matching fails\n", where
->getName());
5125 if (kIOServiceChangesOK
& options
) {
5127 newPri
= OSNumber::withNumber( score
, 32 );
5129 table
->setObject( gIOProbeScoreKey
, newPri
);
5135 matchParent
= false;
5137 nextTable
= OSDynamicCast(OSDictionary
,
5138 table
->getObject( gIOParentMatchKey
));
5140 // look for a matching entry anywhere up to root
5147 table
= OSDynamicCast(OSDictionary
,
5148 table
->getObject( gIOLocationMatchKey
));
5150 // look for a matching entry at matchLocation()
5152 where
= where
->getProvider();
5153 if (where
&& (where
= where
->matchLocation(where
))) continue;
5159 while( matchParent
&& (!match
) && (where
= where
->getProvider()) );
5164 OSSerialize
* s
= OSSerialize::withCapacity(128);
5166 kprintf("parent match 0x%llx, %d,\n%s\n", getRegistryEntryID(), match
, s
->text());
5175 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
5176 UInt32 type
, OSDictionary
* properties
,
5177 IOUserClient
** handler
)
5179 const OSSymbol
*userClientClass
= 0;
5180 IOUserClient
*client
;
5183 if (kIOReturnSuccess
== newUserClient( owningTask
, securityID
, type
, handler
))
5184 return kIOReturnSuccess
;
5186 // First try my own properties for a user client class name
5187 temp
= getProperty(gIOUserClientClassKey
);
5189 if (OSDynamicCast(OSSymbol
, temp
))
5190 userClientClass
= (const OSSymbol
*) temp
;
5191 else if (OSDynamicCast(OSString
, temp
)) {
5192 userClientClass
= OSSymbol::withString((OSString
*) temp
);
5193 if (userClientClass
)
5194 setProperty(kIOUserClientClassKey
,
5195 (OSObject
*) userClientClass
);
5199 // Didn't find one so lets just bomb out now without further ado.
5200 if (!userClientClass
)
5201 return kIOReturnUnsupported
;
5203 // This reference is consumed by the IOServiceOpen call
5204 temp
= OSMetaClass::allocClassWithName(userClientClass
);
5206 return kIOReturnNoMemory
;
5208 if (OSDynamicCast(IOUserClient
, temp
))
5209 client
= (IOUserClient
*) temp
;
5212 return kIOReturnUnsupported
;
5215 if ( !client
->initWithTask(owningTask
, securityID
, type
, properties
) ) {
5217 return kIOReturnBadArgument
;
5220 if ( !client
->attach(this) ) {
5222 return kIOReturnUnsupported
;
5225 if ( !client
->start(this) ) {
5226 client
->detach(this);
5228 return kIOReturnUnsupported
;
5232 return kIOReturnSuccess
;
5235 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
5236 UInt32 type
, IOUserClient
** handler
)
5238 return( kIOReturnUnsupported
);
5241 IOReturn
IOService::requestProbe( IOOptionBits options
)
5243 return( kIOReturnUnsupported
);
5247 * Convert an IOReturn to text. Subclasses which add additional
5248 * IOReturn's should override this method and call
5249 * super::stringFromReturn if the desired value is not found.
5252 const char * IOService::stringFromReturn( IOReturn rtn
)
5254 static const IONamedValue IOReturn_values
[] = {
5255 {kIOReturnSuccess
, "success" },
5256 {kIOReturnError
, "general error" },
5257 {kIOReturnNoMemory
, "memory allocation error" },
5258 {kIOReturnNoResources
, "resource shortage" },
5259 {kIOReturnIPCError
, "Mach IPC failure" },
5260 {kIOReturnNoDevice
, "no such device" },
5261 {kIOReturnNotPrivileged
, "privilege violation" },
5262 {kIOReturnBadArgument
, "invalid argument" },
5263 {kIOReturnLockedRead
, "device is read locked" },
5264 {kIOReturnLockedWrite
, "device is write locked" },
5265 {kIOReturnExclusiveAccess
, "device is exclusive access" },
5266 {kIOReturnBadMessageID
, "bad IPC message ID" },
5267 {kIOReturnUnsupported
, "unsupported function" },
5268 {kIOReturnVMError
, "virtual memory error" },
5269 {kIOReturnInternalError
, "internal driver error" },
5270 {kIOReturnIOError
, "I/O error" },
5271 {kIOReturnCannotLock
, "cannot acquire lock" },
5272 {kIOReturnNotOpen
, "device is not open" },
5273 {kIOReturnNotReadable
, "device is not readable" },
5274 {kIOReturnNotWritable
, "device is not writeable" },
5275 {kIOReturnNotAligned
, "alignment error" },
5276 {kIOReturnBadMedia
, "media error" },
5277 {kIOReturnStillOpen
, "device is still open" },
5278 {kIOReturnRLDError
, "rld failure" },
5279 {kIOReturnDMAError
, "DMA failure" },
5280 {kIOReturnBusy
, "device is busy" },
5281 {kIOReturnTimeout
, "I/O timeout" },
5282 {kIOReturnOffline
, "device is offline" },
5283 {kIOReturnNotReady
, "device is not ready" },
5284 {kIOReturnNotAttached
, "device/channel is not attached" },
5285 {kIOReturnNoChannels
, "no DMA channels available" },
5286 {kIOReturnNoSpace
, "no space for data" },
5287 {kIOReturnPortExists
, "device port already exists" },
5288 {kIOReturnCannotWire
, "cannot wire physical memory" },
5289 {kIOReturnNoInterrupt
, "no interrupt attached" },
5290 {kIOReturnNoFrames
, "no DMA frames enqueued" },
5291 {kIOReturnMessageTooLarge
, "message is too large" },
5292 {kIOReturnNotPermitted
, "operation is not permitted" },
5293 {kIOReturnNoPower
, "device is without power" },
5294 {kIOReturnNoMedia
, "media is not present" },
5295 {kIOReturnUnformattedMedia
, "media is not formatted" },
5296 {kIOReturnUnsupportedMode
, "unsupported mode" },
5297 {kIOReturnUnderrun
, "data underrun" },
5298 {kIOReturnOverrun
, "data overrun" },
5299 {kIOReturnDeviceError
, "device error" },
5300 {kIOReturnNoCompletion
, "no completion routine" },
5301 {kIOReturnAborted
, "operation was aborted" },
5302 {kIOReturnNoBandwidth
, "bus bandwidth would be exceeded" },
5303 {kIOReturnNotResponding
, "device is not responding" },
5304 {kIOReturnInvalid
, "unanticipated driver error" },
5308 return IOFindNameForValue(rtn
, IOReturn_values
);
5312 * Convert an IOReturn to an errno.
5314 int IOService::errnoFromReturn( IOReturn rtn
)
5316 if (unix_err(err_get_code(rtn
)) == rtn
)
5317 return err_get_code(rtn
);
5321 case kIOReturnSuccess
:
5323 case kIOReturnNoMemory
:
5325 case kIOReturnNoDevice
:
5327 case kIOReturnVMError
:
5329 case kIOReturnNotPermitted
:
5331 case kIOReturnNotPrivileged
:
5333 case kIOReturnIOError
:
5335 case kIOReturnNotWritable
:
5337 case kIOReturnBadArgument
:
5339 case kIOReturnUnsupported
:
5343 case kIOReturnNoPower
:
5345 case kIOReturnDeviceError
:
5347 case kIOReturnTimeout
:
5349 case kIOReturnMessageTooLarge
:
5351 case kIOReturnNoSpace
:
5353 case kIOReturnCannotLock
:
5357 case kIOReturnBadMessageID
:
5358 case kIOReturnNoCompletion
:
5359 case kIOReturnNotAligned
:
5361 case kIOReturnNotReady
:
5363 case kIOReturnRLDError
:
5365 case kIOReturnPortExists
:
5366 case kIOReturnStillOpen
:
5368 case kIOReturnExclusiveAccess
:
5369 case kIOReturnLockedRead
:
5370 case kIOReturnLockedWrite
:
5371 case kIOReturnNotOpen
:
5372 case kIOReturnNotReadable
:
5374 case kIOReturnCannotWire
:
5375 case kIOReturnNoResources
:
5377 case kIOReturnAborted
:
5378 case kIOReturnOffline
:
5379 case kIOReturnNotResponding
:
5381 case kIOReturnBadMedia
:
5382 case kIOReturnNoMedia
:
5383 case kIOReturnNotAttached
:
5384 case kIOReturnUnformattedMedia
:
5385 return(ENXIO
); // (media error)
5386 case kIOReturnDMAError
:
5387 case kIOReturnOverrun
:
5388 case kIOReturnUnderrun
:
5389 return(EIO
); // (transfer error)
5390 case kIOReturnNoBandwidth
:
5391 case kIOReturnNoChannels
:
5392 case kIOReturnNoFrames
:
5393 case kIOReturnNoInterrupt
:
5394 return(EIO
); // (hardware error)
5395 case kIOReturnError
:
5396 case kIOReturnInternalError
:
5397 case kIOReturnInvalid
:
5398 return(EIO
); // (generic error)
5399 case kIOReturnIPCError
:
5400 return(EIO
); // (ipc error)
5402 return(EIO
); // (all other errors)
5406 IOReturn
IOService::message( UInt32 type
, IOService
* provider
,
5410 * Generic entry point for calls from the provider. A return value of
5411 * kIOReturnSuccess indicates that the message was received, and where
5412 * applicable, that it was successful.
5415 return kIOReturnUnsupported
;
5422 IOItemCount
IOService::getDeviceMemoryCount( void )
5427 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
5429 count
= array
->getCount();
5436 IODeviceMemory
* IOService::getDeviceMemoryWithIndex( unsigned int index
)
5439 IODeviceMemory
* range
;
5441 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
5443 range
= (IODeviceMemory
*) array
->getObject( index
);
5450 IOMemoryMap
* IOService::mapDeviceMemoryWithIndex( unsigned int index
,
5451 IOOptionBits options
)
5453 IODeviceMemory
* range
;
5456 range
= getDeviceMemoryWithIndex( index
);
5458 map
= range
->map( options
);
5465 OSArray
* IOService::getDeviceMemory( void )
5467 return( OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
)));
5471 void IOService::setDeviceMemory( OSArray
* array
)
5473 setProperty( gIODeviceMemoryKey
, array
);
5477 * For machines where the transfers on an I/O bus can stall because
5478 * the CPU is in an idle mode, These APIs allow a driver to specify
5479 * the maximum bus stall that they can handle. 0 indicates no limit.
5482 setCPUSnoopDelay(UInt32 __unused ns
)
5484 #if defined(__i386__) || defined(__x86_64__)
5485 ml_set_maxsnoop(ns
);
5486 #endif /* defined(__i386__) || defined(__x86_64__) */
5492 #if defined(__i386__) || defined(__x86_64__)
5493 return ml_get_maxsnoop();
5496 #endif /* defined(__i386__) || defined(__x86_64__) */
5499 #if defined(__i386__) || defined(__x86_64__)
5501 requireMaxCpuDelay(IOService
* service
, UInt32 ns
, UInt32 delayType
)
5503 static const UInt kNoReplace
= -1U; // Must be an illegal index
5504 UInt replace
= kNoReplace
;
5505 bool setCpuDelay
= false;
5507 IORecursiveLockLock(sCpuDelayLock
);
5509 UInt count
= sCpuDelayData
->getLength() / sizeof(CpuDelayEntry
);
5510 CpuDelayEntry
*entries
= (CpuDelayEntry
*) sCpuDelayData
->getBytesNoCopy();
5511 IOService
* holder
= NULL
;
5514 const CpuDelayEntry ne
= {service
, ns
, delayType
};
5516 // Set maximum delay.
5517 for (UInt i
= 0; i
< count
; i
++) {
5518 IOService
*thisService
= entries
[i
].fService
;
5519 bool sameType
= (delayType
== entries
[i
].fDelayType
);
5520 if ((service
== thisService
) && sameType
)
5522 else if (!thisService
) {
5523 if (kNoReplace
== replace
)
5526 else if (sameType
) {
5527 const UInt32 thisMax
= entries
[i
].fMaxDelay
;
5531 holder
= thisService
;
5537 if (kNoReplace
== replace
)
5538 sCpuDelayData
->appendBytes(&ne
, sizeof(ne
));
5540 entries
[replace
] = ne
;
5543 ns
= -1U; // Set to max unsigned, i.e. no restriction
5545 for (UInt i
= 0; i
< count
; i
++) {
5546 // Clear a maximum delay.
5547 IOService
*thisService
= entries
[i
].fService
;
5548 if (thisService
&& (delayType
== entries
[i
].fDelayType
)) {
5549 UInt32 thisMax
= entries
[i
].fMaxDelay
;
5550 if (service
== thisService
)
5552 else if (thisMax
< ns
) {
5554 holder
= thisService
;
5559 // Check if entry found
5560 if (kNoReplace
!= replace
) {
5561 entries
[replace
].fService
= 0; // Null the entry
5568 // Must be safe to call from locked context
5569 if (delayType
== kCpuDelayBusStall
)
5571 ml_set_maxbusdelay(ns
);
5573 else if (delayType
== kCpuDelayInterrupt
)
5575 ml_set_maxintdelay(ns
);
5577 sCPULatencyHolder
[delayType
]->setValue(holder
? holder
->getRegistryEntryID() : 0);
5578 sCPULatencySet
[delayType
]->setValue(ns
);
5580 OSArray
* handlers
= sCpuLatencyHandlers
[delayType
];
5582 if (handlers
) for (unsigned int idx
= 0;
5583 (target
= (IOService
*) handlers
->getObject(idx
));
5586 target
->callPlatformFunction(sCPULatencyFunctionName
[delayType
], false,
5587 (void *) (uintptr_t) ns
, holder
,
5592 IORecursiveLockUnlock(sCpuDelayLock
);
5596 setLatencyHandler(UInt32 delayType
, IOService
* target
, bool enable
)
5598 IOReturn result
= kIOReturnNotFound
;
5602 IORecursiveLockLock(sCpuDelayLock
);
5606 if (enable
&& !sCpuLatencyHandlers
[delayType
])
5607 sCpuLatencyHandlers
[delayType
] = OSArray::withCapacity(4);
5608 array
= sCpuLatencyHandlers
[delayType
];
5611 idx
= array
->getNextIndexOfObject(target
, 0);
5616 array
->removeObject(idx
);
5617 result
= kIOReturnSuccess
;
5623 result
= kIOReturnExclusiveAccess
;
5626 array
->setObject(target
);
5628 UInt count
= sCpuDelayData
->getLength() / sizeof(CpuDelayEntry
);
5629 CpuDelayEntry
*entries
= (CpuDelayEntry
*) sCpuDelayData
->getBytesNoCopy();
5630 UInt32 ns
= -1U; // Set to max unsigned, i.e. no restriction
5631 IOService
* holder
= NULL
;
5633 for (UInt i
= 0; i
< count
; i
++) {
5634 if (entries
[i
].fService
5635 && (delayType
== entries
[i
].fDelayType
)
5636 && (entries
[i
].fMaxDelay
< ns
)) {
5637 ns
= entries
[i
].fMaxDelay
;
5638 holder
= entries
[i
].fService
;
5641 target
->callPlatformFunction(sCPULatencyFunctionName
[delayType
], false,
5642 (void *) (uintptr_t) ns
, holder
,
5644 result
= kIOReturnSuccess
;
5649 IORecursiveLockUnlock(sCpuDelayLock
);
5654 #endif /* defined(__i386__) || defined(__x86_64__) */
5657 requireMaxBusStall(UInt32 __unused ns
)
5659 #if defined(__i386__) || defined(__x86_64__)
5660 requireMaxCpuDelay(this, ns
, kCpuDelayBusStall
);
5665 requireMaxInterruptDelay(uint32_t __unused ns
)
5667 #if defined(__i386__) || defined(__x86_64__)
5668 requireMaxCpuDelay(this, ns
, kCpuDelayInterrupt
);
5676 IOReturn
IOService::resolveInterrupt(IOService
*nub
, int source
)
5678 IOInterruptController
*interruptController
;
5681 OSSymbol
*interruptControllerName
;
5683 IOInterruptSource
*interruptSources
;
5685 // Get the parents list from the nub.
5686 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptControllersKey
));
5687 if (array
== 0) return kIOReturnNoResources
;
5689 // Allocate space for the IOInterruptSources if needed... then return early.
5690 if (nub
->_interruptSources
== 0) {
5691 numSources
= array
->getCount();
5692 interruptSources
= (IOInterruptSource
*)IOMalloc(numSources
* sizeof(IOInterruptSource
));
5693 if (interruptSources
== 0) return kIOReturnNoMemory
;
5695 bzero(interruptSources
, numSources
* sizeof(IOInterruptSource
));
5697 nub
->_numInterruptSources
= numSources
;
5698 nub
->_interruptSources
= interruptSources
;
5699 return kIOReturnSuccess
;
5702 interruptControllerName
= OSDynamicCast(OSSymbol
,array
->getObject(source
));
5703 if (interruptControllerName
== 0) return kIOReturnNoResources
;
5705 interruptController
= getPlatform()->lookUpInterruptController(interruptControllerName
);
5706 if (interruptController
== 0) return kIOReturnNoResources
;
5708 // Get the interrupt numbers from the nub.
5709 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptSpecifiersKey
));
5710 if (array
== 0) return kIOReturnNoResources
;
5711 data
= OSDynamicCast(OSData
, array
->getObject(source
));
5712 if (data
== 0) return kIOReturnNoResources
;
5714 // Set the interruptController and interruptSource in the nub's table.
5715 interruptSources
= nub
->_interruptSources
;
5716 interruptSources
[source
].interruptController
= interruptController
;
5717 interruptSources
[source
].vectorData
= data
;
5719 return kIOReturnSuccess
;
5722 IOReturn
IOService::lookupInterrupt(int source
, bool resolve
, IOInterruptController
**interruptController
)
5726 /* Make sure the _interruptSources are set */
5727 if (_interruptSources
== 0) {
5728 ret
= resolveInterrupt(this, source
);
5729 if (ret
!= kIOReturnSuccess
) return ret
;
5732 /* Make sure the local source number is valid */
5733 if ((source
< 0) || (source
>= _numInterruptSources
))
5734 return kIOReturnNoInterrupt
;
5736 /* Look up the contoller for the local source */
5737 *interruptController
= _interruptSources
[source
].interruptController
;
5739 if (*interruptController
== NULL
) {
5740 if (!resolve
) return kIOReturnNoInterrupt
;
5742 /* Try to reslove the interrupt */
5743 ret
= resolveInterrupt(this, source
);
5744 if (ret
!= kIOReturnSuccess
) return ret
;
5746 *interruptController
= _interruptSources
[source
].interruptController
;
5749 return kIOReturnSuccess
;
5752 IOReturn
IOService::registerInterrupt(int source
, OSObject
*target
,
5753 IOInterruptAction handler
,
5756 IOInterruptController
*interruptController
;
5759 ret
= lookupInterrupt(source
, true, &interruptController
);
5760 if (ret
!= kIOReturnSuccess
) return ret
;
5762 /* Register the source */
5763 return interruptController
->registerInterrupt(this, source
, target
,
5764 (IOInterruptHandler
)handler
,
5768 IOReturn
IOService::unregisterInterrupt(int source
)
5770 IOInterruptController
*interruptController
;
5773 ret
= lookupInterrupt(source
, false, &interruptController
);
5774 if (ret
!= kIOReturnSuccess
) return ret
;
5776 /* Unregister the source */
5777 return interruptController
->unregisterInterrupt(this, source
);
5780 IOReturn
IOService::addInterruptStatistics(IOInterruptAccountingData
* statistics
, int source
)
5782 IOReportLegend
* legend
= NULL
;
5783 IOInterruptAccountingData
* oldValue
= NULL
;
5784 IOInterruptAccountingReporter
* newArray
= NULL
;
5785 int newArraySize
= 0;
5789 return kIOReturnBadArgument
;
5793 * We support statistics on a maximum of 256 interrupts per nub; if a nub
5794 * has more than 256 interrupt specifiers associated with it, and tries
5795 * to register a high interrupt index with interrupt accounting, panic.
5796 * Having more than 256 interrupts associated with a single nub is
5797 * probably a sign that something fishy is going on.
5799 if (source
> IA_INDEX_MAX
) {
5800 panic("addInterruptStatistics called for an excessively large index (%d)", source
);
5804 * TODO: This is ugly (wrapping a lock around an allocation). I'm only
5805 * leaving it as is because the likelihood of contention where we are
5806 * actually growing the array is minimal (we would realistically need
5807 * to be starting a driver for the first time, with an IOReporting
5808 * client already in place). Nonetheless, cleanup that can be done
5809 * to adhere to best practices; it'll make the code more complicated,
5812 IOLockLock(reserved
->interruptStatisticsLock
);
5815 * Lazily allocate the statistics array.
5817 if (!reserved
->interruptStatisticsArray
) {
5818 reserved
->interruptStatisticsArray
= IONew(IOInterruptAccountingReporter
, 1);
5819 assert(reserved
->interruptStatisticsArray
);
5820 reserved
->interruptStatisticsArrayCount
= 1;
5821 bzero(reserved
->interruptStatisticsArray
, sizeof(*reserved
->interruptStatisticsArray
));
5824 if (source
>= reserved
->interruptStatisticsArrayCount
) {
5826 * We're still within the range of supported indices, but we are out
5827 * of space in the current array. Do a nasty realloc (because
5828 * IORealloc isn't a thing) here. We'll double the size with each
5831 * Yes, the "next power of 2" could be more efficient; but this will
5832 * be invoked incredibly rarely. Who cares.
5834 newArraySize
= (reserved
->interruptStatisticsArrayCount
<< 1);
5836 while (newArraySize
<= source
)
5837 newArraySize
= (newArraySize
<< 1);
5838 newArray
= IONew(IOInterruptAccountingReporter
, newArraySize
);
5843 * TODO: This even zeroes the memory it is about to overwrite.
5844 * Shameful; fix it. Not particularly high impact, however.
5846 bzero(newArray
, newArraySize
* sizeof(*newArray
));
5847 memcpy(newArray
, reserved
->interruptStatisticsArray
, reserved
->interruptStatisticsArrayCount
* sizeof(*newArray
));
5848 IODelete(reserved
->interruptStatisticsArray
, IOInterruptAccountingReporter
, reserved
->interruptStatisticsArrayCount
);
5849 reserved
->interruptStatisticsArray
= newArray
;
5850 reserved
->interruptStatisticsArrayCount
= newArraySize
;
5853 if (!reserved
->interruptStatisticsArray
[source
].reporter
) {
5855 * We don't have a reporter associated with this index yet, so we
5856 * need to create one.
5859 * TODO: Some statistics do in fact have common units (time); should this be
5860 * split into separate reporters to communicate this?
5862 reserved
->interruptStatisticsArray
[source
].reporter
= IOSimpleReporter::with(this, kIOReportCategoryInterrupt
, kIOReportUnitNone
);
5865 * Each statistic is given an identifier based on the interrupt index (which
5866 * should be unique relative to any single nub) and the statistic involved.
5867 * We should now have a sane (small and positive) index, so start
5868 * constructing the channels for statistics.
5870 for (i
= 0; i
< IA_NUM_INTERRUPT_ACCOUNTING_STATISTICS
; i
++) {
5872 * TODO: Currently, this does not add channels for disabled statistics.
5873 * Will this be confusing for clients? If so, we should just add the
5874 * channels; we can avoid updating the channels even if they exist.
5876 if (IA_GET_STATISTIC_ENABLED(i
))
5877 reserved
->interruptStatisticsArray
[source
].reporter
->addChannel(IA_GET_CHANNEL_ID(source
, i
), kInterruptAccountingStatisticNameArray
[i
]);
5881 * We now need to add the legend for this reporter to the registry.
5883 legend
= IOReportLegend::with(OSDynamicCast(OSArray
, getProperty(kIOReportLegendKey
)));
5885 if ((source
>= IA_MAX_SUBGROUP_NAME
) || (source
< 0)) {
5887 * Either we're using a nonsensical index (should never happen), or the
5888 * index is larger than anticipated (may happen, almost certainly won't).
5889 * This may move to live generation of the names in the future, but for
5890 * now, point both cases to a generic subgroup name (this will confuse
5891 * clients, unfortunately).
5893 legend
->addReporterLegend(reserved
->interruptStatisticsArray
[source
].reporter
, kInterruptAccountingGroupName
, kInterruptAccountingGenericSubgroupName
);
5895 legend
->addReporterLegend(reserved
->interruptStatisticsArray
[source
].reporter
, kInterruptAccountingGroupName
, kInterruptAccountingSubgroupNames
[source
]);
5898 setProperty(kIOReportLegendKey
, legend
->getLegend());
5902 * TODO: Is this a good idea? Probably not; my assumption is it opts
5903 * all entities who register interrupts into public disclosure of all
5904 * IOReporting channels. Unfortunately, this appears to be as fine
5907 setProperty(kIOReportLegendPublicKey
, true);
5911 * Don't stomp existing entries. If we are about to, panic; this
5912 * probably means we failed to tear down our old interrupt source
5915 oldValue
= reserved
->interruptStatisticsArray
[source
].statistics
;
5918 panic("addInterruptStatistics call for index %d would have clobbered existing statistics", source
);
5921 reserved
->interruptStatisticsArray
[source
].statistics
= statistics
;
5924 * Inherit the reporter values for each statistic. The target may
5925 * be torn down as part of the runtime of the service (especially
5926 * for sleep/wake), so we inherit in order to avoid having values
5927 * reset for no apparent reason. Our statistics are ultimately
5928 * tied to the index and the sevice, not to an individual target,
5929 * so we should maintain them accordingly.
5931 interruptAccountingDataInheritChannels(reserved
->interruptStatisticsArray
[source
].statistics
, reserved
->interruptStatisticsArray
[source
].reporter
);
5933 IOLockUnlock(reserved
->interruptStatisticsLock
);
5935 return kIOReturnSuccess
;
5938 IOReturn
IOService::removeInterruptStatistics(int source
)
5940 IOInterruptAccountingData
* value
= NULL
;
5943 return kIOReturnBadArgument
;
5946 IOLockLock(reserved
->interruptStatisticsLock
);
5949 * We dynamically grow the statistics array, so an excessively
5950 * large index value has NEVER been registered. This either
5951 * means our cap on the array size is too small (unlikely), or
5952 * that we have been passed a corrupt index (this must be passed
5953 * the plain index into the interrupt specifier list).
5955 if (source
>= reserved
->interruptStatisticsArrayCount
) {
5956 panic("removeInterruptStatistics called for index %d, which was never registered", source
);
5959 assert(reserved
->interruptStatisticsArray
);
5962 * If there is no existing entry, we are most likely trying to
5963 * free an interrupt owner twice, or we have corrupted the
5966 value
= reserved
->interruptStatisticsArray
[source
].statistics
;
5969 panic("removeInterruptStatistics called for empty index %d", source
);
5973 * We update the statistics, so that any delta with the reporter
5974 * state is not lost.
5976 interruptAccountingDataUpdateChannels(reserved
->interruptStatisticsArray
[source
].statistics
, reserved
->interruptStatisticsArray
[source
].reporter
);
5977 reserved
->interruptStatisticsArray
[source
].statistics
= NULL
;
5978 IOLockUnlock(reserved
->interruptStatisticsLock
);
5980 return kIOReturnSuccess
;
5983 IOReturn
IOService::getInterruptType(int source
, int *interruptType
)
5985 IOInterruptController
*interruptController
;
5988 ret
= lookupInterrupt(source
, true, &interruptController
);
5989 if (ret
!= kIOReturnSuccess
) return ret
;
5991 /* Return the type */
5992 return interruptController
->getInterruptType(this, source
, interruptType
);
5995 IOReturn
IOService::enableInterrupt(int source
)
5997 IOInterruptController
*interruptController
;
6000 ret
= lookupInterrupt(source
, false, &interruptController
);
6001 if (ret
!= kIOReturnSuccess
) return ret
;
6003 /* Enable the source */
6004 return interruptController
->enableInterrupt(this, source
);
6007 IOReturn
IOService::disableInterrupt(int source
)
6009 IOInterruptController
*interruptController
;
6012 ret
= lookupInterrupt(source
, false, &interruptController
);
6013 if (ret
!= kIOReturnSuccess
) return ret
;
6015 /* Disable the source */
6016 return interruptController
->disableInterrupt(this, source
);
6019 IOReturn
IOService::causeInterrupt(int source
)
6021 IOInterruptController
*interruptController
;
6024 ret
= lookupInterrupt(source
, false, &interruptController
);
6025 if (ret
!= kIOReturnSuccess
) return ret
;
6027 /* Cause an interrupt for the source */
6028 return interruptController
->causeInterrupt(this, source
);
6031 IOReturn
IOService::configureReport(IOReportChannelList
*channelList
,
6032 IOReportConfigureAction action
,
6038 for (cnt
= 0; cnt
< channelList
->nchannels
; cnt
++) {
6039 if ( channelList
->channels
[cnt
].channel_id
== kPMPowerStatesChID
) {
6040 if (pwrMgt
) configurePowerStatesReport(action
, result
);
6041 else return kIOReturnUnsupported
;
6043 else if ( channelList
->channels
[cnt
].channel_id
== kPMCurrStateChID
) {
6044 if (pwrMgt
) configureSimplePowerReport(action
, result
);
6045 else return kIOReturnUnsupported
;
6049 IOLockLock(reserved
->interruptStatisticsLock
);
6051 /* The array count is signed (because the interrupt indices are signed), hence the cast */
6052 for (cnt
= 0; cnt
< (unsigned) reserved
->interruptStatisticsArrayCount
; cnt
++) {
6053 if (reserved
->interruptStatisticsArray
[cnt
].reporter
) {
6055 * If the reporter is currently associated with the statistics
6056 * for an event source, we may need to update the reporter.
6058 if (reserved
->interruptStatisticsArray
[cnt
].statistics
)
6059 interruptAccountingDataUpdateChannels(reserved
->interruptStatisticsArray
[cnt
].statistics
, reserved
->interruptStatisticsArray
[cnt
].reporter
);
6061 reserved
->interruptStatisticsArray
[cnt
].reporter
->configureReport(channelList
, action
, result
, destination
);
6065 IOLockUnlock(reserved
->interruptStatisticsLock
);
6067 return kIOReturnSuccess
;
6070 IOReturn
IOService::updateReport(IOReportChannelList
*channelList
,
6071 IOReportUpdateAction action
,
6077 for (cnt
= 0; cnt
< channelList
->nchannels
; cnt
++) {
6078 if ( channelList
->channels
[cnt
].channel_id
== kPMPowerStatesChID
) {
6079 if (pwrMgt
) updatePowerStatesReport(action
, result
, destination
);
6080 else return kIOReturnUnsupported
;
6082 else if ( channelList
->channels
[cnt
].channel_id
== kPMCurrStateChID
) {
6083 if (pwrMgt
) updateSimplePowerReport(action
, result
, destination
);
6084 else return kIOReturnUnsupported
;
6088 IOLockLock(reserved
->interruptStatisticsLock
);
6090 /* The array count is signed (because the interrupt indices are signed), hence the cast */
6091 for (cnt
= 0; cnt
< (unsigned) reserved
->interruptStatisticsArrayCount
; cnt
++) {
6092 if (reserved
->interruptStatisticsArray
[cnt
].reporter
) {
6094 * If the reporter is currently associated with the statistics
6095 * for an event source, we need to update the reporter.
6097 if (reserved
->interruptStatisticsArray
[cnt
].statistics
)
6098 interruptAccountingDataUpdateChannels(reserved
->interruptStatisticsArray
[cnt
].statistics
, reserved
->interruptStatisticsArray
[cnt
].reporter
);
6100 reserved
->interruptStatisticsArray
[cnt
].reporter
->updateReport(channelList
, action
, result
, destination
);
6104 IOLockUnlock(reserved
->interruptStatisticsLock
);
6106 return kIOReturnSuccess
;
6109 uint64_t IOService::getAuthorizationID( void )
6111 return reserved
->authorizationID
;
6114 IOReturn
IOService::setAuthorizationID( uint64_t authorizationID
)
6116 OSObject
* entitlement
;
6119 entitlement
= IOUserClient::copyClientEntitlement( current_task( ), "com.apple.private.iokit.IOServiceSetAuthorizationID" );
6123 if ( entitlement
== kOSBooleanTrue
)
6125 reserved
->authorizationID
= authorizationID
;
6127 status
= kIOReturnSuccess
;
6131 status
= kIOReturnNotPrivileged
;
6134 entitlement
->release( );
6138 status
= kIOReturnNotPrivileged
;
6145 OSMetaClassDefineReservedUsed(IOService
, 0);
6146 OSMetaClassDefineReservedUsed(IOService
, 1);
6147 OSMetaClassDefineReservedUnused(IOService
, 2);
6148 OSMetaClassDefineReservedUnused(IOService
, 3);
6149 OSMetaClassDefineReservedUnused(IOService
, 4);
6150 OSMetaClassDefineReservedUnused(IOService
, 5);
6151 OSMetaClassDefineReservedUnused(IOService
, 6);
6152 OSMetaClassDefineReservedUnused(IOService
, 7);
6154 OSMetaClassDefineReservedUsed(IOService
, 0);
6155 OSMetaClassDefineReservedUsed(IOService
, 1);
6156 OSMetaClassDefineReservedUsed(IOService
, 2);
6157 OSMetaClassDefineReservedUsed(IOService
, 3);
6158 OSMetaClassDefineReservedUsed(IOService
, 4);
6159 OSMetaClassDefineReservedUsed(IOService
, 5);
6160 OSMetaClassDefineReservedUsed(IOService
, 6);
6161 OSMetaClassDefineReservedUsed(IOService
, 7);
6163 OSMetaClassDefineReservedUnused(IOService
, 8);
6164 OSMetaClassDefineReservedUnused(IOService
, 9);
6165 OSMetaClassDefineReservedUnused(IOService
, 10);
6166 OSMetaClassDefineReservedUnused(IOService
, 11);
6167 OSMetaClassDefineReservedUnused(IOService
, 12);
6168 OSMetaClassDefineReservedUnused(IOService
, 13);
6169 OSMetaClassDefineReservedUnused(IOService
, 14);
6170 OSMetaClassDefineReservedUnused(IOService
, 15);
6171 OSMetaClassDefineReservedUnused(IOService
, 16);
6172 OSMetaClassDefineReservedUnused(IOService
, 17);
6173 OSMetaClassDefineReservedUnused(IOService
, 18);
6174 OSMetaClassDefineReservedUnused(IOService
, 19);
6175 OSMetaClassDefineReservedUnused(IOService
, 20);
6176 OSMetaClassDefineReservedUnused(IOService
, 21);
6177 OSMetaClassDefineReservedUnused(IOService
, 22);
6178 OSMetaClassDefineReservedUnused(IOService
, 23);
6179 OSMetaClassDefineReservedUnused(IOService
, 24);
6180 OSMetaClassDefineReservedUnused(IOService
, 25);
6181 OSMetaClassDefineReservedUnused(IOService
, 26);
6182 OSMetaClassDefineReservedUnused(IOService
, 27);
6183 OSMetaClassDefineReservedUnused(IOService
, 28);
6184 OSMetaClassDefineReservedUnused(IOService
, 29);
6185 OSMetaClassDefineReservedUnused(IOService
, 30);
6186 OSMetaClassDefineReservedUnused(IOService
, 31);
6187 OSMetaClassDefineReservedUnused(IOService
, 32);
6188 OSMetaClassDefineReservedUnused(IOService
, 33);
6189 OSMetaClassDefineReservedUnused(IOService
, 34);
6190 OSMetaClassDefineReservedUnused(IOService
, 35);
6191 OSMetaClassDefineReservedUnused(IOService
, 36);
6192 OSMetaClassDefineReservedUnused(IOService
, 37);
6193 OSMetaClassDefineReservedUnused(IOService
, 38);
6194 OSMetaClassDefineReservedUnused(IOService
, 39);
6195 OSMetaClassDefineReservedUnused(IOService
, 40);
6196 OSMetaClassDefineReservedUnused(IOService
, 41);
6197 OSMetaClassDefineReservedUnused(IOService
, 42);
6198 OSMetaClassDefineReservedUnused(IOService
, 43);
6199 OSMetaClassDefineReservedUnused(IOService
, 44);
6200 OSMetaClassDefineReservedUnused(IOService
, 45);
6201 OSMetaClassDefineReservedUnused(IOService
, 46);
6202 OSMetaClassDefineReservedUnused(IOService
, 47);