2 * Copyright (c) 1998-2009 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/IODeviceMemory.h>
39 #include <IOKit/IOInterrupts.h>
40 #include <IOKit/IOInterruptController.h>
41 #include <IOKit/IOPlatformExpert.h>
42 #include <IOKit/IOMessage.h>
43 #include <IOKit/IOLib.h>
44 #include <IOKit/IOKitKeysPrivate.h>
45 #include <IOKit/IOBSD.h>
46 #include <IOKit/IOUserClient.h>
47 #include <IOKit/IOWorkLoop.h>
48 #include <IOKit/IOTimeStamp.h>
49 #include <mach/sync_policy.h>
50 #include <IOKit/assert.h>
51 #include <sys/errno.h>
53 #include <machine/pal_routines.h>
58 #include "IOServicePrivate.h"
59 #include "IOKitKernelInternal.h"
61 // take lockForArbitration before LOCKNOTIFY
63 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
65 #define super IORegistryEntry
67 OSDefineMetaClassAndStructors(IOService
, IORegistryEntry
)
69 OSDefineMetaClassAndStructors(_IOServiceNotifier
, IONotifier
)
71 OSDefineMetaClassAndStructors(_IOServiceInterestNotifier
, IONotifier
)
73 OSDefineMetaClassAndStructors(_IOConfigThread
, OSObject
)
75 OSDefineMetaClassAndStructors(_IOServiceJob
, OSObject
)
77 OSDefineMetaClassAndStructors(IOResources
, IOService
)
79 OSDefineMetaClassAndStructors(_IOOpenServiceIterator
, OSIterator
)
81 OSDefineMetaClassAndAbstractStructors(IONotifier
, OSObject
)
83 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
85 static IOPlatformExpert
* gIOPlatform
;
86 static class IOPMrootDomain
* gIOPMRootDomain
;
87 const IORegistryPlane
* gIOServicePlane
;
88 const IORegistryPlane
* gIOPowerPlane
;
89 const OSSymbol
* gIODeviceMemoryKey
;
90 const OSSymbol
* gIOInterruptControllersKey
;
91 const OSSymbol
* gIOInterruptSpecifiersKey
;
93 const OSSymbol
* gIOResourcesKey
;
94 const OSSymbol
* gIOResourceMatchKey
;
95 const OSSymbol
* gIOProviderClassKey
;
96 const OSSymbol
* gIONameMatchKey
;
97 const OSSymbol
* gIONameMatchedKey
;
98 const OSSymbol
* gIOPropertyMatchKey
;
99 const OSSymbol
* gIOLocationMatchKey
;
100 const OSSymbol
* gIOParentMatchKey
;
101 const OSSymbol
* gIOPathMatchKey
;
102 const OSSymbol
* gIOMatchCategoryKey
;
103 const OSSymbol
* gIODefaultMatchCategoryKey
;
104 const OSSymbol
* gIOMatchedServiceCountKey
;
106 const OSSymbol
* gIOMapperIDKey
;
107 const OSSymbol
* gIOUserClientClassKey
;
108 const OSSymbol
* gIOKitDebugKey
;
110 const OSSymbol
* gIOCommandPoolSizeKey
;
112 const OSSymbol
* gIOConsoleLockedKey
;
113 const OSSymbol
* gIOConsoleUsersKey
;
114 const OSSymbol
* gIOConsoleSessionUIDKey
;
115 const OSSymbol
* gIOConsoleSessionAuditIDKey
;
116 const OSSymbol
* gIOConsoleUsersSeedKey
;
117 const OSSymbol
* gIOConsoleSessionOnConsoleKey
;
118 const OSSymbol
* gIOConsoleSessionSecureInputPIDKey
;
119 const OSSymbol
* gIOConsoleSessionScreenLockedTimeKey
;
121 static clock_sec_t gIOConsoleLockTime
;
123 static int gIOResourceGenerationCount
;
125 const OSSymbol
* gIOServiceKey
;
126 const OSSymbol
* gIOPublishNotification
;
127 const OSSymbol
* gIOFirstPublishNotification
;
128 const OSSymbol
* gIOMatchedNotification
;
129 const OSSymbol
* gIOFirstMatchNotification
;
130 const OSSymbol
* gIOTerminatedNotification
;
132 const OSSymbol
* gIOGeneralInterest
;
133 const OSSymbol
* gIOBusyInterest
;
134 const OSSymbol
* gIOAppPowerStateInterest
;
135 const OSSymbol
* gIOPriorityPowerStateInterest
;
136 const OSSymbol
* gIOConsoleSecurityInterest
;
138 static OSDictionary
* gNotifications
;
139 static IORecursiveLock
* gNotificationLock
;
141 static IOService
* gIOResources
;
142 static IOService
* gIOServiceRoot
;
144 static OSOrderedSet
* gJobs
;
145 static semaphore_port_t gJobsSemaphore
;
146 static IOLock
* gJobsLock
;
147 static int gOutstandingJobs
;
148 static int gNumConfigThreads
;
149 static int gNumWaitingThreads
;
150 static IOLock
* gIOServiceBusyLock
;
152 static thread_t gIOTerminateThread
;
153 static UInt32 gIOTerminateWork
;
154 static OSArray
* gIOTerminatePhase2List
;
155 static OSArray
* gIOStopList
;
156 static OSArray
* gIOStopProviderList
;
157 static OSArray
* gIOFinalizeList
;
159 static SInt32 gIOConsoleUsersSeed
;
160 static OSData
* gIOConsoleUsersSeedValue
;
162 extern const OSSymbol
* gIODTPHandleKey
;
164 const OSSymbol
* gIOPlatformSleepActionKey
;
165 const OSSymbol
* gIOPlatformWakeActionKey
;
166 const OSSymbol
* gIOPlatformQuiesceActionKey
;
167 const OSSymbol
* gIOPlatformActiveActionKey
;
169 const OSSymbol
* gIOPlatformFunctionHandlerSet
;
171 static IOLock
* gIOConsoleUsersLock
;
172 static thread_call_t gIOConsoleLockCallout
;
174 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
176 #define LOCKREADNOTIFY() \
177 IORecursiveLockLock( gNotificationLock )
178 #define LOCKWRITENOTIFY() \
179 IORecursiveLockLock( gNotificationLock )
180 #define LOCKWRITE2READNOTIFY()
181 #define UNLOCKNOTIFY() \
182 IORecursiveLockUnlock( gNotificationLock )
183 #define SLEEPNOTIFY(event) \
184 IORecursiveLockSleep( gNotificationLock, (void *)(event), THREAD_UNINT )
185 #define SLEEPNOTIFYTO(event, deadline) \
186 IORecursiveLockSleepDeadline( gNotificationLock, (void *)(event), deadline, THREAD_UNINT )
187 #define WAKEUPNOTIFY(event) \
188 IORecursiveLockWakeup( gNotificationLock, (void *)(event), /* wake one */ false )
190 #define randomDelay() \
191 int del = read_processor_clock(); \
192 del = (((int)IOThreadSelf()) ^ del ^ (del >> 10)) & 0x3ff; \
195 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
197 #define queue_element(entry, element, type, field) do { \
198 vm_address_t __ele = (vm_address_t) (entry); \
199 __ele -= -4 + ((size_t)(&((type) 4)->field)); \
200 (element) = (type) __ele; \
203 #define iterqueue(que, elt) \
204 for (queue_entry_t elt = queue_first(que); \
205 !queue_end(que, elt); \
206 elt = queue_next(elt))
208 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
210 struct ArbitrationLockQueueElement
{
219 static queue_head_t gArbitrationLockQueueActive
;
220 static queue_head_t gArbitrationLockQueueWaiting
;
221 static queue_head_t gArbitrationLockQueueFree
;
222 static IOLock
* gArbitrationLockQueueLock
;
224 bool IOService::isInactive( void ) const
225 { return( 0 != (kIOServiceInactiveState
& getState())); }
228 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
230 #if defined(__i386__) || defined(__x86_64__)
232 // Only used by the intel implementation of
233 // IOService::requireMaxBusStall(UInt32 ns)
234 // IOService::requireMaxInterruptDelay(uint32_t ns)
237 IOService
* fService
;
243 kCpuDelayBusStall
, kCpuDelayInterrupt
,
247 static OSData
*sCpuDelayData
= OSData::withCapacity(8 * sizeof(CpuDelayEntry
));
248 static IORecursiveLock
*sCpuDelayLock
= IORecursiveLockAlloc();
249 static OSArray
*sCpuLatencyHandlers
[kCpuNumDelayTypes
];
250 const OSSymbol
*sCPULatencyFunctionName
[kCpuNumDelayTypes
];
253 requireMaxCpuDelay(IOService
* service
, UInt32 ns
, UInt32 delayType
);
255 setLatencyHandler(UInt32 delayType
, IOService
* target
, bool enable
);
257 #endif /* defined(__i386__) || defined(__x86_64__) */
259 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
261 void IOService::initialize( void )
265 gIOServicePlane
= IORegistryEntry::makePlane( kIOServicePlane
);
266 gIOPowerPlane
= IORegistryEntry::makePlane( kIOPowerPlane
);
268 gIOProviderClassKey
= OSSymbol::withCStringNoCopy( kIOProviderClassKey
);
269 gIONameMatchKey
= OSSymbol::withCStringNoCopy( kIONameMatchKey
);
270 gIONameMatchedKey
= OSSymbol::withCStringNoCopy( kIONameMatchedKey
);
271 gIOPropertyMatchKey
= OSSymbol::withCStringNoCopy( kIOPropertyMatchKey
);
272 gIOPathMatchKey
= OSSymbol::withCStringNoCopy( kIOPathMatchKey
);
273 gIOLocationMatchKey
= OSSymbol::withCStringNoCopy( kIOLocationMatchKey
);
274 gIOParentMatchKey
= OSSymbol::withCStringNoCopy( kIOParentMatchKey
);
276 gIOMatchCategoryKey
= OSSymbol::withCStringNoCopy( kIOMatchCategoryKey
);
277 gIODefaultMatchCategoryKey
= OSSymbol::withCStringNoCopy(
278 kIODefaultMatchCategoryKey
);
279 gIOMatchedServiceCountKey
= OSSymbol::withCStringNoCopy(
280 kIOMatchedServiceCountKey
);
282 gIOUserClientClassKey
= OSSymbol::withCStringNoCopy( kIOUserClientClassKey
);
284 gIOResourcesKey
= OSSymbol::withCStringNoCopy( kIOResourcesClass
);
285 gIOResourceMatchKey
= OSSymbol::withCStringNoCopy( kIOResourceMatchKey
);
287 gIODeviceMemoryKey
= OSSymbol::withCStringNoCopy( "IODeviceMemory" );
288 gIOInterruptControllersKey
289 = OSSymbol::withCStringNoCopy("IOInterruptControllers");
290 gIOInterruptSpecifiersKey
291 = OSSymbol::withCStringNoCopy("IOInterruptSpecifiers");
293 gIOMapperIDKey
= OSSymbol::withCStringNoCopy(kIOMapperIDKey
);
295 gIOKitDebugKey
= OSSymbol::withCStringNoCopy( kIOKitDebugKey
);
297 gIOCommandPoolSizeKey
= OSSymbol::withCStringNoCopy( kIOCommandPoolSizeKey
);
299 gIOGeneralInterest
= OSSymbol::withCStringNoCopy( kIOGeneralInterest
);
300 gIOBusyInterest
= OSSymbol::withCStringNoCopy( kIOBusyInterest
);
301 gIOAppPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOAppPowerStateInterest
);
302 gIOPriorityPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOPriorityPowerStateInterest
);
303 gIOConsoleSecurityInterest
= OSSymbol::withCStringNoCopy( kIOConsoleSecurityInterest
);
305 gNotifications
= OSDictionary::withCapacity( 1 );
306 gIOPublishNotification
= OSSymbol::withCStringNoCopy(
307 kIOPublishNotification
);
308 gIOFirstPublishNotification
= OSSymbol::withCStringNoCopy(
309 kIOFirstPublishNotification
);
310 gIOMatchedNotification
= OSSymbol::withCStringNoCopy(
311 kIOMatchedNotification
);
312 gIOFirstMatchNotification
= OSSymbol::withCStringNoCopy(
313 kIOFirstMatchNotification
);
314 gIOTerminatedNotification
= OSSymbol::withCStringNoCopy(
315 kIOTerminatedNotification
);
316 gIOServiceKey
= OSSymbol::withCStringNoCopy( kIOServiceClass
);
318 gIOConsoleLockedKey
= OSSymbol::withCStringNoCopy( kIOConsoleLockedKey
);
319 gIOConsoleUsersKey
= OSSymbol::withCStringNoCopy( kIOConsoleUsersKey
);
320 gIOConsoleSessionUIDKey
= OSSymbol::withCStringNoCopy( kIOConsoleSessionUIDKey
);
321 gIOConsoleSessionAuditIDKey
= OSSymbol::withCStringNoCopy( kIOConsoleSessionAuditIDKey
);
323 gIOConsoleUsersSeedKey
= OSSymbol::withCStringNoCopy(kIOConsoleUsersSeedKey
);
324 gIOConsoleSessionOnConsoleKey
= OSSymbol::withCStringNoCopy(kIOConsoleSessionOnConsoleKey
);
325 gIOConsoleSessionSecureInputPIDKey
= OSSymbol::withCStringNoCopy(kIOConsoleSessionSecureInputPIDKey
);
326 gIOConsoleSessionScreenLockedTimeKey
= OSSymbol::withCStringNoCopy(kIOConsoleSessionScreenLockedTimeKey
);
328 gIOConsoleUsersSeedValue
= OSData::withBytesNoCopy(&gIOConsoleUsersSeed
, sizeof(gIOConsoleUsersSeed
));
330 gIOPlatformSleepActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformSleepActionKey
);
331 gIOPlatformWakeActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformWakeActionKey
);
332 gIOPlatformQuiesceActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformQuiesceActionKey
);
333 gIOPlatformActiveActionKey
= OSSymbol::withCStringNoCopy(kIOPlatformActiveActionKey
);
335 gIOPlatformFunctionHandlerSet
= OSSymbol::withCStringNoCopy(kIOPlatformFunctionHandlerSet
);
336 #if defined(__i386__) || defined(__x86_64__)
337 sCPULatencyFunctionName
[kCpuDelayBusStall
] = OSSymbol::withCStringNoCopy(kIOPlatformFunctionHandlerMaxBusDelay
);
338 sCPULatencyFunctionName
[kCpuDelayInterrupt
] = OSSymbol::withCStringNoCopy(kIOPlatformFunctionHandlerMaxInterruptDelay
);
340 gNotificationLock
= IORecursiveLockAlloc();
342 assert( gIOServicePlane
&& gIODeviceMemoryKey
343 && gIOInterruptControllersKey
&& gIOInterruptSpecifiersKey
344 && gIOResourcesKey
&& gNotifications
&& gNotificationLock
345 && gIOProviderClassKey
&& gIONameMatchKey
&& gIONameMatchedKey
346 && gIOMatchCategoryKey
&& gIODefaultMatchCategoryKey
347 && gIOPublishNotification
&& gIOMatchedNotification
348 && gIOTerminatedNotification
&& gIOServiceKey
349 && gIOConsoleUsersKey
&& gIOConsoleSessionUIDKey
350 && gIOConsoleSessionOnConsoleKey
&& gIOConsoleSessionSecureInputPIDKey
351 && gIOConsoleUsersSeedKey
&& gIOConsoleUsersSeedValue
);
353 gJobsLock
= IOLockAlloc();
354 gJobs
= OSOrderedSet::withCapacity( 10 );
356 gIOServiceBusyLock
= IOLockAlloc();
358 gIOConsoleUsersLock
= IOLockAlloc();
360 err
= semaphore_create(kernel_task
, &gJobsSemaphore
, SYNC_POLICY_FIFO
, 0);
362 gIOConsoleLockCallout
= thread_call_allocate(&IOService::consoleLockTimer
, NULL
);
364 assert( gIOServiceBusyLock
&& gJobs
&& gJobsLock
&& gIOConsoleUsersLock
365 && gIOConsoleLockCallout
&& (err
== KERN_SUCCESS
) );
367 gIOResources
= IOResources::resources();
368 assert( gIOResources
);
370 gArbitrationLockQueueLock
= IOLockAlloc();
371 queue_init(&gArbitrationLockQueueActive
);
372 queue_init(&gArbitrationLockQueueWaiting
);
373 queue_init(&gArbitrationLockQueueFree
);
375 assert( gArbitrationLockQueueLock
);
377 gIOTerminatePhase2List
= OSArray::withCapacity( 2 );
378 gIOStopList
= OSArray::withCapacity( 16 );
379 gIOStopProviderList
= OSArray::withCapacity( 16 );
380 gIOFinalizeList
= OSArray::withCapacity( 16 );
381 assert( gIOTerminatePhase2List
&& gIOStopList
&& gIOStopProviderList
&& gIOFinalizeList
);
384 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
387 static UInt64
getDebugFlags( OSDictionary
* props
)
389 OSNumber
* debugProp
;
392 debugProp
= OSDynamicCast( OSNumber
,
393 props
->getObject( gIOKitDebugKey
));
395 debugFlags
= debugProp
->unsigned64BitValue();
397 debugFlags
= gIOKitDebug
;
399 return( debugFlags
);
403 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
405 // Probe a matched service and return an instance to be started.
406 // The default score is from the property table, & may be altered
407 // during probe to change the start order.
409 IOService
* IOService::probe( IOService
* provider
,
415 bool IOService::start( IOService
* provider
)
420 void IOService::stop( IOService
* provider
)
424 void IOService::free( void )
426 requireMaxBusStall(0);
427 requireMaxInterruptDelay(0);
428 if( getPropertyTable())
429 unregisterAllInterest();
435 * Attach in service plane
437 bool IOService::attach( IOService
* provider
)
443 if( gIOKitDebug
& kIOLogAttach
)
444 LOG( "%s::attach(%s)\n", getName(),
445 provider
->getName());
447 provider
->lockForArbitration();
448 if( provider
->__state
[0] & kIOServiceInactiveState
)
451 ok
= attachToParent( provider
, gIOServicePlane
);
452 provider
->unlockForArbitration();
455 gIOServiceRoot
= this;
456 ok
= attachToParent( getRegistryRoot(), gIOServicePlane
);
462 IOService
* IOService::getServiceRoot( void )
464 return( gIOServiceRoot
);
467 void IOService::detach( IOService
* provider
)
469 IOService
* newProvider
= 0;
473 if( gIOKitDebug
& kIOLogAttach
)
474 LOG("%s::detach(%s)\n", getName(), provider
->getName());
476 lockForArbitration();
478 adjParent
= ((busy
= (__state
[1] & kIOServiceBusyStateMask
))
479 && (provider
== getProvider()));
481 detachFromParent( provider
, gIOServicePlane
);
484 newProvider
= getProvider();
485 if( busy
&& (__state
[1] & kIOServiceTermPhase3State
) && (0 == newProvider
))
486 _adjustBusy( -busy
);
489 unlockForArbitration();
492 newProvider
->lockForArbitration();
493 newProvider
->_adjustBusy(1);
494 newProvider
->unlockForArbitration();
497 // check for last client detach from a terminated service
498 if( provider
->lockForArbitration( true )) {
500 provider
->_adjustBusy( -1 );
501 if( (provider
->__state
[1] & kIOServiceTermPhase3State
)
502 && (0 == provider
->getClient())) {
503 provider
->scheduleFinalize();
505 provider
->unlockForArbitration();
510 * Register instance - publish it for matching
513 void IOService::registerService( IOOptionBits options
)
519 enum { kMaxPathLen
= 256 };
520 enum { kMaxChars
= 63 };
522 IORegistryEntry
* parent
= this;
523 IORegistryEntry
* root
= getRegistryRoot();
524 while( parent
&& (parent
!= root
))
525 parent
= parent
->getParentEntry( gIOServicePlane
);
527 if( parent
!= root
) {
528 IOLog("%s: not registry member at registerService()\n", getName());
532 // Allow the Platform Expert to adjust this node.
533 if( gIOPlatform
&& (!gIOPlatform
->platformAdjustService(this)))
536 if( (this != gIOResources
)
537 && (kIOLogRegister
& gIOKitDebug
)) {
539 pathBuf
= (char *) IOMalloc( kMaxPathLen
);
541 IOLog( "Registering: " );
544 if( pathBuf
&& getPath( pathBuf
, &len
, gIOServicePlane
)) {
547 if( len
> kMaxChars
) {
551 if( (skip
= strchr( path
, '/')))
557 IOLog( "%s\n", path
);
560 IOFree( pathBuf
, kMaxPathLen
);
563 startMatching( options
);
566 void IOService::startMatching( IOOptionBits options
)
568 IOService
* provider
;
571 bool needWake
= false;
576 lockForArbitration();
578 sync
= (options
& kIOServiceSynchronous
)
579 || ((provider
= getProvider())
580 && (provider
->__state
[1] & kIOServiceSynchronousState
));
582 if ( options
& kIOServiceAsynchronous
)
585 needConfig
= (0 == (__state
[1] & (kIOServiceNeedConfigState
| kIOServiceConfigState
)))
586 && (0 == (__state
[0] & kIOServiceInactiveState
));
588 __state
[1] |= kIOServiceNeedConfigState
;
590 // __state[0] &= ~kIOServiceInactiveState;
592 // if( sync) LOG("OSKernelStackRemaining = %08x @ %s\n",
593 // OSKernelStackRemaining(), getName());
596 needWake
= (0 != (kIOServiceSyncPubState
& __state
[1]));
600 __state
[1] |= kIOServiceSynchronousState
;
602 __state
[1] &= ~kIOServiceSynchronousState
;
604 unlockForArbitration();
608 prevBusy
= _adjustBusy( 1 );
611 IOLockLock( gIOServiceBusyLock
);
612 thread_wakeup( (event_t
) this/*&__state[1]*/ );
613 IOLockUnlock( gIOServiceBusyLock
);
615 } else if( !sync
|| (kIOServiceAsynchronous
& options
)) {
617 ok
= (0 != _IOServiceJob::startJob( this, kMatchNubJob
, options
));
621 if( (__state
[1] & kIOServiceNeedConfigState
))
622 doServiceMatch( options
);
624 lockForArbitration();
625 IOLockLock( gIOServiceBusyLock
);
627 waitAgain
= (prevBusy
< (__state
[1] & kIOServiceBusyStateMask
));
629 __state
[1] |= kIOServiceSyncPubState
| kIOServiceBusyWaiterState
;
631 __state
[1] &= ~kIOServiceSyncPubState
;
633 unlockForArbitration();
636 assert_wait( (event_t
) this/*&__state[1]*/, THREAD_UNINT
);
638 IOLockUnlock( gIOServiceBusyLock
);
640 thread_block(THREAD_CONTINUE_NULL
);
642 } while( waitAgain
);
646 IOReturn
IOService::catalogNewDrivers( OSOrderedSet
* newTables
)
648 OSDictionary
* table
;
658 while( (table
= (OSDictionary
*) newTables
->getFirstObject())) {
661 set
= (OSSet
*) copyExistingServices( table
,
662 kIOServiceRegisteredState
,
663 kIOServiceExistingSet
);
668 count
+= set
->getCount();
671 allSet
->merge((const OSSet
*) set
);
679 if( getDebugFlags( table
) & kIOLogMatch
)
680 LOG("Matching service count = %ld\n", (long)count
);
682 newTables
->removeObject(table
);
686 while( (service
= (IOService
*) allSet
->getAnyObject())) {
687 service
->startMatching(kIOServiceAsynchronous
);
688 allSet
->removeObject(service
);
693 newTables
->release();
695 return( kIOReturnSuccess
);
698 _IOServiceJob
* _IOServiceJob::startJob( IOService
* nub
, int type
,
699 IOOptionBits options
)
703 job
= new _IOServiceJob
;
704 if( job
&& !job
->init()) {
712 job
->options
= options
;
713 nub
->retain(); // thread will release()
721 * Called on a registered service to see if it matches
725 bool IOService::matchPropertyTable( OSDictionary
* table
, SInt32
* score
)
727 return( matchPropertyTable(table
) );
730 bool IOService::matchPropertyTable( OSDictionary
* table
)
736 * Called on a matched service to allocate resources
737 * before first driver is attached.
740 IOReturn
IOService::getResources( void )
742 return( kIOReturnSuccess
);
746 * Client/provider accessors
749 IOService
* IOService::getProvider( void ) const
751 IOService
* self
= (IOService
*) this;
756 generation
= getGenerationCount();
757 if( __providerGeneration
== generation
)
760 parent
= (IOService
*) getParentEntry( gIOServicePlane
);
761 if( parent
== IORegistryEntry::getRegistryRoot())
762 /* root is not an IOService */
765 self
->__provider
= parent
;
766 // save the count before getParentEntry()
767 self
->__providerGeneration
= generation
;
772 IOWorkLoop
* IOService::getWorkLoop() const
774 IOService
*provider
= getProvider();
777 return provider
->getWorkLoop();
782 OSIterator
* IOService::getProviderIterator( void ) const
784 return( getParentIterator( gIOServicePlane
));
787 IOService
* IOService::getClient( void ) const
789 return( (IOService
*) getChildEntry( gIOServicePlane
));
792 OSIterator
* IOService::getClientIterator( void ) const
794 return( getChildIterator( gIOServicePlane
));
797 OSIterator
* _IOOpenServiceIterator::iterator( OSIterator
* _iter
,
798 const IOService
* client
,
799 const IOService
* provider
)
801 _IOOpenServiceIterator
* inst
;
806 inst
= new _IOOpenServiceIterator
;
808 if( inst
&& !inst
->init()) {
814 inst
->client
= client
;
815 inst
->provider
= provider
;
821 void _IOOpenServiceIterator::free()
825 last
->unlockForArbitration();
829 OSObject
* _IOOpenServiceIterator::getNextObject()
834 last
->unlockForArbitration();
836 while( (next
= (IOService
*) iter
->getNextObject())) {
838 next
->lockForArbitration();
839 if( (client
&& (next
->isOpen( client
)))
840 || (provider
&& (provider
->isOpen( next
))) )
842 next
->unlockForArbitration();
850 bool _IOOpenServiceIterator::isValid()
852 return( iter
->isValid() );
855 void _IOOpenServiceIterator::reset()
858 last
->unlockForArbitration();
864 OSIterator
* IOService::getOpenProviderIterator( void ) const
866 return( _IOOpenServiceIterator::iterator( getProviderIterator(), this, 0 ));
869 OSIterator
* IOService::getOpenClientIterator( void ) const
871 return( _IOOpenServiceIterator::iterator( getClientIterator(), 0, this ));
875 IOReturn
IOService::callPlatformFunction( const OSSymbol
* functionName
,
876 bool waitForFunction
,
877 void *param1
, void *param2
,
878 void *param3
, void *param4
)
880 IOReturn result
= kIOReturnUnsupported
;
883 if (gIOPlatformFunctionHandlerSet
== functionName
)
885 #if defined(__i386__) || defined(__x86_64__)
886 const OSSymbol
* functionHandlerName
= (const OSSymbol
*) param1
;
887 IOService
* target
= (IOService
*) param2
;
888 bool enable
= (param3
!= 0);
890 if (sCPULatencyFunctionName
[kCpuDelayBusStall
] == functionHandlerName
)
891 result
= setLatencyHandler(kCpuDelayBusStall
, target
, enable
);
892 else if (sCPULatencyFunctionName
[kCpuDelayInterrupt
] == param1
)
893 result
= setLatencyHandler(kCpuDelayInterrupt
, target
, enable
);
894 #endif /* defined(__i386__) || defined(__x86_64__) */
897 if ((kIOReturnUnsupported
== result
) && (provider
= getProvider())) {
898 result
= provider
->callPlatformFunction(functionName
, waitForFunction
,
899 param1
, param2
, param3
, param4
);
905 IOReturn
IOService::callPlatformFunction( const char * functionName
,
906 bool waitForFunction
,
907 void *param1
, void *param2
,
908 void *param3
, void *param4
)
910 IOReturn result
= kIOReturnNoMemory
;
911 const OSSymbol
*functionSymbol
= OSSymbol::withCString(functionName
);
913 if (functionSymbol
!= 0) {
914 result
= callPlatformFunction(functionSymbol
, waitForFunction
,
915 param1
, param2
, param3
, param4
);
916 functionSymbol
->release();
924 * Accessors for global services
927 IOPlatformExpert
* IOService::getPlatform( void )
929 return( gIOPlatform
);
932 class IOPMrootDomain
* IOService::getPMRootDomain( void )
934 return( gIOPMRootDomain
);
937 IOService
* IOService::getResourceService( void )
939 return( gIOResources
);
942 void IOService::setPlatform( IOPlatformExpert
* platform
)
944 gIOPlatform
= platform
;
945 gIOResources
->attachToParent( gIOServiceRoot
, gIOServicePlane
);
948 void IOService::setPMRootDomain( class IOPMrootDomain
* rootDomain
)
950 gIOPMRootDomain
= rootDomain
;
951 publishResource("IOKit");
958 bool IOService::lockForArbitration( bool isSuccessRequired
)
962 ArbitrationLockQueueElement
* element
;
963 ArbitrationLockQueueElement
* active
;
964 ArbitrationLockQueueElement
* waiting
;
966 enum { kPutOnFreeQueue
, kPutOnActiveQueue
, kPutOnWaitingQueue
} action
;
968 // lock global access
969 IOTakeLock( gArbitrationLockQueueLock
);
971 // obtain an unused queue element
972 if( !queue_empty( &gArbitrationLockQueueFree
)) {
973 queue_remove_first( &gArbitrationLockQueueFree
,
975 ArbitrationLockQueueElement
*,
978 element
= IONew( ArbitrationLockQueueElement
, 1 );
982 // prepare the queue element
983 element
->thread
= IOThreadSelf();
984 element
->service
= this;
986 element
->required
= isSuccessRequired
;
987 element
->aborted
= false;
989 // determine whether this object is already locked (ie. on active queue)
991 queue_iterate( &gArbitrationLockQueueActive
,
993 ArbitrationLockQueueElement
*,
996 if( active
->service
== element
->service
) {
1002 if( found
) { // this object is already locked
1004 // determine whether it is the same or a different thread trying to lock
1005 if( active
->thread
!= element
->thread
) { // it is a different thread
1007 ArbitrationLockQueueElement
* victim
= 0;
1009 // before placing this new thread on the waiting queue, we look for
1010 // a deadlock cycle...
1013 // determine whether the active thread holding the object we
1014 // want is waiting for another object to be unlocked
1016 queue_iterate( &gArbitrationLockQueueWaiting
,
1018 ArbitrationLockQueueElement
*,
1021 if( waiting
->thread
== active
->thread
) {
1022 assert( false == waiting
->aborted
);
1028 if( found
) { // yes, active thread waiting for another object
1030 // this may be a candidate for rejection if the required
1031 // flag is not set, should we detect a deadlock later on
1032 if( false == waiting
->required
)
1035 // find the thread that is holding this other object, that
1036 // is blocking the active thread from proceeding (fun :-)
1038 queue_iterate( &gArbitrationLockQueueActive
,
1039 active
, // (reuse active queue element)
1040 ArbitrationLockQueueElement
*,
1043 if( active
->service
== waiting
->service
) {
1049 // someone must be holding it or it wouldn't be waiting
1052 if( active
->thread
== element
->thread
) {
1054 // doh, it's waiting for the thread that originated
1055 // this whole lock (ie. current thread) -> deadlock
1056 if( false == element
->required
) { // willing to fail?
1058 // the originating thread doesn't have the required
1059 // flag, so it can fail
1060 success
= false; // (fail originating lock request)
1061 break; // (out of while)
1063 } else { // originating thread is not willing to fail
1065 // see if we came across a waiting thread that did
1066 // not have the 'required' flag set: we'll fail it
1069 // we do have a willing victim, fail it's lock
1070 victim
->aborted
= true;
1072 // take the victim off the waiting queue
1073 queue_remove( &gArbitrationLockQueueWaiting
,
1075 ArbitrationLockQueueElement
*,
1079 IOLockWakeup( gArbitrationLockQueueLock
,
1081 /* one thread */ true );
1083 // allow this thread to proceed (ie. wait)
1084 success
= true; // (put request on wait queue)
1085 break; // (out of while)
1088 // all the waiting threads we came across in
1089 // finding this loop had the 'required' flag
1090 // set, so we've got a deadlock we can't avoid
1091 panic("I/O Kit: Unrecoverable deadlock.");
1095 // repeat while loop, redefining active thread to be the
1096 // thread holding "this other object" (see above), and
1097 // looking for threads waiting on it; note the active
1098 // variable points to "this other object" already... so
1099 // there nothing to do in this else clause.
1101 } else { // no, active thread is not waiting for another object
1103 success
= true; // (put request on wait queue)
1104 break; // (out of while)
1108 if( success
) { // put the request on the waiting queue?
1109 kern_return_t wait_result
;
1111 // place this thread on the waiting queue and put it to sleep;
1112 // we place it at the tail of the queue...
1113 queue_enter( &gArbitrationLockQueueWaiting
,
1115 ArbitrationLockQueueElement
*,
1118 // declare that this thread will wait for a given event
1119 restart_sleep
: wait_result
= assert_wait( element
,
1120 element
->required
? THREAD_UNINT
1121 : THREAD_INTERRUPTIBLE
);
1123 // unlock global access
1124 IOUnlock( gArbitrationLockQueueLock
);
1126 // put thread to sleep, waiting for our event to fire...
1127 if (wait_result
== THREAD_WAITING
)
1128 wait_result
= thread_block(THREAD_CONTINUE_NULL
);
1131 // ...and we've been woken up; we might be in one of two states:
1132 // (a) we've been aborted and our queue element is not on
1133 // any of the three queues, but is floating around
1134 // (b) we're allowed to proceed with the lock and we have
1135 // already been moved from the waiting queue to the
1137 // ...plus a 3rd state, should the thread have been interrupted:
1138 // (c) we're still on the waiting queue
1140 // determine whether we were interrupted out of our sleep
1141 if( THREAD_INTERRUPTED
== wait_result
) {
1143 // re-lock global access
1144 IOTakeLock( gArbitrationLockQueueLock
);
1146 // determine whether we're still on the waiting queue
1148 queue_iterate( &gArbitrationLockQueueWaiting
,
1149 waiting
, // (reuse waiting queue element)
1150 ArbitrationLockQueueElement
*,
1153 if( waiting
== element
) {
1159 if( found
) { // yes, we're still on the waiting queue
1161 // determine whether we're willing to fail
1162 if( false == element
->required
) {
1164 // mark us as aborted
1165 element
->aborted
= true;
1167 // take us off the waiting queue
1168 queue_remove( &gArbitrationLockQueueWaiting
,
1170 ArbitrationLockQueueElement
*,
1172 } else { // we are not willing to fail
1174 // ignore interruption, go back to sleep
1179 // unlock global access
1180 IOUnlock( gArbitrationLockQueueLock
);
1182 // proceed as though this were a normal wake up
1183 wait_result
= THREAD_AWAKENED
;
1186 assert( THREAD_AWAKENED
== wait_result
);
1188 // determine whether we've been aborted while we were asleep
1189 if( element
->aborted
) {
1190 assert( false == element
->required
);
1192 // re-lock global access
1193 IOTakeLock( gArbitrationLockQueueLock
);
1195 action
= kPutOnFreeQueue
;
1197 } else { // we weren't aborted, so we must be ready to go :-)
1199 // we've already been moved from waiting to active queue
1203 } else { // the lock request is to be failed
1205 // return unused queue element to queue
1206 action
= kPutOnFreeQueue
;
1208 } else { // it is the same thread, recursive access is allowed
1210 // add one level of recursion
1213 // return unused queue element to queue
1214 action
= kPutOnFreeQueue
;
1217 } else { // this object is not already locked, so let this thread through
1218 action
= kPutOnActiveQueue
;
1222 // put the new element on a queue
1223 if( kPutOnActiveQueue
== action
) {
1224 queue_enter( &gArbitrationLockQueueActive
,
1226 ArbitrationLockQueueElement
*,
1228 } else if( kPutOnFreeQueue
== action
) {
1229 queue_enter( &gArbitrationLockQueueFree
,
1231 ArbitrationLockQueueElement
*,
1234 assert( 0 ); // kPutOnWaitingQueue never occurs, handled specially above
1237 // unlock global access
1238 IOUnlock( gArbitrationLockQueueLock
);
1243 void IOService::unlockForArbitration( void )
1246 ArbitrationLockQueueElement
* element
;
1248 // lock global access
1249 IOTakeLock( gArbitrationLockQueueLock
);
1251 // find the lock element for this object (ie. on active queue)
1253 queue_iterate( &gArbitrationLockQueueActive
,
1255 ArbitrationLockQueueElement
*,
1258 if( element
->service
== this ) {
1266 // determine whether the lock has been taken recursively
1267 if( element
->count
> 1 ) {
1268 // undo one level of recursion
1273 // remove it from the active queue
1274 queue_remove( &gArbitrationLockQueueActive
,
1276 ArbitrationLockQueueElement
*,
1279 // put it on the free queue
1280 queue_enter( &gArbitrationLockQueueFree
,
1282 ArbitrationLockQueueElement
*,
1285 // determine whether a thread is waiting for object (head to tail scan)
1287 queue_iterate( &gArbitrationLockQueueWaiting
,
1289 ArbitrationLockQueueElement
*,
1292 if( element
->service
== this ) {
1298 if ( found
) { // we found an interested thread on waiting queue
1300 // remove it from the waiting queue
1301 queue_remove( &gArbitrationLockQueueWaiting
,
1303 ArbitrationLockQueueElement
*,
1306 // put it on the active queue
1307 queue_enter( &gArbitrationLockQueueActive
,
1309 ArbitrationLockQueueElement
*,
1312 // wake the waiting thread
1313 IOLockWakeup( gArbitrationLockQueueLock
,
1315 /* one thread */ true );
1319 // unlock global access
1320 IOUnlock( gArbitrationLockQueueLock
);
1323 void IOService::applyToProviders( IOServiceApplierFunction applier
,
1326 applyToParents( (IORegistryEntryApplierFunction
) applier
,
1327 context
, gIOServicePlane
);
1330 void IOService::applyToClients( IOServiceApplierFunction applier
,
1333 applyToChildren( (IORegistryEntryApplierFunction
) applier
,
1334 context
, gIOServicePlane
);
1343 // send a message to a client or interested party of this service
1344 IOReturn
IOService::messageClient( UInt32 type
, OSObject
* client
,
1345 void * argument
, vm_size_t argSize
)
1348 IOService
* service
;
1349 _IOServiceInterestNotifier
* notify
;
1351 if( (service
= OSDynamicCast( IOService
, client
)))
1352 ret
= service
->message( type
, this, argument
);
1354 else if( (notify
= OSDynamicCast( _IOServiceInterestNotifier
, client
))) {
1356 _IOServiceNotifierInvocation invocation
;
1359 invocation
.thread
= current_thread();
1362 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
1365 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
1366 _IOServiceNotifierInvocation
*, link
);
1372 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
,
1373 type
, this, argument
, argSize
);
1376 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
1377 _IOServiceNotifierInvocation
*, link
);
1378 if( kIOServiceNotifyWaiter
& notify
->state
) {
1379 notify
->state
&= ~kIOServiceNotifyWaiter
;
1380 WAKEUPNOTIFY( notify
);
1385 ret
= kIOReturnSuccess
;
1388 ret
= kIOReturnBadArgument
;
1394 applyToInterestNotifiers(const IORegistryEntry
*target
,
1395 const OSSymbol
* typeOfInterest
,
1396 OSObjectApplierFunction applier
,
1399 OSArray
* copyArray
= 0;
1403 IOCommand
*notifyList
=
1404 OSDynamicCast( IOCommand
, target
->getProperty( typeOfInterest
));
1407 copyArray
= OSArray::withCapacity(1);
1409 // iterate over queue, entry is set to each element in the list
1410 iterqueue(¬ifyList
->fCommandChain
, entry
) {
1411 _IOServiceInterestNotifier
* notify
;
1413 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1414 copyArray
->setObject(notify
);
1423 for( index
= 0; (next
= copyArray
->getObject( index
)); index
++)
1424 (*applier
)(next
, context
);
1425 copyArray
->release();
1429 void IOService::applyToInterested( const OSSymbol
* typeOfInterest
,
1430 OSObjectApplierFunction applier
,
1433 if (gIOGeneralInterest
== typeOfInterest
)
1434 applyToClients( (IOServiceApplierFunction
) applier
, context
);
1435 applyToInterestNotifiers(this, typeOfInterest
, applier
, context
);
1438 struct MessageClientsContext
{
1439 IOService
* service
;
1446 static void messageClientsApplier( OSObject
* object
, void * ctx
)
1449 MessageClientsContext
* context
= (MessageClientsContext
*) ctx
;
1451 ret
= context
->service
->messageClient( context
->type
,
1452 object
, context
->argument
, context
->argSize
);
1453 if( kIOReturnSuccess
!= ret
)
1457 // send a message to all clients
1458 IOReturn
IOService::messageClients( UInt32 type
,
1459 void * argument
, vm_size_t argSize
)
1461 MessageClientsContext context
;
1463 context
.service
= this;
1464 context
.type
= type
;
1465 context
.argument
= argument
;
1466 context
.argSize
= argSize
;
1467 context
.ret
= kIOReturnSuccess
;
1469 applyToInterested( gIOGeneralInterest
,
1470 &messageClientsApplier
, &context
);
1472 return( context
.ret
);
1475 IOReturn
IOService::acknowledgeNotification( IONotificationRef notification
,
1476 IOOptionBits response
)
1478 return( kIOReturnUnsupported
);
1481 IONotifier
* IOService::registerInterest( const OSSymbol
* typeOfInterest
,
1482 IOServiceInterestHandler handler
, void * target
, void * ref
)
1484 _IOServiceInterestNotifier
* notify
= 0;
1486 if( (typeOfInterest
!= gIOGeneralInterest
)
1487 && (typeOfInterest
!= gIOBusyInterest
)
1488 && (typeOfInterest
!= gIOAppPowerStateInterest
)
1489 && (typeOfInterest
!= gIOConsoleSecurityInterest
)
1490 && (typeOfInterest
!= gIOPriorityPowerStateInterest
))
1493 lockForArbitration();
1494 if( 0 == (__state
[0] & kIOServiceInactiveState
)) {
1496 notify
= new _IOServiceInterestNotifier
;
1497 if( notify
&& !notify
->init()) {
1503 notify
->handler
= handler
;
1504 notify
->target
= target
;
1506 notify
->state
= kIOServiceNotifyEnable
;
1507 queue_init( ¬ify
->handlerInvocations
);
1513 // Get the head of the notifier linked list
1514 IOCommand
*notifyList
= (IOCommand
*) getProperty( typeOfInterest
);
1515 if (!notifyList
|| !OSDynamicCast(IOCommand
, notifyList
)) {
1516 notifyList
= OSTypeAlloc(IOCommand
);
1519 setProperty( typeOfInterest
, notifyList
);
1520 notifyList
->release();
1525 enqueue(¬ifyList
->fCommandChain
, ¬ify
->chain
);
1526 notify
->retain(); // ref'ed while in list
1532 unlockForArbitration();
1537 static void cleanInterestList( OSObject
* head
)
1539 IOCommand
*notifyHead
= OSDynamicCast(IOCommand
, head
);
1544 while ( queue_entry_t entry
= dequeue(¬ifyHead
->fCommandChain
) ) {
1545 queue_next(entry
) = queue_prev(entry
) = 0;
1547 _IOServiceInterestNotifier
* notify
;
1549 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1555 void IOService::unregisterAllInterest( void )
1557 cleanInterestList( getProperty( gIOGeneralInterest
));
1558 cleanInterestList( getProperty( gIOBusyInterest
));
1559 cleanInterestList( getProperty( gIOAppPowerStateInterest
));
1560 cleanInterestList( getProperty( gIOPriorityPowerStateInterest
));
1561 cleanInterestList( getProperty( gIOConsoleSecurityInterest
));
1565 * _IOServiceInterestNotifier
1568 // wait for all threads, other than the current one,
1569 // to exit the handler
1571 void _IOServiceInterestNotifier::wait()
1573 _IOServiceNotifierInvocation
* next
;
1578 queue_iterate( &handlerInvocations
, next
,
1579 _IOServiceNotifierInvocation
*, link
) {
1580 if( next
->thread
!= current_thread() ) {
1586 state
|= kIOServiceNotifyWaiter
;
1593 void _IOServiceInterestNotifier::free()
1595 assert( queue_empty( &handlerInvocations
));
1599 void _IOServiceInterestNotifier::remove()
1603 if( queue_next( &chain
)) {
1605 queue_next( &chain
) = queue_prev( &chain
) = 0;
1609 state
&= ~kIOServiceNotifyEnable
;
1618 bool _IOServiceInterestNotifier::disable()
1624 ret
= (0 != (kIOServiceNotifyEnable
& state
));
1625 state
&= ~kIOServiceNotifyEnable
;
1634 void _IOServiceInterestNotifier::enable( bool was
)
1638 state
|= kIOServiceNotifyEnable
;
1640 state
&= ~kIOServiceNotifyEnable
;
1644 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1650 #define tailQ(o) setObject(o)
1651 #define headQ(o) setObject(0, o)
1652 #define TLOG(fmt, args...) { if(kIOLogYield & gIOKitDebug) { IOLog("[%llx] ", thread_tid(current_thread())); IOLog(fmt, ## args); }}
1654 static void _workLoopAction( IOWorkLoop::Action action
,
1655 IOService
* service
,
1656 void * p0
= 0, void * p1
= 0,
1657 void * p2
= 0, void * p3
= 0 )
1661 if( (wl
= service
->getWorkLoop())) {
1663 wl
->runAction( action
, service
, p0
, p1
, p2
, p3
);
1666 (*action
)( service
, p0
, p1
, p2
, p3
);
1669 bool IOService::requestTerminate( IOService
* provider
, IOOptionBits options
)
1673 // if its our only provider
1674 ok
= isParent( provider
, gIOServicePlane
, true);
1678 provider
->terminateClient( this, options
| kIOServiceRecursing
);
1679 ok
= (0 != (__state
[1] & kIOServiceRecursing
));
1686 bool IOService::terminatePhase1( IOOptionBits options
)
1691 OSArray
* makeInactive
;
1692 int waitResult
= THREAD_AWAKENED
;
1696 bool startPhase2
= false;
1698 TLOG("%s::terminatePhase1(%08llx)\n", getName(), (long long)options
);
1700 uint64_t regID
= getRegistryEntryID();
1702 IOSERVICE_TERMINATE_PHASE1
,
1704 (uintptr_t) (regID
>> 32),
1706 (uintptr_t) options
);
1709 if( options
& kIOServiceRecursing
) {
1710 __state
[1] |= kIOServiceRecursing
;
1715 makeInactive
= OSArray::withCapacity( 16 );
1724 didInactive
= victim
->lockForArbitration( true );
1726 didInactive
= (0 == (victim
->__state
[0] & kIOServiceInactiveState
));
1728 victim
->__state
[0] |= kIOServiceInactiveState
;
1729 victim
->__state
[0] &= ~(kIOServiceRegisteredState
| kIOServiceMatchedState
1730 | kIOServiceFirstPublishState
| kIOServiceFirstMatchState
);
1733 victim
->__state
[1] |= kIOServiceTermPhase1State
;
1735 victim
->_adjustBusy( 1 );
1737 } else if (victim
!= this) do {
1739 IOLockLock(gIOServiceBusyLock
);
1740 wait
= (victim
->__state
[1] & kIOServiceTermPhase1State
);
1742 TLOG("%s::waitPhase1(%s)\n", getName(), victim
->getName());
1743 victim
->__state
[1] |= kIOServiceTerm1WaiterState
;
1744 victim
->unlockForArbitration();
1745 assert_wait((event_t
)&victim
->__state
[1], THREAD_UNINT
);
1747 IOLockUnlock(gIOServiceBusyLock
);
1749 waitResult
= thread_block(THREAD_CONTINUE_NULL
);
1750 TLOG("%s::did waitPhase1(%s)\n", getName(), victim
->getName());
1751 victim
->lockForArbitration();
1753 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
1755 victim
->unlockForArbitration();
1758 startPhase2
= didInactive
;
1761 victim
->deliverNotification( gIOTerminatedNotification
, 0, 0xffffffff );
1762 IOUserClient::destroyUserReferences( victim
);
1764 iter
= victim
->getClientIterator();
1766 while( (client
= (IOService
*) iter
->getNextObject())) {
1767 TLOG("%s::requestTerminate(%s, %08llx)\n",
1768 client
->getName(), victim
->getName(), (long long)options
);
1769 ok
= client
->requestTerminate( victim
, options
);
1770 TLOG("%s::requestTerminate(%s, ok = %d)\n",
1771 client
->getName(), victim
->getName(), ok
);
1773 uint64_t regID1
= client
->getRegistryEntryID();
1774 uint64_t regID2
= victim
->getRegistryEntryID();
1776 (ok
? IOSERVICE_TERMINATE_REQUEST_OK
1777 : IOSERVICE_TERMINATE_REQUEST_FAIL
),
1779 (uintptr_t) (regID1
>> 32),
1781 (uintptr_t) (regID2
>> 32));
1784 makeInactive
->setObject( client
);
1790 victim
= (IOService
*) makeInactive
->getObject(0);
1793 makeInactive
->removeObject(0);
1797 makeInactive
->release();
1801 lockForArbitration();
1802 __state
[1] &= ~kIOServiceTermPhase1State
;
1803 if (kIOServiceTerm1WaiterState
& __state
[1])
1805 __state
[1] &= ~kIOServiceTerm1WaiterState
;
1806 TLOG("%s::wakePhase1\n", getName());
1807 IOLockLock( gIOServiceBusyLock
);
1808 thread_wakeup( (event_t
) &__state
[1]);
1809 IOLockUnlock( gIOServiceBusyLock
);
1811 unlockForArbitration();
1813 scheduleTerminatePhase2( options
);
1818 void IOService::scheduleTerminatePhase2( IOOptionBits options
)
1820 AbsoluteTime deadline
;
1821 int waitResult
= THREAD_AWAKENED
;
1822 bool wait
, haveDeadline
= false;
1824 options
|= kIOServiceRequired
;
1828 IOLockLock( gJobsLock
);
1830 if( (options
& kIOServiceSynchronous
)
1831 && (current_thread() != gIOTerminateThread
)) {
1834 wait
= (gIOTerminateThread
!= 0);
1836 // wait to become the terminate thread
1837 IOLockSleep( gJobsLock
, &gIOTerminateThread
, THREAD_UNINT
);
1841 gIOTerminateThread
= current_thread();
1842 gIOTerminatePhase2List
->setObject( this );
1846 while( gIOTerminateWork
)
1847 terminateWorker( options
);
1848 wait
= (0 != (__state
[1] & kIOServiceBusyStateMask
));
1850 // wait for the victim to go non-busy
1851 if( !haveDeadline
) {
1852 clock_interval_to_deadline( 15, kSecondScale
, &deadline
);
1853 haveDeadline
= true;
1855 waitResult
= IOLockSleepDeadline( gJobsLock
, &gIOTerminateWork
,
1856 deadline
, THREAD_UNINT
);
1857 if( waitResult
== THREAD_TIMED_OUT
) {
1858 IOLog("%s::terminate(kIOServiceSynchronous) timeout\n", getName());
1861 } while(gIOTerminateWork
|| (wait
&& (waitResult
!= THREAD_TIMED_OUT
)));
1863 gIOTerminateThread
= 0;
1864 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1867 // ! kIOServiceSynchronous
1869 gIOTerminatePhase2List
->setObject( this );
1870 if( 0 == gIOTerminateWork
++) {
1871 if( !gIOTerminateThread
)
1872 kernel_thread_start(&terminateThread
, (void *) options
, &gIOTerminateThread
);
1874 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1878 IOLockUnlock( gJobsLock
);
1883 void IOService::terminateThread( void * arg
, wait_result_t waitResult
)
1885 IOLockLock( gJobsLock
);
1887 while (gIOTerminateWork
)
1888 terminateWorker( (uintptr_t) arg
);
1890 thread_deallocate(gIOTerminateThread
);
1891 gIOTerminateThread
= 0;
1892 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1894 IOLockUnlock( gJobsLock
);
1897 void IOService::scheduleStop( IOService
* provider
)
1899 TLOG("%s::scheduleStop(%s)\n", getName(), provider
->getName());
1901 uint64_t regID1
= getRegistryEntryID();
1902 uint64_t regID2
= provider
->getRegistryEntryID();
1904 IOSERVICE_TERMINATE_SCHEDULE_STOP
,
1906 (uintptr_t) (regID1
>> 32),
1908 (uintptr_t) (regID2
>> 32));
1910 IOLockLock( gJobsLock
);
1911 gIOStopList
->tailQ( this );
1912 gIOStopProviderList
->tailQ( provider
);
1914 if( 0 == gIOTerminateWork
++) {
1915 if( !gIOTerminateThread
)
1916 kernel_thread_start(&terminateThread
, (void *) 0, &gIOTerminateThread
);
1918 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1921 IOLockUnlock( gJobsLock
);
1924 void IOService::scheduleFinalize( void )
1926 TLOG("%s::scheduleFinalize\n", getName());
1928 uint64_t regID1
= getRegistryEntryID();
1930 IOSERVICE_TERMINATE_SCHEDULE_FINALIZE
,
1932 (uintptr_t) (regID1
>> 32),
1935 IOLockLock( gJobsLock
);
1936 gIOFinalizeList
->tailQ( this );
1938 if( 0 == gIOTerminateWork
++) {
1939 if( !gIOTerminateThread
)
1940 kernel_thread_start(&terminateThread
, (void *) 0, &gIOTerminateThread
);
1942 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1945 IOLockUnlock( gJobsLock
);
1948 bool IOService::willTerminate( IOService
* provider
, IOOptionBits options
)
1953 bool IOService::didTerminate( IOService
* provider
, IOOptionBits options
, bool * defer
)
1955 if( false == *defer
) {
1957 if( lockForArbitration( true )) {
1958 if( false == provider
->handleIsOpen( this ))
1959 scheduleStop( provider
);
1962 message( kIOMessageServiceIsRequestingClose
, provider
, (void *) options
);
1963 if( false == provider
->handleIsOpen( this ))
1964 scheduleStop( provider
);
1967 unlockForArbitration();
1974 void IOService::actionWillTerminate( IOService
* victim
, IOOptionBits options
,
1975 OSArray
* doPhase2List
,
1976 void *unused2 __unused
,
1977 void *unused3 __unused
)
1983 iter
= victim
->getClientIterator();
1985 while( (client
= (IOService
*) iter
->getNextObject())) {
1986 TLOG("%s::willTerminate(%s, %08llx)\n",
1987 client
->getName(), victim
->getName(), (long long)options
);
1989 uint64_t regID1
= client
->getRegistryEntryID();
1990 uint64_t regID2
= victim
->getRegistryEntryID();
1992 IOSERVICE_TERMINATE_WILL
,
1994 (uintptr_t) (regID1
>> 32),
1996 (uintptr_t) (regID2
>> 32));
1998 ok
= client
->willTerminate( victim
, options
);
1999 doPhase2List
->tailQ( client
);
2005 void IOService::actionDidTerminate( IOService
* victim
, IOOptionBits options
,
2006 void *unused1 __unused
, void *unused2 __unused
,
2007 void *unused3 __unused
)
2013 victim
->messageClients( kIOMessageServiceIsTerminated
, (void *) options
);
2015 iter
= victim
->getClientIterator();
2017 while( (client
= (IOService
*) iter
->getNextObject())) {
2018 TLOG("%s::didTerminate(%s, %08llx)\n",
2019 client
->getName(), victim
->getName(), (long long)options
);
2020 client
->didTerminate( victim
, options
, &defer
);
2022 uint64_t regID1
= client
->getRegistryEntryID();
2023 uint64_t regID2
= victim
->getRegistryEntryID();
2025 (defer
? IOSERVICE_TERMINATE_DID_DEFER
2026 : IOSERVICE_TERMINATE_DID
),
2028 (uintptr_t) (regID1
>> 32),
2030 (uintptr_t) (regID2
>> 32));
2032 TLOG("%s::didTerminate(%s, defer %d)\n",
2033 client
->getName(), victim
->getName(), defer
);
2039 void IOService::actionFinalize( IOService
* victim
, IOOptionBits options
,
2040 void *unused1 __unused
, void *unused2 __unused
,
2041 void *unused3 __unused
)
2043 TLOG("%s::finalize(%08llx)\n", victim
->getName(), (long long)options
);
2045 uint64_t regID1
= victim
->getRegistryEntryID();
2047 IOSERVICE_TERMINATE_FINALIZE
,
2049 (uintptr_t) (regID1
>> 32),
2052 victim
->finalize( options
);
2055 void IOService::actionStop( IOService
* provider
, IOService
* client
,
2056 void *unused1 __unused
, void *unused2 __unused
,
2057 void *unused3 __unused
)
2059 TLOG("%s::stop(%s)\n", client
->getName(), provider
->getName());
2061 uint64_t regID1
= provider
->getRegistryEntryID();
2062 uint64_t regID2
= client
->getRegistryEntryID();
2064 IOSERVICE_TERMINATE_STOP
,
2066 (uintptr_t) (regID1
>> 32),
2068 (uintptr_t) (regID2
>> 32));
2070 client
->stop( provider
);
2071 if( provider
->isOpen( client
))
2072 provider
->close( client
);
2073 TLOG("%s::detach(%s)\n", client
->getName(), provider
->getName());
2074 client
->detach( provider
);
2077 void IOService::terminateWorker( IOOptionBits options
)
2079 OSArray
* doPhase2List
;
2080 OSArray
* didPhase2List
;
2085 IOService
* provider
;
2091 options
|= kIOServiceRequired
;
2093 doPhase2List
= OSArray::withCapacity( 16 );
2094 didPhase2List
= OSArray::withCapacity( 16 );
2095 freeList
= OSSet::withCapacity( 16 );
2096 if( (0 == doPhase2List
) || (0 == didPhase2List
) || (0 == freeList
))
2100 workDone
= gIOTerminateWork
;
2102 while( (victim
= (IOService
*) gIOTerminatePhase2List
->getObject(0) )) {
2105 gIOTerminatePhase2List
->removeObject(0);
2106 IOLockUnlock( gJobsLock
);
2110 doPhase2
= victim
->lockForArbitration( true );
2112 doPhase2
= (0 != (kIOServiceInactiveState
& victim
->__state
[0]));
2114 doPhase2
= (0 == (victim
->__state
[1] & kIOServiceTermPhase2State
))
2115 && (0 == (victim
->__state
[1] & kIOServiceConfigState
));
2117 victim
->__state
[1] |= kIOServiceTermPhase2State
;
2119 victim
->unlockForArbitration();
2122 if( 0 == victim
->getClient()) {
2123 // no clients - will go to finalize
2124 IOLockLock( gJobsLock
);
2125 gIOFinalizeList
->tailQ( victim
);
2126 IOLockUnlock( gJobsLock
);
2128 _workLoopAction( (IOWorkLoop::Action
) &actionWillTerminate
,
2129 victim
, (void *) options
, (void *) doPhase2List
);
2131 didPhase2List
->headQ( victim
);
2134 victim
= (IOService
*) doPhase2List
->getObject(0);
2137 doPhase2List
->removeObject(0);
2141 while( (victim
= (IOService
*) didPhase2List
->getObject(0)) ) {
2143 if( victim
->lockForArbitration( true )) {
2144 victim
->__state
[1] |= kIOServiceTermPhase3State
;
2145 victim
->unlockForArbitration();
2147 _workLoopAction( (IOWorkLoop::Action
) &actionDidTerminate
,
2148 victim
, (void *) options
);
2149 didPhase2List
->removeObject(0);
2151 IOLockLock( gJobsLock
);
2158 while( (victim
= (IOService
*) gIOFinalizeList
->getObject(0))) {
2160 IOLockUnlock( gJobsLock
);
2161 _workLoopAction( (IOWorkLoop::Action
) &actionFinalize
,
2162 victim
, (void *) options
);
2163 IOLockLock( gJobsLock
);
2165 freeList
->setObject( victim
);
2166 // safe if finalize list is append only
2167 gIOFinalizeList
->removeObject(0);
2171 (!doPhase3
) && (client
= (IOService
*) gIOStopList
->getObject(idx
)); ) {
2173 provider
= (IOService
*) gIOStopProviderList
->getObject(idx
);
2176 if( !provider
->isChild( client
, gIOServicePlane
)) {
2177 // may be multiply queued - nop it
2178 TLOG("%s::nop stop(%s)\n", client
->getName(), provider
->getName());
2180 uint64_t regID1
= provider
->getRegistryEntryID();
2181 uint64_t regID2
= client
->getRegistryEntryID();
2183 IOSERVICE_TERMINATE_STOP_NOP
,
2185 (uintptr_t) (regID1
>> 32),
2187 (uintptr_t) (regID2
>> 32));
2190 // a terminated client is not ready for stop if it has clients, skip it
2191 if( (kIOServiceInactiveState
& client
->__state
[0]) && client
->getClient()) {
2192 TLOG("%s::defer stop(%s)\n", client
->getName(), provider
->getName());
2194 uint64_t regID1
= provider
->getRegistryEntryID();
2195 uint64_t regID2
= client
->getRegistryEntryID();
2197 IOSERVICE_TERMINATE_STOP_DEFER
,
2199 (uintptr_t) (regID1
>> 32),
2201 (uintptr_t) (regID2
>> 32));
2207 IOLockUnlock( gJobsLock
);
2208 _workLoopAction( (IOWorkLoop::Action
) &actionStop
,
2209 provider
, (void *) client
);
2210 IOLockLock( gJobsLock
);
2211 // check the finalize list now
2215 freeList
->setObject( client
);
2216 freeList
->setObject( provider
);
2218 // safe if stop list is append only
2219 gIOStopList
->removeObject( idx
);
2220 gIOStopProviderList
->removeObject( idx
);
2224 } while( doPhase3
);
2226 gIOTerminateWork
-= workDone
;
2227 moreToDo
= (gIOTerminateWork
!= 0);
2230 TLOG("iokit terminate done, %d stops remain\n", gIOStopList
->getCount());
2232 IOSERVICE_TERMINATE_DONE
,
2233 (uintptr_t) gIOStopList
->getCount(), 0, 0, 0);
2236 } while( moreToDo
);
2238 IOLockUnlock( gJobsLock
);
2240 freeList
->release();
2241 doPhase2List
->release();
2242 didPhase2List
->release();
2244 IOLockLock( gJobsLock
);
2247 bool IOService::finalize( IOOptionBits options
)
2250 IOService
* provider
;
2252 iter
= getProviderIterator();
2256 while( (provider
= (IOService
*) iter
->getNextObject())) {
2259 if( 0 == (__state
[1] & kIOServiceTermPhase3State
)) {
2260 /* we come down here on programmatic terminate */
2262 if( provider
->isOpen( this ))
2263 provider
->close( this );
2267 if( provider
->lockForArbitration( true )) {
2268 if( 0 == (provider
->__state
[1] & kIOServiceTermPhase3State
))
2269 scheduleStop( provider
);
2270 provider
->unlockForArbitration();
2287 void IOService::doServiceTerminate( IOOptionBits options
)
2291 // a method in case someone needs to override it
2292 bool IOService::terminateClient( IOService
* client
, IOOptionBits options
)
2296 if( client
->isParent( this, gIOServicePlane
, true))
2297 // we are the clients only provider
2298 ok
= client
->terminate( options
);
2305 bool IOService::terminate( IOOptionBits options
)
2307 options
|= kIOServiceTerminate
;
2309 return( terminatePhase1( options
));
2312 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2318 struct ServiceOpenMessageContext
2320 IOService
* service
;
2322 IOService
* excludeClient
;
2323 IOOptionBits options
;
2326 static void serviceOpenMessageApplier( OSObject
* object
, void * ctx
)
2328 ServiceOpenMessageContext
* context
= (ServiceOpenMessageContext
*) ctx
;
2330 if( object
!= context
->excludeClient
)
2331 context
->service
->messageClient( context
->type
, object
, (void *) context
->options
);
2334 bool IOService::open( IOService
* forClient
,
2335 IOOptionBits options
,
2339 ServiceOpenMessageContext context
;
2341 context
.service
= this;
2342 context
.type
= kIOMessageServiceIsAttemptingOpen
;
2343 context
.excludeClient
= forClient
;
2344 context
.options
= options
;
2346 applyToInterested( gIOGeneralInterest
,
2347 &serviceOpenMessageApplier
, &context
);
2349 if( false == lockForArbitration(false) )
2352 ok
= (0 == (__state
[0] & kIOServiceInactiveState
));
2354 ok
= handleOpen( forClient
, options
, arg
);
2356 unlockForArbitration();
2361 void IOService::close( IOService
* forClient
,
2362 IOOptionBits options
)
2367 lockForArbitration();
2369 wasClosed
= handleIsOpen( forClient
);
2371 handleClose( forClient
, options
);
2372 last
= (__state
[1] & kIOServiceTermPhase3State
);
2375 unlockForArbitration();
2378 forClient
->scheduleStop( this );
2380 else if( wasClosed
) {
2382 ServiceOpenMessageContext context
;
2384 context
.service
= this;
2385 context
.type
= kIOMessageServiceWasClosed
;
2386 context
.excludeClient
= forClient
;
2387 context
.options
= options
;
2389 applyToInterested( gIOGeneralInterest
,
2390 &serviceOpenMessageApplier
, &context
);
2394 bool IOService::isOpen( const IOService
* forClient
) const
2396 IOService
* self
= (IOService
*) this;
2399 self
->lockForArbitration();
2401 ok
= handleIsOpen( forClient
);
2403 self
->unlockForArbitration();
2408 bool IOService::handleOpen( IOService
* forClient
,
2409 IOOptionBits options
,
2414 ok
= (0 == __owner
);
2416 __owner
= forClient
;
2418 else if( options
& kIOServiceSeize
) {
2419 ok
= (kIOReturnSuccess
== messageClient( kIOMessageServiceIsRequestingClose
,
2420 __owner
, (void *) options
));
2421 if( ok
&& (0 == __owner
))
2422 __owner
= forClient
;
2429 void IOService::handleClose( IOService
* forClient
,
2430 IOOptionBits options
)
2432 if( __owner
== forClient
)
2436 bool IOService::handleIsOpen( const IOService
* forClient
) const
2439 return( __owner
== forClient
);
2441 return( __owner
!= forClient
);
2445 * Probing & starting
2447 static SInt32
IONotifyOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2449 const _IOServiceNotifier
* obj1
= (const _IOServiceNotifier
*) inObj1
;
2450 const _IOServiceNotifier
* obj2
= (const _IOServiceNotifier
*) inObj2
;
2458 val1
= obj1
->priority
;
2461 val2
= obj2
->priority
;
2463 return ( val1
- val2
);
2466 static SInt32
IOServiceObjectOrder( const OSObject
* entry
, void * ref
)
2468 OSDictionary
* dict
;
2469 IOService
* service
;
2470 _IOServiceNotifier
* notify
;
2471 OSSymbol
* key
= (OSSymbol
*) ref
;
2474 if( (notify
= OSDynamicCast( _IOServiceNotifier
, entry
)))
2475 return( notify
->priority
);
2477 else if( (service
= OSDynamicCast( IOService
, entry
)))
2478 offset
= OSDynamicCast(OSNumber
, service
->getProperty( key
));
2479 else if( (dict
= OSDynamicCast( OSDictionary
, entry
)))
2480 offset
= OSDynamicCast(OSNumber
, dict
->getObject( key
));
2487 return( (SInt32
) offset
->unsigned32BitValue());
2489 return( kIODefaultProbeScore
);
2492 SInt32
IOServiceOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2494 const OSObject
* obj1
= (const OSObject
*) inObj1
;
2495 const OSObject
* obj2
= (const OSObject
*) inObj2
;
2503 val1
= IOServiceObjectOrder( obj1
, ref
);
2506 val2
= IOServiceObjectOrder( obj2
, ref
);
2508 return ( val1
- val2
);
2511 IOService
* IOService::copyClientWithCategory( const OSSymbol
* category
)
2513 IOService
* service
= 0;
2515 const OSSymbol
* nextCat
;
2517 iter
= getClientIterator();
2519 while( (service
= (IOService
*) iter
->getNextObject())) {
2520 if( kIOServiceInactiveState
& service
->__state
[0])
2522 nextCat
= (const OSSymbol
*) OSDynamicCast( OSSymbol
,
2523 service
->getProperty( gIOMatchCategoryKey
));
2524 if( category
== nextCat
)
2535 IOService
* IOService::getClientWithCategory( const OSSymbol
* category
)
2538 service
= copyClientWithCategory(category
);
2544 bool IOService::invokeNotifer( _IOServiceNotifier
* notify
)
2546 _IOServiceNotifierInvocation invocation
;
2550 invocation
.thread
= current_thread();
2553 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
2556 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
2557 _IOServiceNotifierInvocation
*, link
);
2563 ret
= (*notify
->handler
)(notify
->target
, notify
->ref
, this, notify
);
2566 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
2567 _IOServiceNotifierInvocation
*, link
);
2568 if( kIOServiceNotifyWaiter
& notify
->state
) {
2569 notify
->state
&= ~kIOServiceNotifyWaiter
;
2570 WAKEUPNOTIFY( notify
);
2579 * Alloc and probe matching classes,
2580 * called on the provider instance
2583 void IOService::probeCandidates( OSOrderedSet
* matches
)
2585 OSDictionary
* match
= 0;
2588 IOService
* newInst
;
2589 OSDictionary
* props
;
2592 OSOrderedSet
* familyMatches
= 0;
2593 OSOrderedSet
* startList
;
2594 OSDictionary
* startDict
= 0;
2595 const OSSymbol
* category
;
2597 _IOServiceNotifier
* notify
;
2598 OSObject
* nextMatch
= 0;
2600 bool needReloc
= false;
2601 #if CONFIG_MACF_KEXT
2602 OSBoolean
* isSandbox
= 0;
2603 bool useSandbox
= false;
2608 IOService
* client
= NULL
;
2612 while( !needReloc
&& (nextMatch
= matches
->getFirstObject())) {
2614 nextMatch
->retain();
2615 matches
->removeObject(nextMatch
);
2617 if( (notify
= OSDynamicCast( _IOServiceNotifier
, nextMatch
))) {
2619 lockForArbitration();
2620 if( 0 == (__state
[0] & kIOServiceInactiveState
))
2621 invokeNotifer( notify
);
2622 unlockForArbitration();
2623 nextMatch
->release();
2627 } else if( !(match
= OSDynamicCast( OSDictionary
, nextMatch
))) {
2628 nextMatch
->release();
2635 debugFlags
= getDebugFlags( match
);
2639 category
= OSDynamicCast( OSSymbol
,
2640 match
->getObject( gIOMatchCategoryKey
));
2642 category
= gIODefaultMatchCategoryKey
;
2644 if( (client
= copyClientWithCategory(category
)) ) {
2646 if( debugFlags
& kIOLogMatch
)
2647 LOG("%s: match category %s exists\n", getName(),
2648 category
->getCStringNoCopy());
2650 nextMatch
->release();
2659 // create a copy now in case its modified during matching
2660 props
= OSDictionary::withDictionary( match
, match
->getCount());
2663 props
->setCapacityIncrement(1);
2665 // check the nub matches
2666 if( false == passiveMatch( props
, true ))
2669 // Check to see if driver reloc has been loaded.
2670 needReloc
= (false == gIOCatalogue
->isModuleLoaded( match
));
2673 if( debugFlags
& kIOLogCatalogue
)
2674 LOG("%s: stalling for module\n", getName());
2676 // If reloc hasn't been loaded, exit;
2677 // reprobing will occur after reloc has been loaded.
2681 // reorder on family matchPropertyTable score.
2682 if( 0 == familyMatches
)
2683 familyMatches
= OSOrderedSet::withCapacity( 1,
2684 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2686 familyMatches
->setObject( props
);
2691 nextMatch
->release();
2700 if( familyMatches
) {
2703 && (props
= (OSDictionary
*) familyMatches
->getFirstObject())) {
2706 familyMatches
->removeObject( props
);
2711 debugFlags
= getDebugFlags( props
);
2714 symbol
= OSDynamicCast( OSSymbol
,
2715 props
->getObject( gIOClassKey
));
2719 //IOLog("%s alloc (symbol %p props %p)\n", symbol->getCStringNoCopy(), symbol, props);
2721 // alloc the driver instance
2722 inst
= (IOService
*) OSMetaClass::allocClassWithName( symbol
);
2725 IOLog("Couldn't alloc class \"%s\"\n",
2726 symbol
->getCStringNoCopy());
2730 // init driver instance
2731 if( !(inst
->init( props
))) {
2733 if( debugFlags
& kIOLogStart
)
2734 IOLog("%s::init fails\n", symbol
->getCStringNoCopy());
2738 if( __state
[1] & kIOServiceSynchronousState
)
2739 inst
->__state
[1] |= kIOServiceSynchronousState
;
2741 // give the driver the default match category if not specified
2742 category
= OSDynamicCast( OSSymbol
,
2743 props
->getObject( gIOMatchCategoryKey
));
2745 category
= gIODefaultMatchCategoryKey
;
2746 inst
->setProperty( gIOMatchCategoryKey
, (OSObject
*) category
);
2747 #if CONFIG_MACF_KEXT
2748 isSandbox
= OSDynamicCast(OSBoolean
,
2749 props
->getObject("IOKitForceMatch"));
2751 // attach driver instance
2752 if( !(inst
->attach( this )))
2755 // pass in score from property table
2756 score
= familyMatches
->orderObject( props
);
2758 // & probe the new driver instance
2760 if( debugFlags
& kIOLogProbe
)
2761 LOG("%s::probe(%s)\n",
2762 inst
->getMetaClass()->getClassName(), getName());
2765 newInst
= inst
->probe( this, &score
);
2766 inst
->detach( this );
2767 #if CONFIG_MACF_KEXT
2769 * If this is the Sandbox driver and it matched, this is a
2770 * disallowed device; toss any drivers that were already
2773 if (isSandbox
&& isSandbox
->isTrue() && newInst
!= 0) {
2774 if (startDict
!= 0) {
2775 startDict
->flushCollection();
2776 startDict
->release();
2784 if( debugFlags
& kIOLogProbe
)
2785 IOLog("%s::probe fails\n", symbol
->getCStringNoCopy());
2791 newPri
= OSNumber::withNumber( score
, 32 );
2793 newInst
->setProperty( gIOProbeScoreKey
, newPri
);
2797 // add to start list for the match category
2799 startDict
= OSDictionary::withCapacity( 1 );
2800 assert( startDict
);
2801 startList
= (OSOrderedSet
*)
2802 startDict
->getObject( category
);
2803 if( 0 == startList
) {
2804 startList
= OSOrderedSet::withCapacity( 1,
2805 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2806 if( startDict
&& startList
) {
2807 startDict
->setObject( category
, startList
);
2808 startList
->release();
2811 assert( startList
);
2813 startList
->setObject( newInst
);
2820 #if CONFIG_MACF_KEXT
2822 * If we're forcing the sandbox, drop out of the loop.
2824 if (isSandbox
&& isSandbox
->isTrue() && useSandbox
)
2828 familyMatches
->release();
2832 // start the best (until success) of each category
2834 iter
= OSCollectionIterator::withCollection( startDict
);
2836 while( (category
= (const OSSymbol
*) iter
->getNextObject())) {
2838 startList
= (OSOrderedSet
*) startDict
->getObject( category
);
2839 assert( startList
);
2844 while( true // (!started)
2845 && (inst
= (IOService
*)startList
->getFirstObject())) {
2848 startList
->removeObject(inst
);
2851 debugFlags
= getDebugFlags( inst
->getPropertyTable() );
2853 if( debugFlags
& kIOLogStart
) {
2855 LOG( "match category exists, skipping " );
2856 LOG( "%s::start(%s) <%d>\n", inst
->getName(),
2857 getName(), inst
->getRetainCount());
2860 if( false == started
)
2861 started
= startCandidate( inst
);
2863 if( (debugFlags
& kIOLogStart
) && (false == started
))
2864 LOG( "%s::start(%s) <%d> failed\n", inst
->getName(), getName(),
2865 inst
->getRetainCount());
2874 // adjust the busy count by +1 if matching is stalled for a module,
2875 // or -1 if a previously stalled matching is complete.
2876 lockForArbitration();
2878 uint64_t regID
= getRegistryEntryID();
2881 adjBusy
= (__state
[1] & kIOServiceModuleStallState
) ? 0 : 1;
2885 IOSERVICE_MODULESTALL
,
2887 (uintptr_t) (regID
>> 32),
2891 __state
[1] |= kIOServiceModuleStallState
;
2894 } else if( __state
[1] & kIOServiceModuleStallState
) {
2897 IOSERVICE_MODULEUNSTALL
,
2899 (uintptr_t) (regID
>> 32),
2903 __state
[1] &= ~kIOServiceModuleStallState
;
2907 _adjustBusy( adjBusy
);
2908 unlockForArbitration();
2911 startDict
->release();
2915 * Start a previously attached & probed instance,
2916 * called on exporting object instance
2919 bool IOService::startCandidate( IOService
* service
)
2923 ok
= service
->attach( this );
2927 if (this != gIOResources
)
2929 // stall for any nub resources
2931 // stall for any driver resources
2932 service
->checkResources();
2935 AbsoluteTime startTime
;
2936 AbsoluteTime endTime
;
2939 if (kIOLogStart
& gIOKitDebug
)
2940 clock_get_uptime(&startTime
);
2942 ok
= service
->start(this);
2944 if (kIOLogStart
& gIOKitDebug
)
2946 clock_get_uptime(&endTime
);
2948 if (CMP_ABSOLUTETIME(&endTime
, &startTime
) > 0)
2950 SUB_ABSOLUTETIME(&endTime
, &startTime
);
2951 absolutetime_to_nanoseconds(endTime
, &nano
);
2952 if (nano
> 500000000ULL)
2953 IOLog("%s::start took %ld ms\n", service
->getName(), (long)(UInt32
)(nano
/ 1000000ULL));
2957 service
->detach( this );
2962 void IOService::publishResource( const char * key
, OSObject
* value
)
2964 const OSSymbol
* sym
;
2966 if( (sym
= OSSymbol::withCString( key
))) {
2967 publishResource( sym
, value
);
2972 void IOService::publishResource( const OSSymbol
* key
, OSObject
* value
)
2975 value
= (OSObject
*) gIOServiceKey
;
2977 gIOResources
->setProperty( key
, value
);
2979 if( IORecursiveLockHaveLock( gNotificationLock
))
2982 gIOResourceGenerationCount
++;
2983 gIOResources
->registerService();
2986 bool IOService::addNeededResource( const char * key
)
2988 OSObject
* resourcesProp
;
2993 resourcesProp
= getProperty( gIOResourceMatchKey
);
2995 newKey
= OSString::withCString( key
);
2996 if( (0 == resourcesProp
) || (0 == newKey
))
2999 set
= OSDynamicCast( OSSet
, resourcesProp
);
3001 set
= OSSet::withCapacity( 1 );
3003 set
->setObject( resourcesProp
);
3008 set
->setObject( newKey
);
3010 ret
= setProperty( gIOResourceMatchKey
, set
);
3016 bool IOService::checkResource( OSObject
* matching
)
3019 OSDictionary
* table
;
3021 if( (str
= OSDynamicCast( OSString
, matching
))) {
3022 if( gIOResources
->getProperty( str
))
3027 table
= resourceMatching( str
);
3028 else if( (table
= OSDynamicCast( OSDictionary
, matching
)))
3031 IOLog("%s: Can't match using: %s\n", getName(),
3032 matching
->getMetaClass()->getClassName());
3033 /* false would stall forever */
3037 if( gIOKitDebug
& kIOLogConfig
)
3038 LOG("config(%p): stalling %s\n", IOThreadSelf(), getName());
3040 waitForService( table
);
3042 if( gIOKitDebug
& kIOLogConfig
)
3043 LOG("config(%p): waking\n", IOThreadSelf() );
3048 bool IOService::checkResources( void )
3050 OSObject
* resourcesProp
;
3055 resourcesProp
= getProperty( gIOResourceMatchKey
);
3056 if( 0 == resourcesProp
)
3059 if( (set
= OSDynamicCast( OSSet
, resourcesProp
))) {
3061 iter
= OSCollectionIterator::withCollection( set
);
3063 while( ok
&& (resourcesProp
= iter
->getNextObject()) )
3064 ok
= checkResource( resourcesProp
);
3069 ok
= checkResource( resourcesProp
);
3075 void _IOConfigThread::configThread( void )
3077 _IOConfigThread
* inst
;
3080 if( !(inst
= new _IOConfigThread
))
3085 if (KERN_SUCCESS
!= kernel_thread_start(&_IOConfigThread::main
, inst
, &unused
))
3098 void _IOConfigThread::free( void )
3100 thread_deallocate(current_thread());
3104 void IOService::doServiceMatch( IOOptionBits options
)
3106 _IOServiceNotifier
* notify
;
3108 OSOrderedSet
* matches
;
3109 SInt32 catalogGeneration
;
3110 bool keepGuessing
= true;
3111 bool reRegistered
= true;
3113 // job->nub->deliverNotification( gIOPublishNotification,
3114 // kIOServiceRegisteredState, 0xffffffff );
3116 while( keepGuessing
) {
3118 matches
= gIOCatalogue
->findDrivers( this, &catalogGeneration
);
3119 // the matches list should always be created by findDrivers()
3122 lockForArbitration();
3123 if( 0 == (__state
[0] & kIOServiceFirstPublishState
))
3124 deliverNotification( gIOFirstPublishNotification
,
3125 kIOServiceFirstPublishState
, 0xffffffff );
3127 __state
[1] &= ~kIOServiceNeedConfigState
;
3128 __state
[1] |= kIOServiceConfigState
;
3129 __state
[0] |= kIOServiceRegisteredState
;
3131 keepGuessing
&= (0 == (__state
[0] & kIOServiceInactiveState
));
3132 if (reRegistered
&& keepGuessing
) {
3133 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
3134 gNotifications
->getObject( gIOPublishNotification
) );
3136 while((notify
= (_IOServiceNotifier
*)
3137 iter
->getNextObject())) {
3139 if( passiveMatch( notify
->matching
)
3140 && (kIOServiceNotifyEnable
& notify
->state
))
3141 matches
->setObject( notify
);
3148 unlockForArbitration();
3150 if (keepGuessing
&& matches
->getCount() && (kIOReturnSuccess
== getResources()))
3151 probeCandidates( matches
);
3156 lockForArbitration();
3157 reRegistered
= (0 != (__state
[1] & kIOServiceNeedConfigState
));
3159 (reRegistered
|| (catalogGeneration
!=
3160 gIOCatalogue
->getGenerationCount()))
3161 && (0 == (__state
[0] & kIOServiceInactiveState
));
3164 unlockForArbitration();
3167 if( (0 == (__state
[0] & kIOServiceInactiveState
))
3168 && (0 == (__state
[1] & kIOServiceModuleStallState
)) ) {
3169 deliverNotification( gIOMatchedNotification
,
3170 kIOServiceMatchedState
, 0xffffffff );
3171 if( 0 == (__state
[0] & kIOServiceFirstMatchState
))
3172 deliverNotification( gIOFirstMatchNotification
,
3173 kIOServiceFirstMatchState
, 0xffffffff );
3176 __state
[1] &= ~kIOServiceConfigState
;
3177 if( __state
[0] & kIOServiceInactiveState
)
3178 scheduleTerminatePhase2();
3181 unlockForArbitration();
3184 UInt32
IOService::_adjustBusy( SInt32 delta
)
3189 bool wasQuiet
, nowQuiet
, needWake
;
3192 result
= __state
[1] & kIOServiceBusyStateMask
;
3196 next
->lockForArbitration();
3197 count
= next
->__state
[1] & kIOServiceBusyStateMask
;
3198 wasQuiet
= (0 == count
);
3199 if (((delta
< 0) && wasQuiet
) || ((delta
> 0) && (kIOServiceBusyMax
== count
)))
3200 OSReportWithBacktrace("%s: bad busy count (%d,%d)\n", next
->getName(), count
, delta
);
3203 next
->__state
[1] = (next
->__state
[1] & ~kIOServiceBusyStateMask
) | count
;
3204 nowQuiet
= (0 == count
);
3205 needWake
= (0 != (kIOServiceBusyWaiterState
& next
->__state
[1]));
3208 next
->__state
[1] &= ~kIOServiceBusyWaiterState
;
3209 IOLockLock( gIOServiceBusyLock
);
3210 thread_wakeup( (event_t
) next
);
3211 IOLockUnlock( gIOServiceBusyLock
);
3214 next
->unlockForArbitration();
3216 if( (wasQuiet
|| nowQuiet
) ) {
3217 uint64_t regID
= next
->getRegistryEntryID();
3220 ((wasQuiet
/*nowBusy*/) ? IOSERVICE_BUSY
: IOSERVICE_NONBUSY
),
3222 (uintptr_t) (regID
>> 32),
3228 next
->__timeBusy
= mach_absolute_time();
3232 next
->__accumBusy
+= mach_absolute_time() - next
->__timeBusy
;
3233 next
->__timeBusy
= 0;
3236 MessageClientsContext context
;
3238 context
.service
= next
;
3239 context
.type
= kIOMessageServiceBusyStateChange
;
3240 context
.argument
= (void *) wasQuiet
; /*nowBusy*/
3241 context
.argSize
= 0;
3243 applyToInterestNotifiers( next
, gIOBusyInterest
,
3244 &messageClientsApplier
, &context
);
3247 if( nowQuiet
&& (next
== gIOServiceRoot
)) {
3248 OSKext::considerUnloads();
3249 IOServiceTrace(IOSERVICE_REGISTRY_QUIET
, 0, 0, 0, 0);
3254 delta
= nowQuiet
? -1 : +1;
3256 } while( (wasQuiet
|| nowQuiet
) && (next
= next
->getProvider()));
3261 void IOService::adjustBusy( SInt32 delta
)
3263 lockForArbitration();
3264 _adjustBusy( delta
);
3265 unlockForArbitration();
3268 uint64_t IOService::getAccumulatedBusyTime( void )
3270 uint64_t accumBusy
= __accumBusy
;
3271 uint64_t timeBusy
= __timeBusy
;
3276 accumBusy
= __accumBusy
;
3277 timeBusy
= __timeBusy
;
3279 accumBusy
+= mach_absolute_time() - timeBusy
;
3281 while (timeBusy
!= __timeBusy
);
3283 absolutetime_to_nanoseconds(*(AbsoluteTime
*)&accumBusy
, &nano
);
3288 UInt32
IOService::getBusyState( void )
3290 return( __state
[1] & kIOServiceBusyStateMask
);
3293 IOReturn
IOService::waitForState( UInt32 mask
, UInt32 value
,
3294 mach_timespec_t
* timeout
)
3296 panic("waitForState");
3297 return (kIOReturnUnsupported
);
3300 IOReturn
IOService::waitForState( UInt32 mask
, UInt32 value
,
3304 int waitResult
= THREAD_AWAKENED
;
3305 bool computeDeadline
= true;
3306 AbsoluteTime abstime
;
3309 lockForArbitration();
3310 IOLockLock( gIOServiceBusyLock
);
3311 wait
= (value
!= (__state
[1] & mask
));
3313 __state
[1] |= kIOServiceBusyWaiterState
;
3314 unlockForArbitration();
3315 if( timeout
!= UINT64_MAX
) {
3316 if( computeDeadline
) {
3317 AbsoluteTime nsinterval
;
3318 nanoseconds_to_absolutetime(timeout
, &nsinterval
);
3319 clock_absolutetime_interval_to_deadline(nsinterval
, &abstime
);
3320 computeDeadline
= false;
3322 assert_wait_deadline((event_t
)this, THREAD_UNINT
, __OSAbsoluteTime(abstime
));
3325 assert_wait((event_t
)this, THREAD_UNINT
);
3327 unlockForArbitration();
3328 IOLockUnlock( gIOServiceBusyLock
);
3330 waitResult
= thread_block(THREAD_CONTINUE_NULL
);
3332 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
3334 if( waitResult
== THREAD_TIMED_OUT
)
3335 return( kIOReturnTimeout
);
3337 return( kIOReturnSuccess
);
3340 IOReturn
IOService::waitQuiet( uint64_t timeout
)
3342 return( waitForState( kIOServiceBusyStateMask
, 0, timeout
));
3345 IOReturn
IOService::waitQuiet( mach_timespec_t
* timeout
)
3351 timeoutNS
= timeout
->tv_sec
;
3352 timeoutNS
*= kSecondScale
;
3353 timeoutNS
+= timeout
->tv_nsec
;
3356 timeoutNS
= UINT64_MAX
;
3358 return( waitForState( kIOServiceBusyStateMask
, 0, timeoutNS
));
3361 bool IOService::serializeProperties( OSSerialize
* s
) const
3364 ((IOService
*)this)->setProperty( ((IOService
*)this)->__state
,
3365 sizeof( __state
), "__state");
3367 return( super::serializeProperties(s
) );
3371 void _IOConfigThread::main(void * arg
, wait_result_t result
)
3373 _IOConfigThread
* self
= (_IOConfigThread
*) arg
;
3374 _IOServiceJob
* job
;
3378 thread_precedence_policy_data_t precedence
= { -1 };
3380 kr
= thread_policy_set(current_thread(),
3381 THREAD_PRECEDENCE_POLICY
,
3382 (thread_policy_t
) &precedence
,
3383 THREAD_PRECEDENCE_POLICY_COUNT
);
3384 if (KERN_SUCCESS
!= kr
)
3385 IOLog("thread_policy_set(%d)\n", kr
);
3391 semaphore_wait( gJobsSemaphore
);
3393 IOTakeLock( gJobsLock
);
3394 job
= (_IOServiceJob
*) gJobs
->getFirstObject();
3396 gJobs
->removeObject(job
);
3399 // gNumConfigThreads--; // we're out of service
3400 gNumWaitingThreads
--; // we're out of service
3402 IOUnlock( gJobsLock
);
3408 if( gIOKitDebug
& kIOLogConfig
)
3409 LOG("config(%p): starting on %s, %d\n",
3410 IOThreadSelf(), job
->nub
->getName(), job
->type
);
3412 switch( job
->type
) {
3415 nub
->doServiceMatch( job
->options
);
3419 LOG("config(%p): strange type (%d)\n",
3420 IOThreadSelf(), job
->type
);
3427 IOTakeLock( gJobsLock
);
3428 alive
= (gOutstandingJobs
> gNumWaitingThreads
);
3430 gNumWaitingThreads
++; // back in service
3431 // gNumConfigThreads++;
3433 if( 0 == --gNumConfigThreads
) {
3434 // IOLog("MATCH IDLE\n");
3435 IOLockWakeup( gJobsLock
, (event_t
) &gNumConfigThreads
, /* one-thread */ false );
3438 IOUnlock( gJobsLock
);
3443 if( gIOKitDebug
& kIOLogConfig
)
3444 LOG("config(%p): terminating\n", IOThreadSelf() );
3449 IOReturn
IOService::waitMatchIdle( UInt32 msToWait
)
3452 int waitResult
= THREAD_AWAKENED
;
3453 bool computeDeadline
= true;
3454 AbsoluteTime deadline
;
3456 IOLockLock( gJobsLock
);
3458 wait
= (0 != gNumConfigThreads
);
3461 if( computeDeadline
) {
3462 clock_interval_to_deadline(
3463 msToWait
, kMillisecondScale
, &deadline
);
3464 computeDeadline
= false;
3466 waitResult
= IOLockSleepDeadline( gJobsLock
, &gNumConfigThreads
,
3467 deadline
, THREAD_UNINT
);
3469 waitResult
= IOLockSleep( gJobsLock
, &gNumConfigThreads
,
3473 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
3474 IOLockUnlock( gJobsLock
);
3476 if( waitResult
== THREAD_TIMED_OUT
)
3477 return( kIOReturnTimeout
);
3479 return( kIOReturnSuccess
);
3482 void _IOServiceJob::pingConfig( _IOServiceJob
* job
)
3489 IOTakeLock( gJobsLock
);
3492 gJobs
->setLastObject( job
);
3494 count
= gNumWaitingThreads
;
3495 // if( gNumConfigThreads) count++;// assume we're called from a config thread
3497 create
= ( (gOutstandingJobs
> count
)
3498 && (gNumConfigThreads
< kMaxConfigThreads
) );
3500 gNumConfigThreads
++;
3501 gNumWaitingThreads
++;
3504 IOUnlock( gJobsLock
);
3509 if( gIOKitDebug
& kIOLogConfig
)
3510 LOG("config(%d): creating\n", gNumConfigThreads
- 1);
3511 _IOConfigThread::configThread();
3514 semaphore_signal( gJobsSemaphore
);
3517 // internal - call with gNotificationLock
3518 OSObject
* IOService::copyExistingServices( OSDictionary
* matching
,
3519 IOOptionBits inState
, IOOptionBits options
)
3521 OSObject
* current
= 0;
3523 IOService
* service
;
3530 && (obj
= matching
->getObject(gIOProviderClassKey
))
3532 && gIOResourcesKey
->isEqualTo(obj
)
3533 && (service
= gIOResources
))
3535 if( (inState
== (service
->__state
[0] & inState
))
3536 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3537 && service
->passiveMatch( matching
))
3539 if( options
& kIONotifyOnce
)
3545 current
= OSSet::withObjects(
3546 (const OSObject
**) &service
, 1, 1 );
3551 iter
= IORegistryIterator::iterateOver( gIOServicePlane
,
3552 kIORegistryIterateRecursively
);
3556 while( (service
= (IOService
*) iter
->getNextObject())) {
3557 if( (inState
== (service
->__state
[0] & inState
))
3558 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3559 && service
->passiveMatch( matching
)) {
3561 if( options
& kIONotifyOnce
) {
3567 ((OSSet
*)current
)->setObject( service
);
3569 current
= OSSet::withObjects(
3570 (const OSObject
**) &service
, 1, 1 );
3573 } while( !service
&& !iter
->isValid());
3578 if( current
&& (0 == (options
& (kIONotifyOnce
| kIOServiceExistingSet
)))) {
3579 iter
= OSCollectionIterator::withCollection( (OSSet
*)current
);
3588 OSIterator
* IOService::getMatchingServices( OSDictionary
* matching
)
3592 // is a lock even needed?
3595 iter
= (OSIterator
*) copyExistingServices( matching
,
3596 kIOServiceMatchedState
);
3603 struct _IOServiceMatchingNotificationHandlerRef
3605 IOServiceNotificationHandler handler
;
3609 static bool _IOServiceMatchingNotificationHandler( void * target
, void * refCon
,
3610 IOService
* newService
,
3611 IONotifier
* notifier
)
3613 return ((*((_IOServiceNotifier
*) notifier
)->compatHandler
)(target
, refCon
, newService
));
3616 // internal - call with gNotificationLock
3617 IONotifier
* IOService::setNotification(
3618 const OSSymbol
* type
, OSDictionary
* matching
,
3619 IOServiceMatchingNotificationHandler handler
, void * target
, void * ref
,
3622 _IOServiceNotifier
* notify
= 0;
3628 notify
= new _IOServiceNotifier
;
3629 if( notify
&& !notify
->init()) {
3635 notify
->handler
= handler
;
3636 notify
->target
= target
;
3637 notify
->matching
= matching
;
3639 if (handler
== &_IOServiceMatchingNotificationHandler
)
3641 notify
->compatHandler
= ((_IOServiceMatchingNotificationHandlerRef
*)ref
)->handler
;
3642 notify
->ref
= ((_IOServiceMatchingNotificationHandlerRef
*)ref
)->ref
;
3646 notify
->priority
= priority
;
3647 notify
->state
= kIOServiceNotifyEnable
;
3648 queue_init( ¬ify
->handlerInvocations
);
3652 if( 0 == (set
= (OSOrderedSet
*) gNotifications
->getObject( type
))) {
3653 set
= OSOrderedSet::withCapacity( 1,
3654 IONotifyOrdering
, 0 );
3656 gNotifications
->setObject( type
, set
);
3660 notify
->whence
= set
;
3662 set
->setObject( notify
);
3668 // internal - call with gNotificationLock
3669 IONotifier
* IOService::doInstallNotification(
3670 const OSSymbol
* type
, OSDictionary
* matching
,
3671 IOServiceMatchingNotificationHandler handler
,
3672 void * target
, void * ref
,
3673 SInt32 priority
, OSIterator
** existing
)
3676 IONotifier
* notify
;
3677 IOOptionBits inState
;
3682 if( type
== gIOPublishNotification
)
3683 inState
= kIOServiceRegisteredState
;
3685 else if( type
== gIOFirstPublishNotification
)
3686 inState
= kIOServiceFirstPublishState
;
3688 else if( (type
== gIOMatchedNotification
)
3689 || (type
== gIOFirstMatchNotification
))
3690 inState
= kIOServiceMatchedState
;
3691 else if( type
== gIOTerminatedNotification
)
3696 notify
= setNotification( type
, matching
, handler
, target
, ref
, priority
);
3699 // get the current set
3700 exist
= (OSIterator
*) copyExistingServices( matching
, inState
);
3709 #if !defined(__LP64__)
3710 IONotifier
* IOService::installNotification(const OSSymbol
* type
, OSDictionary
* matching
,
3711 IOServiceNotificationHandler handler
,
3712 void * target
, void * refCon
,
3713 SInt32 priority
, OSIterator
** existing
)
3715 IONotifier
* result
;
3716 _IOServiceMatchingNotificationHandlerRef ref
;
3717 ref
.handler
= handler
;
3720 result
= (_IOServiceNotifier
*) installNotification( type
, matching
,
3721 &_IOServiceMatchingNotificationHandler
,
3722 target
, &ref
, priority
, existing
);
3724 matching
->release();
3728 #endif /* !defined(__LP64__) */
3731 IONotifier
* IOService::installNotification(
3732 const OSSymbol
* type
, OSDictionary
* matching
,
3733 IOServiceMatchingNotificationHandler handler
,
3734 void * target
, void * ref
,
3735 SInt32 priority
, OSIterator
** existing
)
3737 IONotifier
* notify
;
3741 notify
= doInstallNotification( type
, matching
, handler
, target
, ref
,
3742 priority
, existing
);
3749 IONotifier
* IOService::addNotification(
3750 const OSSymbol
* type
, OSDictionary
* matching
,
3751 IOServiceNotificationHandler handler
,
3752 void * target
, void * refCon
,
3755 IONotifier
* result
;
3756 _IOServiceMatchingNotificationHandlerRef ref
;
3758 ref
.handler
= handler
;
3761 result
= addMatchingNotification(type
, matching
, &_IOServiceMatchingNotificationHandler
,
3762 target
, &ref
, priority
);
3765 matching
->release();
3770 IONotifier
* IOService::addMatchingNotification(
3771 const OSSymbol
* type
, OSDictionary
* matching
,
3772 IOServiceMatchingNotificationHandler handler
,
3773 void * target
, void * ref
,
3776 OSIterator
* existing
= NULL
;
3777 _IOServiceNotifier
* notify
;
3780 notify
= (_IOServiceNotifier
*) installNotification( type
, matching
,
3781 handler
, target
, ref
, priority
, &existing
);
3783 // send notifications for existing set
3786 notify
->retain(); // in case handler remove()s
3787 while( (next
= (IOService
*) existing
->getNextObject())) {
3789 next
->lockForArbitration();
3790 if( 0 == (next
->__state
[0] & kIOServiceInactiveState
))
3791 next
->invokeNotifer( notify
);
3792 next
->unlockForArbitration();
3795 existing
->release();
3801 bool IOService::syncNotificationHandler(
3802 void * /* target */, void * ref
,
3803 IOService
* newService
,
3804 IONotifier
* notifier
)
3808 if (!*((IOService
**) ref
))
3810 newService
->retain();
3811 (*(IOService
**) ref
) = newService
;
3819 IOService
* IOService::waitForMatchingService( OSDictionary
* matching
,
3822 IONotifier
* notify
= 0;
3823 // priority doesn't help us much since we need a thread wakeup
3824 SInt32 priority
= 0;
3835 result
= (IOService
*) copyExistingServices( matching
,
3836 kIOServiceMatchedState
, kIONotifyOnce
);
3839 notify
= IOService::setNotification( gIOMatchedNotification
, matching
,
3840 &IOService::syncNotificationHandler
, (void *) 0,
3841 &result
, priority
);
3844 if (UINT64_MAX
!= timeout
)
3846 AbsoluteTime deadline
;
3847 nanoseconds_to_absolutetime(timeout
, &deadline
);
3848 clock_absolutetime_interval_to_deadline(deadline
, &deadline
);
3849 SLEEPNOTIFYTO(&result
, deadline
);
3853 SLEEPNOTIFY(&result
);
3861 notify
->remove(); // dequeues
3866 IOService
* IOService::waitForService( OSDictionary
* matching
,
3867 mach_timespec_t
* timeout
)
3874 timeoutNS
= timeout
->tv_sec
;
3875 timeoutNS
*= kSecondScale
;
3876 timeoutNS
+= timeout
->tv_nsec
;
3879 timeoutNS
= UINT64_MAX
;
3881 result
= waitForMatchingService(matching
, timeoutNS
);
3883 matching
->release();
3890 void IOService::deliverNotification( const OSSymbol
* type
,
3891 IOOptionBits orNewState
, IOOptionBits andNewState
)
3893 _IOServiceNotifier
* notify
;
3895 OSArray
* willSend
= 0;
3897 lockForArbitration();
3899 if( (0 == (__state
[0] & kIOServiceInactiveState
))
3900 || (type
== gIOTerminatedNotification
)) {
3904 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
3905 gNotifications
->getObject( type
) );
3908 while( (notify
= (_IOServiceNotifier
*) iter
->getNextObject())) {
3910 if( passiveMatch( notify
->matching
)
3911 && (kIOServiceNotifyEnable
& notify
->state
)) {
3913 willSend
= OSArray::withCapacity(8);
3915 willSend
->setObject( notify
);
3921 __state
[0] = (__state
[0] | orNewState
) & andNewState
;
3927 for( unsigned int idx
= 0;
3928 (notify
= (_IOServiceNotifier
*) willSend
->getObject(idx
));
3930 invokeNotifer( notify
);
3932 willSend
->release();
3934 unlockForArbitration();
3937 IOOptionBits
IOService::getState( void ) const
3939 return( __state
[0] );
3943 * Helpers to make matching objects for simple cases
3946 OSDictionary
* IOService::serviceMatching( const OSString
* name
,
3947 OSDictionary
* table
)
3950 table
= OSDictionary::withCapacity( 2 );
3952 table
->setObject(gIOProviderClassKey
, (OSObject
*)name
);
3957 OSDictionary
* IOService::serviceMatching( const char * name
,
3958 OSDictionary
* table
)
3960 const OSString
* str
;
3962 str
= OSSymbol::withCString( name
);
3966 table
= serviceMatching( str
, table
);
3971 OSDictionary
* IOService::nameMatching( const OSString
* name
,
3972 OSDictionary
* table
)
3975 table
= OSDictionary::withCapacity( 2 );
3977 table
->setObject( gIONameMatchKey
, (OSObject
*)name
);
3982 OSDictionary
* IOService::nameMatching( const char * name
,
3983 OSDictionary
* table
)
3985 const OSString
* str
;
3987 str
= OSSymbol::withCString( name
);
3991 table
= nameMatching( str
, table
);
3996 OSDictionary
* IOService::resourceMatching( const OSString
* str
,
3997 OSDictionary
* table
)
3999 table
= serviceMatching( gIOResourcesKey
, table
);
4001 table
->setObject( gIOResourceMatchKey
, (OSObject
*) str
);
4006 OSDictionary
* IOService::resourceMatching( const char * name
,
4007 OSDictionary
* table
)
4009 const OSSymbol
* str
;
4011 str
= OSSymbol::withCString( name
);
4015 table
= resourceMatching( str
, table
);
4021 OSDictionary
* IOService::propertyMatching( const OSSymbol
* key
, const OSObject
* value
,
4022 OSDictionary
* table
)
4024 OSDictionary
* properties
;
4026 properties
= OSDictionary::withCapacity( 2 );
4029 properties
->setObject( key
, value
);
4032 table
= OSDictionary::withCapacity( 2 );
4034 table
->setObject( gIOPropertyMatchKey
, properties
);
4036 properties
->release();
4041 OSDictionary
* IOService::registryEntryIDMatching( uint64_t entryID
,
4042 OSDictionary
* table
)
4046 num
= OSNumber::withNumber( entryID
, 64 );
4051 table
= OSDictionary::withCapacity( 2 );
4053 table
->setObject( gIORegistryEntryIDKey
, num
);
4063 * _IOServiceNotifier
4066 // wait for all threads, other than the current one,
4067 // to exit the handler
4069 void _IOServiceNotifier::wait()
4071 _IOServiceNotifierInvocation
* next
;
4076 queue_iterate( &handlerInvocations
, next
,
4077 _IOServiceNotifierInvocation
*, link
) {
4078 if( next
->thread
!= current_thread() ) {
4084 state
|= kIOServiceNotifyWaiter
;
4091 void _IOServiceNotifier::free()
4093 assert( queue_empty( &handlerInvocations
));
4097 void _IOServiceNotifier::remove()
4102 whence
->removeObject( (OSObject
*) this );
4106 matching
->release();
4110 state
&= ~kIOServiceNotifyEnable
;
4119 bool _IOServiceNotifier::disable()
4125 ret
= (0 != (kIOServiceNotifyEnable
& state
));
4126 state
&= ~kIOServiceNotifyEnable
;
4135 void _IOServiceNotifier::enable( bool was
)
4139 state
|= kIOServiceNotifyEnable
;
4141 state
&= ~kIOServiceNotifyEnable
;
4149 IOService
* IOResources::resources( void )
4153 inst
= new IOResources
;
4154 if( inst
&& !inst
->init()) {
4162 bool IOResources::init( OSDictionary
* dictionary
)
4164 // Do super init first
4165 if ( !super::init() )
4168 // Allow PAL layer to publish a value
4169 const char *property_name
;
4172 pal_get_resource_property( &property_name
, &property_value
);
4174 if( property_name
) {
4176 const OSSymbol
* sym
;
4178 if( (num
= OSNumber::withNumber(property_value
, 32)) != 0 ) {
4179 if( (sym
= OSSymbol::withCString( property_name
)) != 0 ) {
4180 this->setProperty( sym
, num
);
4190 IOWorkLoop
* IOResources::getWorkLoop() const
4192 // If we are the resource root
4193 // then use the platform's workloop
4194 if (this == (IOResources
*) gIOResources
)
4195 return getPlatform()->getWorkLoop();
4197 return IOService::getWorkLoop();
4200 bool IOResources::matchPropertyTable( OSDictionary
* table
)
4208 prop
= table
->getObject( gIOResourceMatchKey
);
4209 str
= OSDynamicCast( OSString
, prop
);
4211 ok
= (0 != getProperty( str
));
4213 else if( (set
= OSDynamicCast( OSSet
, prop
))) {
4215 iter
= OSCollectionIterator::withCollection( set
);
4217 while( ok
&& (str
= OSDynamicCast( OSString
, iter
->getNextObject()) ))
4218 ok
= (0 != getProperty( str
));
4227 void IOService::consoleLockTimer(thread_call_param_t p0
, thread_call_param_t p1
)
4229 IOService::updateConsoleUsers(NULL
, 0);
4232 void IOService::updateConsoleUsers(OSArray
* consoleUsers
, IOMessage systemMessage
)
4234 IORegistryEntry
* regEntry
;
4235 OSObject
* locked
= kOSBooleanFalse
;
4238 OSDictionary
* user
;
4239 static IOMessage sSystemPower
;
4241 regEntry
= IORegistryEntry::getRegistryRoot();
4243 IOLockLock(gIOConsoleUsersLock
);
4247 sSystemPower
= systemMessage
;
4253 (!num
) && (user
= OSDynamicCast(OSDictionary
, consoleUsers
->getObject(idx
)));
4256 num
= OSDynamicCast(OSNumber
, user
->getObject(gIOConsoleSessionScreenLockedTimeKey
));
4258 gIOConsoleLockTime
= num
? num
->unsigned32BitValue() : 0;
4261 if (gIOConsoleLockTime
)
4263 if (kIOMessageSystemWillSleep
== sSystemPower
)
4264 locked
= kOSBooleanTrue
;
4268 clock_usec_t microsecs
;
4270 clock_get_calendar_microtime(&now
, µsecs
);
4271 if (gIOConsoleLockTime
> now
)
4273 AbsoluteTime deadline
;
4274 clock_interval_to_deadline(gIOConsoleLockTime
- now
, kSecondScale
, &deadline
);
4275 thread_call_enter_delayed(gIOConsoleLockCallout
, deadline
);
4279 locked
= kOSBooleanTrue
;
4284 publish
= (consoleUsers
|| (locked
!= regEntry
->getProperty(gIOConsoleLockedKey
)));
4287 regEntry
->setProperty(gIOConsoleLockedKey
, locked
);
4290 regEntry
->setProperty(gIOConsoleUsersKey
, consoleUsers
);
4292 OSIncrementAtomic( &gIOConsoleUsersSeed
);
4295 IOLockUnlock(gIOConsoleUsersLock
);
4299 publishResource( gIOConsoleUsersSeedKey
, gIOConsoleUsersSeedValue
);
4301 MessageClientsContext context
;
4303 context
.service
= getServiceRoot();
4304 context
.type
= kIOMessageConsoleSecurityChange
;
4305 context
.argument
= (void *) regEntry
;
4306 context
.argSize
= 0;
4308 applyToInterestNotifiers(getServiceRoot(), gIOConsoleSecurityInterest
,
4309 &messageClientsApplier
, &context
);
4313 IOReturn
IOResources::setProperties( OSObject
* properties
)
4316 const OSSymbol
* key
;
4317 OSDictionary
* dict
;
4318 OSCollectionIterator
* iter
;
4320 err
= IOUserClient::clientHasPrivilege(current_task(), kIOClientPrivilegeAdministrator
);
4321 if ( kIOReturnSuccess
!= err
)
4324 dict
= OSDynamicCast(OSDictionary
, properties
);
4326 return( kIOReturnBadArgument
);
4328 iter
= OSCollectionIterator::withCollection( dict
);
4330 return( kIOReturnBadArgument
);
4332 while( (key
= OSDynamicCast(OSSymbol
, iter
->getNextObject())))
4334 if (gIOConsoleUsersKey
== key
) do
4336 OSArray
* consoleUsers
;
4337 consoleUsers
= OSDynamicCast(OSArray
, dict
->getObject(key
));
4340 IOService::updateConsoleUsers(consoleUsers
, 0);
4344 publishResource( key
, dict
->getObject(key
) );
4349 return( kIOReturnSuccess
);
4353 * Helpers for matching dictionaries.
4354 * Keys existing in matching are checked in properties.
4355 * Keys may be a string or OSCollection of IOStrings
4358 bool IOService::compareProperty( OSDictionary
* matching
,
4364 value
= matching
->getObject( key
);
4366 ok
= value
->isEqualTo( getProperty( key
));
4374 bool IOService::compareProperty( OSDictionary
* matching
,
4375 const OSString
* key
)
4380 value
= matching
->getObject( key
);
4382 ok
= value
->isEqualTo( getProperty( key
));
4389 bool IOService::compareProperties( OSDictionary
* matching
,
4390 OSCollection
* keys
)
4392 OSCollectionIterator
* iter
;
4393 const OSString
* key
;
4396 if( !matching
|| !keys
)
4399 iter
= OSCollectionIterator::withCollection( keys
);
4402 while( ok
&& (key
= OSDynamicCast( OSString
, iter
->getNextObject())))
4403 ok
= compareProperty( matching
, key
);
4407 keys
->release(); // !! consume a ref !!
4412 /* Helper to add a location matching dict to the table */
4414 OSDictionary
* IOService::addLocation( OSDictionary
* table
)
4416 OSDictionary
* dict
;
4421 dict
= OSDictionary::withCapacity( 1 );
4423 table
->setObject( gIOLocationMatchKey
, dict
);
4431 * Go looking for a provider to match a location dict.
4434 IOService
* IOService::matchLocation( IOService
* /* client */ )
4438 parent
= getProvider();
4441 parent
= parent
->matchLocation( this );
4446 bool IOService::passiveMatch( OSDictionary
* table
, bool changesOK
)
4452 IORegistryEntry
* entry
;
4457 bool matchParent
= false;
4468 str
= OSDynamicCast( OSString
, table
->getObject( gIOProviderClassKey
));
4471 match
= (0 != where
->metaCast( str
));
4476 obj
= table
->getObject( gIONameMatchKey
);
4479 match
= where
->compareNames( obj
, changesOK
? &matched
: 0 );
4482 if( changesOK
&& matched
) {
4483 // leave a hint as to which name matched
4484 table
->setObject( gIONameMatchedKey
, matched
);
4489 str
= OSDynamicCast( OSString
, table
->getObject( gIOLocationMatchKey
));
4492 const OSSymbol
* sym
;
4496 sym
= where
->copyLocation();
4498 match
= sym
->isEqualTo( str
);
4505 obj
= table
->getObject( gIOPropertyMatchKey
);
4508 OSDictionary
* dict
;
4509 OSDictionary
* nextDict
;
4514 dict
= where
->dictionaryWithProperties();
4516 nextDict
= OSDynamicCast( OSDictionary
, obj
);
4520 iter
= OSCollectionIterator::withCollection(
4521 OSDynamicCast(OSCollection
, obj
));
4524 || (iter
&& (0 != (nextDict
= OSDynamicCast(OSDictionary
,
4525 iter
->getNextObject()))))) {
4526 match
= dict
->isEqualTo( nextDict
, nextDict
);
4539 str
= OSDynamicCast( OSString
, table
->getObject( gIOPathMatchKey
));
4542 entry
= IORegistryEntry::fromPath( str
->getCStringNoCopy() );
4543 match
= (where
== entry
);
4550 num
= OSDynamicCast( OSNumber
, table
->getObject( gIORegistryEntryIDKey
));
4553 match
= (getRegistryEntryID() == num
->unsigned64BitValue());
4556 num
= OSDynamicCast( OSNumber
, table
->getObject( gIOMatchedServiceCountKey
));
4560 IOService
* service
= 0;
4561 UInt32 serviceCount
= 0;
4564 iter
= where
->getClientIterator();
4566 while( (service
= (IOService
*) iter
->getNextObject())) {
4567 if( kIOServiceInactiveState
& service
->__state
[0])
4569 if( 0 == service
->getProperty( gIOMatchCategoryKey
))
4575 match
= (serviceCount
== num
->unsigned32BitValue());
4580 if( done
== table
->getCount()) {
4581 // don't call family if we've done all the entries in the table
4582 matchParent
= false;
4586 // pass in score from property table
4587 score
= IOServiceObjectOrder( table
, (void *) gIOProbeScoreKey
);
4589 // do family specific matching
4590 match
= where
->matchPropertyTable( table
, &score
);
4594 if( kIOLogMatch
& getDebugFlags( table
))
4595 LOG("%s: family specific matching fails\n", where
->getName());
4602 newPri
= OSNumber::withNumber( score
, 32 );
4604 table
->setObject( gIOProbeScoreKey
, newPri
);
4609 if( !(match
= where
->compareProperty( table
, kIOBSDNameKey
)))
4611 if( !(match
= where
->compareProperty( table
, kIOBSDMajorKey
)))
4613 if( !(match
= where
->compareProperty( table
, kIOBSDMinorKey
)))
4615 if( !(match
= where
->compareProperty( table
, kIOBSDUnitKey
)))
4618 matchParent
= false;
4620 obj
= OSDynamicCast( OSDictionary
,
4621 table
->getObject( gIOParentMatchKey
));
4625 table
= (OSDictionary
*) obj
;
4629 table
= OSDynamicCast( OSDictionary
,
4630 table
->getObject( gIOLocationMatchKey
));
4633 where
= where
->getProvider();
4635 where
= where
->matchLocation( where
);
4638 } while( table
&& where
);
4640 } while( matchParent
&& (where
= where
->getProvider()) );
4642 if( kIOLogMatch
& gIOKitDebug
)
4643 if( where
&& (where
!= this) )
4644 LOG("match parent @ %s = %d\n",
4645 where
->getName(), match
);
4651 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
4652 UInt32 type
, OSDictionary
* properties
,
4653 IOUserClient
** handler
)
4655 const OSSymbol
*userClientClass
= 0;
4656 IOUserClient
*client
;
4659 if (kIOReturnSuccess
== newUserClient( owningTask
, securityID
, type
, handler
))
4660 return kIOReturnSuccess
;
4662 // First try my own properties for a user client class name
4663 temp
= getProperty(gIOUserClientClassKey
);
4665 if (OSDynamicCast(OSSymbol
, temp
))
4666 userClientClass
= (const OSSymbol
*) temp
;
4667 else if (OSDynamicCast(OSString
, temp
)) {
4668 userClientClass
= OSSymbol::withString((OSString
*) temp
);
4669 if (userClientClass
)
4670 setProperty(kIOUserClientClassKey
,
4671 (OSObject
*) userClientClass
);
4675 // Didn't find one so lets just bomb out now without further ado.
4676 if (!userClientClass
)
4677 return kIOReturnUnsupported
;
4679 // This reference is consumed by the IOServiceOpen call
4680 temp
= OSMetaClass::allocClassWithName(userClientClass
);
4682 return kIOReturnNoMemory
;
4684 if (OSDynamicCast(IOUserClient
, temp
))
4685 client
= (IOUserClient
*) temp
;
4688 return kIOReturnUnsupported
;
4691 if ( !client
->initWithTask(owningTask
, securityID
, type
, properties
) ) {
4693 return kIOReturnBadArgument
;
4696 if ( !client
->attach(this) ) {
4698 return kIOReturnUnsupported
;
4701 if ( !client
->start(this) ) {
4702 client
->detach(this);
4704 return kIOReturnUnsupported
;
4708 return kIOReturnSuccess
;
4711 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
4712 UInt32 type
, IOUserClient
** handler
)
4714 return( kIOReturnUnsupported
);
4717 IOReturn
IOService::requestProbe( IOOptionBits options
)
4719 return( kIOReturnUnsupported
);
4723 * Convert an IOReturn to text. Subclasses which add additional
4724 * IOReturn's should override this method and call
4725 * super::stringFromReturn if the desired value is not found.
4728 const char * IOService::stringFromReturn( IOReturn rtn
)
4730 static const IONamedValue IOReturn_values
[] = {
4731 {kIOReturnSuccess
, "success" },
4732 {kIOReturnError
, "general error" },
4733 {kIOReturnNoMemory
, "memory allocation error" },
4734 {kIOReturnNoResources
, "resource shortage" },
4735 {kIOReturnIPCError
, "Mach IPC failure" },
4736 {kIOReturnNoDevice
, "no such device" },
4737 {kIOReturnNotPrivileged
, "privilege violation" },
4738 {kIOReturnBadArgument
, "invalid argument" },
4739 {kIOReturnLockedRead
, "device is read locked" },
4740 {kIOReturnLockedWrite
, "device is write locked" },
4741 {kIOReturnExclusiveAccess
, "device is exclusive access" },
4742 {kIOReturnBadMessageID
, "bad IPC message ID" },
4743 {kIOReturnUnsupported
, "unsupported function" },
4744 {kIOReturnVMError
, "virtual memory error" },
4745 {kIOReturnInternalError
, "internal driver error" },
4746 {kIOReturnIOError
, "I/O error" },
4747 {kIOReturnCannotLock
, "cannot acquire lock" },
4748 {kIOReturnNotOpen
, "device is not open" },
4749 {kIOReturnNotReadable
, "device is not readable" },
4750 {kIOReturnNotWritable
, "device is not writeable" },
4751 {kIOReturnNotAligned
, "alignment error" },
4752 {kIOReturnBadMedia
, "media error" },
4753 {kIOReturnStillOpen
, "device is still open" },
4754 {kIOReturnRLDError
, "rld failure" },
4755 {kIOReturnDMAError
, "DMA failure" },
4756 {kIOReturnBusy
, "device is busy" },
4757 {kIOReturnTimeout
, "I/O timeout" },
4758 {kIOReturnOffline
, "device is offline" },
4759 {kIOReturnNotReady
, "device is not ready" },
4760 {kIOReturnNotAttached
, "device/channel is not attached" },
4761 {kIOReturnNoChannels
, "no DMA channels available" },
4762 {kIOReturnNoSpace
, "no space for data" },
4763 {kIOReturnPortExists
, "device port already exists" },
4764 {kIOReturnCannotWire
, "cannot wire physical memory" },
4765 {kIOReturnNoInterrupt
, "no interrupt attached" },
4766 {kIOReturnNoFrames
, "no DMA frames enqueued" },
4767 {kIOReturnMessageTooLarge
, "message is too large" },
4768 {kIOReturnNotPermitted
, "operation is not permitted" },
4769 {kIOReturnNoPower
, "device is without power" },
4770 {kIOReturnNoMedia
, "media is not present" },
4771 {kIOReturnUnformattedMedia
, "media is not formatted" },
4772 {kIOReturnUnsupportedMode
, "unsupported mode" },
4773 {kIOReturnUnderrun
, "data underrun" },
4774 {kIOReturnOverrun
, "data overrun" },
4775 {kIOReturnDeviceError
, "device error" },
4776 {kIOReturnNoCompletion
, "no completion routine" },
4777 {kIOReturnAborted
, "operation was aborted" },
4778 {kIOReturnNoBandwidth
, "bus bandwidth would be exceeded" },
4779 {kIOReturnNotResponding
, "device is not responding" },
4780 {kIOReturnInvalid
, "unanticipated driver error" },
4784 return IOFindNameForValue(rtn
, IOReturn_values
);
4788 * Convert an IOReturn to an errno.
4790 int IOService::errnoFromReturn( IOReturn rtn
)
4794 case kIOReturnSuccess
:
4796 case kIOReturnNoMemory
:
4798 case kIOReturnNoDevice
:
4800 case kIOReturnVMError
:
4802 case kIOReturnNotPermitted
:
4804 case kIOReturnNotPrivileged
:
4806 case kIOReturnIOError
:
4808 case kIOReturnNotWritable
:
4810 case kIOReturnBadArgument
:
4812 case kIOReturnUnsupported
:
4816 case kIOReturnNoPower
:
4818 case kIOReturnDeviceError
:
4820 case kIOReturnTimeout
:
4822 case kIOReturnMessageTooLarge
:
4824 case kIOReturnNoSpace
:
4826 case kIOReturnCannotLock
:
4830 case kIOReturnBadMessageID
:
4831 case kIOReturnNoCompletion
:
4832 case kIOReturnNotAligned
:
4834 case kIOReturnNotReady
:
4836 case kIOReturnRLDError
:
4838 case kIOReturnPortExists
:
4839 case kIOReturnStillOpen
:
4841 case kIOReturnExclusiveAccess
:
4842 case kIOReturnLockedRead
:
4843 case kIOReturnLockedWrite
:
4844 case kIOReturnNotOpen
:
4845 case kIOReturnNotReadable
:
4847 case kIOReturnCannotWire
:
4848 case kIOReturnNoResources
:
4850 case kIOReturnAborted
:
4851 case kIOReturnOffline
:
4852 case kIOReturnNotResponding
:
4854 case kIOReturnBadMedia
:
4855 case kIOReturnNoMedia
:
4856 case kIOReturnNotAttached
:
4857 case kIOReturnUnformattedMedia
:
4858 return(ENXIO
); // (media error)
4859 case kIOReturnDMAError
:
4860 case kIOReturnOverrun
:
4861 case kIOReturnUnderrun
:
4862 return(EIO
); // (transfer error)
4863 case kIOReturnNoBandwidth
:
4864 case kIOReturnNoChannels
:
4865 case kIOReturnNoFrames
:
4866 case kIOReturnNoInterrupt
:
4867 return(EIO
); // (hardware error)
4868 case kIOReturnError
:
4869 case kIOReturnInternalError
:
4870 case kIOReturnInvalid
:
4871 return(EIO
); // (generic error)
4872 case kIOReturnIPCError
:
4873 return(EIO
); // (ipc error)
4875 return(EIO
); // (all other errors)
4879 IOReturn
IOService::message( UInt32 type
, IOService
* provider
,
4883 * Generic entry point for calls from the provider. A return value of
4884 * kIOReturnSuccess indicates that the message was received, and where
4885 * applicable, that it was successful.
4888 return kIOReturnUnsupported
;
4895 IOItemCount
IOService::getDeviceMemoryCount( void )
4900 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4902 count
= array
->getCount();
4909 IODeviceMemory
* IOService::getDeviceMemoryWithIndex( unsigned int index
)
4912 IODeviceMemory
* range
;
4914 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4916 range
= (IODeviceMemory
*) array
->getObject( index
);
4923 IOMemoryMap
* IOService::mapDeviceMemoryWithIndex( unsigned int index
,
4924 IOOptionBits options
)
4926 IODeviceMemory
* range
;
4929 range
= getDeviceMemoryWithIndex( index
);
4931 map
= range
->map( options
);
4938 OSArray
* IOService::getDeviceMemory( void )
4940 return( OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
)));
4944 void IOService::setDeviceMemory( OSArray
* array
)
4946 setProperty( gIODeviceMemoryKey
, array
);
4950 * For machines where the transfers on an I/O bus can stall because
4951 * the CPU is in an idle mode, These APIs allow a driver to specify
4952 * the maximum bus stall that they can handle. 0 indicates no limit.
4955 setCPUSnoopDelay(UInt32 __unused ns
)
4957 #if defined(__i386__) || defined(__x86_64__)
4958 ml_set_maxsnoop(ns
);
4959 #endif /* defined(__i386__) || defined(__x86_64__) */
4965 #if defined(__i386__) || defined(__x86_64__)
4966 return ml_get_maxsnoop();
4969 #endif /* defined(__i386__) || defined(__x86_64__) */
4972 #if defined(__i386__) || defined(__x86_64__)
4974 requireMaxCpuDelay(IOService
* service
, UInt32 ns
, UInt32 delayType
)
4976 static const UInt kNoReplace
= -1U; // Must be an illegal index
4977 UInt replace
= kNoReplace
;
4978 bool setCpuDelay
= false;
4980 IORecursiveLockLock(sCpuDelayLock
);
4982 UInt count
= sCpuDelayData
->getLength() / sizeof(CpuDelayEntry
);
4983 CpuDelayEntry
*entries
= (CpuDelayEntry
*) sCpuDelayData
->getBytesNoCopy();
4984 IOService
* holder
= NULL
;
4987 const CpuDelayEntry ne
= {service
, ns
, delayType
};
4989 // Set maximum delay.
4990 for (UInt i
= 0; i
< count
; i
++) {
4991 IOService
*thisService
= entries
[i
].fService
;
4992 bool sameType
= (delayType
== entries
[i
].fDelayType
);
4993 if ((service
== thisService
) && sameType
)
4995 else if (!thisService
) {
4996 if (kNoReplace
== replace
)
4999 else if (sameType
) {
5000 const UInt32 thisMax
= entries
[i
].fMaxDelay
;
5004 holder
= thisService
;
5010 if (kNoReplace
== replace
)
5011 sCpuDelayData
->appendBytes(&ne
, sizeof(ne
));
5013 entries
[replace
] = ne
;
5016 ns
= -1U; // Set to max unsigned, i.e. no restriction
5018 for (UInt i
= 0; i
< count
; i
++) {
5019 // Clear a maximum delay.
5020 IOService
*thisService
= entries
[i
].fService
;
5021 if (thisService
&& (delayType
== entries
[i
].fDelayType
)) {
5022 UInt32 thisMax
= entries
[i
].fMaxDelay
;
5023 if (service
== thisService
)
5025 else if (thisMax
< ns
) {
5027 holder
= thisService
;
5032 // Check if entry found
5033 if (kNoReplace
!= replace
) {
5034 entries
[replace
].fService
= 0; // Null the entry
5041 // Must be safe to call from locked context
5042 if (delayType
== kCpuDelayBusStall
)
5044 ml_set_maxbusdelay(ns
);
5046 else if (delayType
== kCpuDelayInterrupt
)
5048 ml_set_maxintdelay(ns
);
5051 OSArray
* handlers
= sCpuLatencyHandlers
[delayType
];
5053 if (handlers
) for (unsigned int idx
= 0;
5054 (target
= (IOService
*) handlers
->getObject(idx
));
5057 target
->callPlatformFunction(sCPULatencyFunctionName
[delayType
], false,
5058 (void *) (uintptr_t) ns
, holder
,
5063 IORecursiveLockUnlock(sCpuDelayLock
);
5067 setLatencyHandler(UInt32 delayType
, IOService
* target
, bool enable
)
5069 IOReturn result
= kIOReturnNotFound
;
5073 IORecursiveLockLock(sCpuDelayLock
);
5077 if (enable
&& !sCpuLatencyHandlers
[delayType
])
5078 sCpuLatencyHandlers
[delayType
] = OSArray::withCapacity(4);
5079 array
= sCpuLatencyHandlers
[delayType
];
5082 idx
= array
->getNextIndexOfObject(target
, 0);
5087 array
->removeObject(idx
);
5088 result
= kIOReturnSuccess
;
5094 result
= kIOReturnExclusiveAccess
;
5097 array
->setObject(target
);
5099 UInt count
= sCpuDelayData
->getLength() / sizeof(CpuDelayEntry
);
5100 CpuDelayEntry
*entries
= (CpuDelayEntry
*) sCpuDelayData
->getBytesNoCopy();
5101 UInt32 ns
= -1U; // Set to max unsigned, i.e. no restriction
5102 IOService
* holder
= NULL
;
5104 for (UInt i
= 0; i
< count
; i
++) {
5105 if (entries
[i
].fService
5106 && (delayType
== entries
[i
].fDelayType
)
5107 && (entries
[i
].fMaxDelay
< ns
)) {
5108 ns
= entries
[i
].fMaxDelay
;
5109 holder
= entries
[i
].fService
;
5112 target
->callPlatformFunction(sCPULatencyFunctionName
[delayType
], false,
5113 (void *) (uintptr_t) ns
, holder
,
5115 result
= kIOReturnSuccess
;
5120 IORecursiveLockUnlock(sCpuDelayLock
);
5125 #endif /* defined(__i386__) || defined(__x86_64__) */
5128 requireMaxBusStall(UInt32 __unused ns
)
5130 #if defined(__i386__) || defined(__x86_64__)
5131 requireMaxCpuDelay(this, ns
, kCpuDelayBusStall
);
5136 requireMaxInterruptDelay(uint32_t __unused ns
)
5138 #if defined(__i386__) || defined(__x86_64__)
5139 requireMaxCpuDelay(this, ns
, kCpuDelayInterrupt
);
5147 IOReturn
IOService::resolveInterrupt(IOService
*nub
, int source
)
5149 IOInterruptController
*interruptController
;
5152 OSSymbol
*interruptControllerName
;
5154 IOInterruptSource
*interruptSources
;
5156 // Get the parents list from the nub.
5157 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptControllersKey
));
5158 if (array
== 0) return kIOReturnNoResources
;
5160 // Allocate space for the IOInterruptSources if needed... then return early.
5161 if (nub
->_interruptSources
== 0) {
5162 numSources
= array
->getCount();
5163 interruptSources
= (IOInterruptSource
*)IOMalloc(numSources
* sizeof(IOInterruptSource
));
5164 if (interruptSources
== 0) return kIOReturnNoMemory
;
5166 bzero(interruptSources
, numSources
* sizeof(IOInterruptSource
));
5168 nub
->_numInterruptSources
= numSources
;
5169 nub
->_interruptSources
= interruptSources
;
5170 return kIOReturnSuccess
;
5173 interruptControllerName
= OSDynamicCast(OSSymbol
,array
->getObject(source
));
5174 if (interruptControllerName
== 0) return kIOReturnNoResources
;
5176 interruptController
= getPlatform()->lookUpInterruptController(interruptControllerName
);
5177 if (interruptController
== 0) return kIOReturnNoResources
;
5179 // Get the interrupt numbers from the nub.
5180 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptSpecifiersKey
));
5181 if (array
== 0) return kIOReturnNoResources
;
5182 data
= OSDynamicCast(OSData
, array
->getObject(source
));
5183 if (data
== 0) return kIOReturnNoResources
;
5185 // Set the interruptController and interruptSource in the nub's table.
5186 interruptSources
= nub
->_interruptSources
;
5187 interruptSources
[source
].interruptController
= interruptController
;
5188 interruptSources
[source
].vectorData
= data
;
5190 return kIOReturnSuccess
;
5193 IOReturn
IOService::lookupInterrupt(int source
, bool resolve
, IOInterruptController
**interruptController
)
5197 /* Make sure the _interruptSources are set */
5198 if (_interruptSources
== 0) {
5199 ret
= resolveInterrupt(this, source
);
5200 if (ret
!= kIOReturnSuccess
) return ret
;
5203 /* Make sure the local source number is valid */
5204 if ((source
< 0) || (source
>= _numInterruptSources
))
5205 return kIOReturnNoInterrupt
;
5207 /* Look up the contoller for the local source */
5208 *interruptController
= _interruptSources
[source
].interruptController
;
5210 if (*interruptController
== NULL
) {
5211 if (!resolve
) return kIOReturnNoInterrupt
;
5213 /* Try to reslove the interrupt */
5214 ret
= resolveInterrupt(this, source
);
5215 if (ret
!= kIOReturnSuccess
) return ret
;
5217 *interruptController
= _interruptSources
[source
].interruptController
;
5220 return kIOReturnSuccess
;
5223 IOReturn
IOService::registerInterrupt(int source
, OSObject
*target
,
5224 IOInterruptAction handler
,
5227 IOInterruptController
*interruptController
;
5230 ret
= lookupInterrupt(source
, true, &interruptController
);
5231 if (ret
!= kIOReturnSuccess
) return ret
;
5233 /* Register the source */
5234 return interruptController
->registerInterrupt(this, source
, target
,
5235 (IOInterruptHandler
)handler
,
5239 IOReturn
IOService::unregisterInterrupt(int source
)
5241 IOInterruptController
*interruptController
;
5244 ret
= lookupInterrupt(source
, false, &interruptController
);
5245 if (ret
!= kIOReturnSuccess
) return ret
;
5247 /* Unregister the source */
5248 return interruptController
->unregisterInterrupt(this, source
);
5251 IOReturn
IOService::getInterruptType(int source
, int *interruptType
)
5253 IOInterruptController
*interruptController
;
5256 ret
= lookupInterrupt(source
, true, &interruptController
);
5257 if (ret
!= kIOReturnSuccess
) return ret
;
5259 /* Return the type */
5260 return interruptController
->getInterruptType(this, source
, interruptType
);
5263 IOReturn
IOService::enableInterrupt(int source
)
5265 IOInterruptController
*interruptController
;
5268 ret
= lookupInterrupt(source
, false, &interruptController
);
5269 if (ret
!= kIOReturnSuccess
) return ret
;
5271 /* Enable the source */
5272 return interruptController
->enableInterrupt(this, source
);
5275 IOReturn
IOService::disableInterrupt(int source
)
5277 IOInterruptController
*interruptController
;
5280 ret
= lookupInterrupt(source
, false, &interruptController
);
5281 if (ret
!= kIOReturnSuccess
) return ret
;
5283 /* Disable the source */
5284 return interruptController
->disableInterrupt(this, source
);
5287 IOReturn
IOService::causeInterrupt(int source
)
5289 IOInterruptController
*interruptController
;
5292 ret
= lookupInterrupt(source
, false, &interruptController
);
5293 if (ret
!= kIOReturnSuccess
) return ret
;
5295 /* Cause an interrupt for the source */
5296 return interruptController
->causeInterrupt(this, source
);
5300 OSMetaClassDefineReservedUnused(IOService
, 0);
5301 OSMetaClassDefineReservedUnused(IOService
, 1);
5302 OSMetaClassDefineReservedUnused(IOService
, 2);
5303 OSMetaClassDefineReservedUnused(IOService
, 3);
5304 OSMetaClassDefineReservedUnused(IOService
, 4);
5305 OSMetaClassDefineReservedUnused(IOService
, 5);
5307 OSMetaClassDefineReservedUsed(IOService
, 0);
5308 OSMetaClassDefineReservedUsed(IOService
, 1);
5309 OSMetaClassDefineReservedUsed(IOService
, 2);
5310 OSMetaClassDefineReservedUsed(IOService
, 3);
5311 OSMetaClassDefineReservedUsed(IOService
, 4);
5312 OSMetaClassDefineReservedUsed(IOService
, 5);
5314 OSMetaClassDefineReservedUnused(IOService
, 6);
5315 OSMetaClassDefineReservedUnused(IOService
, 7);
5316 OSMetaClassDefineReservedUnused(IOService
, 8);
5317 OSMetaClassDefineReservedUnused(IOService
, 9);
5318 OSMetaClassDefineReservedUnused(IOService
, 10);
5319 OSMetaClassDefineReservedUnused(IOService
, 11);
5320 OSMetaClassDefineReservedUnused(IOService
, 12);
5321 OSMetaClassDefineReservedUnused(IOService
, 13);
5322 OSMetaClassDefineReservedUnused(IOService
, 14);
5323 OSMetaClassDefineReservedUnused(IOService
, 15);
5324 OSMetaClassDefineReservedUnused(IOService
, 16);
5325 OSMetaClassDefineReservedUnused(IOService
, 17);
5326 OSMetaClassDefineReservedUnused(IOService
, 18);
5327 OSMetaClassDefineReservedUnused(IOService
, 19);
5328 OSMetaClassDefineReservedUnused(IOService
, 20);
5329 OSMetaClassDefineReservedUnused(IOService
, 21);
5330 OSMetaClassDefineReservedUnused(IOService
, 22);
5331 OSMetaClassDefineReservedUnused(IOService
, 23);
5332 OSMetaClassDefineReservedUnused(IOService
, 24);
5333 OSMetaClassDefineReservedUnused(IOService
, 25);
5334 OSMetaClassDefineReservedUnused(IOService
, 26);
5335 OSMetaClassDefineReservedUnused(IOService
, 27);
5336 OSMetaClassDefineReservedUnused(IOService
, 28);
5337 OSMetaClassDefineReservedUnused(IOService
, 29);
5338 OSMetaClassDefineReservedUnused(IOService
, 30);
5339 OSMetaClassDefineReservedUnused(IOService
, 31);
5340 OSMetaClassDefineReservedUnused(IOService
, 32);
5341 OSMetaClassDefineReservedUnused(IOService
, 33);
5342 OSMetaClassDefineReservedUnused(IOService
, 34);
5343 OSMetaClassDefineReservedUnused(IOService
, 35);
5344 OSMetaClassDefineReservedUnused(IOService
, 36);
5345 OSMetaClassDefineReservedUnused(IOService
, 37);
5346 OSMetaClassDefineReservedUnused(IOService
, 38);
5347 OSMetaClassDefineReservedUnused(IOService
, 39);
5348 OSMetaClassDefineReservedUnused(IOService
, 40);
5349 OSMetaClassDefineReservedUnused(IOService
, 41);
5350 OSMetaClassDefineReservedUnused(IOService
, 42);
5351 OSMetaClassDefineReservedUnused(IOService
, 43);
5352 OSMetaClassDefineReservedUnused(IOService
, 44);
5353 OSMetaClassDefineReservedUnused(IOService
, 45);
5354 OSMetaClassDefineReservedUnused(IOService
, 46);
5355 OSMetaClassDefineReservedUnused(IOService
, 47);