2 * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_OSREFERENCE_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
10 * License may not be used to create, or enable the creation or
11 * redistribution of, unlawful or unlicensed copies of an Apple operating
12 * system, or to circumvent, violate, or enable the circumvention or
13 * violation of, any terms of an Apple operating system software license
16 * Please obtain a copy of the License at
17 * http://www.opensource.apple.com/apsl/ and read it before using this
20 * The Original Code and all software distributed under the License are
21 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
22 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
23 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
25 * Please see the License for the specific language governing rights and
26 * limitations under the License.
28 * @APPLE_LICENSE_OSREFERENCE_HEADER_END@
31 #include <IOKit/system.h>
33 #include <IOKit/IOService.h>
34 #include <libkern/c++/OSContainers.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 <mach/sync_policy.h>
49 #include <IOKit/assert.h>
50 #include <sys/errno.h>
55 #include "IOServicePrivate.h"
57 // take lockForArbitration before LOCKNOTIFY
59 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
61 #define super IORegistryEntry
63 OSDefineMetaClassAndStructors(IOService
, IORegistryEntry
)
65 OSDefineMetaClassAndStructors(_IOServiceNotifier
, IONotifier
)
67 OSDefineMetaClassAndStructors(_IOServiceInterestNotifier
, IONotifier
)
69 OSDefineMetaClassAndStructors(_IOConfigThread
, OSObject
)
71 OSDefineMetaClassAndStructors(_IOServiceJob
, OSObject
)
73 OSDefineMetaClassAndStructors(IOResources
, IOService
)
75 OSDefineMetaClassAndStructors(_IOOpenServiceIterator
, OSIterator
)
77 OSDefineMetaClassAndAbstractStructors(IONotifier
, OSObject
)
79 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
81 static IOPlatformExpert
* gIOPlatform
;
82 static class IOPMrootDomain
* gIOPMRootDomain
;
83 const IORegistryPlane
* gIOServicePlane
;
84 const IORegistryPlane
* gIOPowerPlane
;
85 const OSSymbol
* gIODeviceMemoryKey
;
86 const OSSymbol
* gIOInterruptControllersKey
;
87 const OSSymbol
* gIOInterruptSpecifiersKey
;
89 const OSSymbol
* gIOResourcesKey
;
90 const OSSymbol
* gIOResourceMatchKey
;
91 const OSSymbol
* gIOProviderClassKey
;
92 const OSSymbol
* gIONameMatchKey
;
93 const OSSymbol
* gIONameMatchedKey
;
94 const OSSymbol
* gIOPropertyMatchKey
;
95 const OSSymbol
* gIOLocationMatchKey
;
96 const OSSymbol
* gIOParentMatchKey
;
97 const OSSymbol
* gIOPathMatchKey
;
98 const OSSymbol
* gIOMatchCategoryKey
;
99 const OSSymbol
* gIODefaultMatchCategoryKey
;
100 const OSSymbol
* gIOMatchedServiceCountKey
;
102 const OSSymbol
* gIOUserClientClassKey
;
103 const OSSymbol
* gIOKitDebugKey
;
105 const OSSymbol
* gIOCommandPoolSizeKey
;
107 const OSSymbol
* gIOConsoleUsersKey
;
108 const OSSymbol
* gIOConsoleSessionUIDKey
;
109 const OSSymbol
* gIOConsoleUsersSeedKey
;
111 static int gIOResourceGenerationCount
;
113 const OSSymbol
* gIOServiceKey
;
114 const OSSymbol
* gIOPublishNotification
;
115 const OSSymbol
* gIOFirstPublishNotification
;
116 const OSSymbol
* gIOMatchedNotification
;
117 const OSSymbol
* gIOFirstMatchNotification
;
118 const OSSymbol
* gIOTerminatedNotification
;
120 const OSSymbol
* gIOGeneralInterest
;
121 const OSSymbol
* gIOBusyInterest
;
122 const OSSymbol
* gIOAppPowerStateInterest
;
123 const OSSymbol
* gIOPriorityPowerStateInterest
;
125 static OSDictionary
* gNotifications
;
126 static IORecursiveLock
* gNotificationLock
;
128 static IOService
* gIOResources
;
129 static IOService
* gIOServiceRoot
;
131 static OSOrderedSet
* gJobs
;
132 static semaphore_port_t gJobsSemaphore
;
133 static IOLock
* gJobsLock
;
134 static int gOutstandingJobs
;
135 static int gNumConfigThreads
;
136 static int gNumWaitingThreads
;
137 static IOLock
* gIOServiceBusyLock
;
139 static thread_t gIOTerminateThread
;
140 static UInt32 gIOTerminateWork
;
141 static OSArray
* gIOTerminatePhase2List
;
142 static OSArray
* gIOStopList
;
143 static OSArray
* gIOStopProviderList
;
144 static OSArray
* gIOFinalizeList
;
146 static SInt32 gIOConsoleUsersSeed
;
147 static OSData
* gIOConsoleUsersSeedValue
;
149 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
151 #define LOCKREADNOTIFY() \
152 IORecursiveLockLock( gNotificationLock )
153 #define LOCKWRITENOTIFY() \
154 IORecursiveLockLock( gNotificationLock )
155 #define LOCKWRITE2READNOTIFY()
156 #define UNLOCKNOTIFY() \
157 IORecursiveLockUnlock( gNotificationLock )
158 #define SLEEPNOTIFY(event) \
159 IORecursiveLockSleep( gNotificationLock, (void *)(event), THREAD_UNINT )
160 #define WAKEUPNOTIFY(event) \
161 IORecursiveLockWakeup( gNotificationLock, (void *)(event), /* wake one */ false )
163 #define randomDelay() \
164 int del = read_processor_clock(); \
165 del = (((int)IOThreadSelf()) ^ del ^ (del >> 10)) & 0x3ff; \
168 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
170 #define queue_element(entry, element, type, field) do { \
171 vm_address_t __ele = (vm_address_t) (entry); \
172 __ele -= -4 + ((size_t)(&((type) 4)->field)); \
173 (element) = (type) __ele; \
176 #define iterqueue(que, elt) \
177 for (queue_entry_t elt = queue_first(que); \
178 !queue_end(que, elt); \
179 elt = queue_next(elt))
181 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
183 struct ArbitrationLockQueueElement
{
192 static queue_head_t gArbitrationLockQueueActive
;
193 static queue_head_t gArbitrationLockQueueWaiting
;
194 static queue_head_t gArbitrationLockQueueFree
;
195 static IOLock
* gArbitrationLockQueueLock
;
197 bool IOService::isInactive( void ) const
198 { return( 0 != (kIOServiceInactiveState
& getState())); }
200 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
204 // Only used by the intel implementation of
205 // IOService::requireMaxBusStall(UInt32 __unused ns)
208 const IOService
*fService
;
212 static OSData
*sBusStall
= OSData::withCapacity(8 * sizeof(BusStallEntry
));
213 static IOLock
*sBusStallLock
= IOLockAlloc();
214 #endif /* __i386__ */
216 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
218 void IOService::initialize( void )
222 gIOServicePlane
= IORegistryEntry::makePlane( kIOServicePlane
);
223 gIOPowerPlane
= IORegistryEntry::makePlane( kIOPowerPlane
);
225 gIOProviderClassKey
= OSSymbol::withCStringNoCopy( kIOProviderClassKey
);
226 gIONameMatchKey
= OSSymbol::withCStringNoCopy( kIONameMatchKey
);
227 gIONameMatchedKey
= OSSymbol::withCStringNoCopy( kIONameMatchedKey
);
228 gIOPropertyMatchKey
= OSSymbol::withCStringNoCopy( kIOPropertyMatchKey
);
229 gIOPathMatchKey
= OSSymbol::withCStringNoCopy( kIOPathMatchKey
);
230 gIOLocationMatchKey
= OSSymbol::withCStringNoCopy( kIOLocationMatchKey
);
231 gIOParentMatchKey
= OSSymbol::withCStringNoCopy( kIOParentMatchKey
);
233 gIOMatchCategoryKey
= OSSymbol::withCStringNoCopy( kIOMatchCategoryKey
);
234 gIODefaultMatchCategoryKey
= OSSymbol::withCStringNoCopy(
235 kIODefaultMatchCategoryKey
);
236 gIOMatchedServiceCountKey
= OSSymbol::withCStringNoCopy(
237 kIOMatchedServiceCountKey
);
239 gIOUserClientClassKey
= OSSymbol::withCStringNoCopy( kIOUserClientClassKey
);
241 gIOResourcesKey
= OSSymbol::withCStringNoCopy( kIOResourcesClass
);
242 gIOResourceMatchKey
= OSSymbol::withCStringNoCopy( kIOResourceMatchKey
);
244 gIODeviceMemoryKey
= OSSymbol::withCStringNoCopy( "IODeviceMemory" );
245 gIOInterruptControllersKey
246 = OSSymbol::withCStringNoCopy("IOInterruptControllers");
247 gIOInterruptSpecifiersKey
248 = OSSymbol::withCStringNoCopy("IOInterruptSpecifiers");
250 gIOKitDebugKey
= OSSymbol::withCStringNoCopy( kIOKitDebugKey
);
252 gIOCommandPoolSizeKey
= OSSymbol::withCStringNoCopy( kIOCommandPoolSizeKey
);
254 gIOGeneralInterest
= OSSymbol::withCStringNoCopy( kIOGeneralInterest
);
255 gIOBusyInterest
= OSSymbol::withCStringNoCopy( kIOBusyInterest
);
256 gIOAppPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOAppPowerStateInterest
);
257 gIOPriorityPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOPriorityPowerStateInterest
);
259 gNotifications
= OSDictionary::withCapacity( 1 );
260 gIOPublishNotification
= OSSymbol::withCStringNoCopy(
261 kIOPublishNotification
);
262 gIOFirstPublishNotification
= OSSymbol::withCStringNoCopy(
263 kIOFirstPublishNotification
);
264 gIOMatchedNotification
= OSSymbol::withCStringNoCopy(
265 kIOMatchedNotification
);
266 gIOFirstMatchNotification
= OSSymbol::withCStringNoCopy(
267 kIOFirstMatchNotification
);
268 gIOTerminatedNotification
= OSSymbol::withCStringNoCopy(
269 kIOTerminatedNotification
);
270 gIOServiceKey
= OSSymbol::withCStringNoCopy( kIOServiceClass
);
272 gIOConsoleUsersKey
= OSSymbol::withCStringNoCopy( kIOConsoleUsersKey
);
273 gIOConsoleSessionUIDKey
= OSSymbol::withCStringNoCopy( kIOConsoleSessionUIDKey
);
274 gIOConsoleUsersSeedKey
= OSSymbol::withCStringNoCopy( kIOConsoleUsersSeedKey
);
275 gIOConsoleUsersSeedValue
= OSData::withBytesNoCopy(&gIOConsoleUsersSeed
, sizeof(gIOConsoleUsersSeed
));
277 gNotificationLock
= IORecursiveLockAlloc();
279 assert( gIOServicePlane
&& gIODeviceMemoryKey
280 && gIOInterruptControllersKey
&& gIOInterruptSpecifiersKey
281 && gIOResourcesKey
&& gNotifications
&& gNotificationLock
282 && gIOProviderClassKey
&& gIONameMatchKey
&& gIONameMatchedKey
283 && gIOMatchCategoryKey
&& gIODefaultMatchCategoryKey
284 && gIOPublishNotification
&& gIOMatchedNotification
285 && gIOTerminatedNotification
&& gIOServiceKey
286 && gIOConsoleUsersKey
&& gIOConsoleSessionUIDKey
287 && gIOConsoleUsersSeedKey
&& gIOConsoleUsersSeedValue
);
289 gJobsLock
= IOLockAlloc();
290 gJobs
= OSOrderedSet::withCapacity( 10 );
292 gIOServiceBusyLock
= IOLockAlloc();
294 err
= semaphore_create(kernel_task
, &gJobsSemaphore
, SYNC_POLICY_FIFO
, 0);
296 assert( gIOServiceBusyLock
&& gJobs
&& gJobsLock
&& (err
== KERN_SUCCESS
) );
298 gIOResources
= IOResources::resources();
299 assert( gIOResources
);
301 gArbitrationLockQueueLock
= IOLockAlloc();
302 queue_init(&gArbitrationLockQueueActive
);
303 queue_init(&gArbitrationLockQueueWaiting
);
304 queue_init(&gArbitrationLockQueueFree
);
306 assert( gArbitrationLockQueueLock
);
308 gIOTerminatePhase2List
= OSArray::withCapacity( 2 );
309 gIOStopList
= OSArray::withCapacity( 16 );
310 gIOStopProviderList
= OSArray::withCapacity( 16 );
311 gIOFinalizeList
= OSArray::withCapacity( 16 );
312 assert( gIOTerminatePhase2List
&& gIOStopList
&& gIOStopProviderList
&& gIOFinalizeList
);
315 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
318 static UInt64
getDebugFlags( OSDictionary
* props
)
320 OSNumber
* debugProp
;
323 debugProp
= OSDynamicCast( OSNumber
,
324 props
->getObject( gIOKitDebugKey
));
326 debugFlags
= debugProp
->unsigned64BitValue();
328 debugFlags
= gIOKitDebug
;
330 return( debugFlags
);
334 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
336 // Probe a matched service and return an instance to be started.
337 // The default score is from the property table, & may be altered
338 // during probe to change the start order.
340 IOService
* IOService::probe( IOService
* provider
,
346 bool IOService::start( IOService
* provider
)
351 void IOService::stop( IOService
* provider
)
355 void IOService::free( void )
357 requireMaxBusStall(0);
358 if( getPropertyTable())
359 unregisterAllInterest();
365 * Attach in service plane
367 bool IOService::attach( IOService
* provider
)
373 if( gIOKitDebug
& kIOLogAttach
)
374 LOG( "%s::attach(%s)\n", getName(),
375 provider
->getName());
377 provider
->lockForArbitration();
378 if( provider
->__state
[0] & kIOServiceInactiveState
)
381 ok
= attachToParent( provider
, gIOServicePlane
);
382 provider
->unlockForArbitration();
385 gIOServiceRoot
= this;
386 ok
= attachToParent( getRegistryRoot(), gIOServicePlane
);
392 IOService
* IOService::getServiceRoot( void )
394 return( gIOServiceRoot
);
397 void IOService::detach( IOService
* provider
)
399 IOService
* newProvider
= 0;
403 if( gIOKitDebug
& kIOLogAttach
)
404 LOG("%s::detach(%s)\n", getName(), provider
->getName());
406 lockForArbitration();
408 adjParent
= ((busy
= (__state
[1] & kIOServiceBusyStateMask
))
409 && (provider
== getProvider()));
411 detachFromParent( provider
, gIOServicePlane
);
414 newProvider
= getProvider();
415 if( busy
&& (__state
[1] & kIOServiceTermPhase3State
) && (0 == newProvider
))
416 _adjustBusy( -busy
);
419 unlockForArbitration();
422 newProvider
->lockForArbitration();
423 newProvider
->_adjustBusy(1);
424 newProvider
->unlockForArbitration();
427 // check for last client detach from a terminated service
428 if( provider
->lockForArbitration( true )) {
430 provider
->_adjustBusy( -1 );
431 if( (provider
->__state
[1] & kIOServiceTermPhase3State
)
432 && (0 == provider
->getClient())) {
433 provider
->scheduleFinalize();
435 provider
->unlockForArbitration();
440 * Register instance - publish it for matching
443 void IOService::registerService( IOOptionBits options
)
449 enum { kMaxPathLen
= 256 };
450 enum { kMaxChars
= 63 };
452 IORegistryEntry
* parent
= this;
453 IORegistryEntry
* root
= getRegistryRoot();
454 while( parent
&& (parent
!= root
))
455 parent
= parent
->getParentEntry( gIOServicePlane
);
457 if( parent
!= root
) {
458 IOLog("%s: not registry member at registerService()\n", getName());
462 // Allow the Platform Expert to adjust this node.
463 if( gIOPlatform
&& (!gIOPlatform
->platformAdjustService(this)))
466 if( (this != gIOResources
)
467 && (kIOLogRegister
& gIOKitDebug
)) {
469 pathBuf
= (char *) IOMalloc( kMaxPathLen
);
471 IOLog( "Registering: " );
474 if( pathBuf
&& getPath( pathBuf
, &len
, gIOServicePlane
)) {
477 if( len
> kMaxChars
) {
481 if( (skip
= strchr( path
, '/')))
487 IOLog( "%s\n", path
);
490 IOFree( pathBuf
, kMaxPathLen
);
493 startMatching( options
);
496 void IOService::startMatching( IOOptionBits options
)
498 IOService
* provider
;
501 bool needWake
= false;
506 lockForArbitration();
508 sync
= (options
& kIOServiceSynchronous
)
509 || ((provider
= getProvider())
510 && (provider
->__state
[1] & kIOServiceSynchronousState
));
512 if ( options
& kIOServiceAsynchronous
)
515 needConfig
= (0 == (__state
[1] & (kIOServiceNeedConfigState
| kIOServiceConfigState
)))
516 && (0 == (__state
[0] & kIOServiceInactiveState
));
518 __state
[1] |= kIOServiceNeedConfigState
;
520 // __state[0] &= ~kIOServiceInactiveState;
522 // if( sync) LOG("OSKernelStackRemaining = %08x @ %s\n",
523 // OSKernelStackRemaining(), getName());
526 prevBusy
= _adjustBusy( 1 );
527 needWake
= (0 != (kIOServiceSyncPubState
& __state
[1]));
531 __state
[1] |= kIOServiceSynchronousState
;
533 __state
[1] &= ~kIOServiceSynchronousState
;
535 unlockForArbitration();
540 IOLockLock( gIOServiceBusyLock
);
541 thread_wakeup( (event_t
) this/*&__state[1]*/ );
542 IOLockUnlock( gIOServiceBusyLock
);
544 } else if( !sync
|| (kIOServiceAsynchronous
& options
)) {
546 ok
= (0 != _IOServiceJob::startJob( this, kMatchNubJob
, options
));
550 if( (__state
[1] & kIOServiceNeedConfigState
))
551 doServiceMatch( options
);
553 lockForArbitration();
554 IOLockLock( gIOServiceBusyLock
);
556 waitAgain
= (prevBusy
< (__state
[1] & kIOServiceBusyStateMask
));
558 __state
[1] |= kIOServiceSyncPubState
| kIOServiceBusyWaiterState
;
560 __state
[1] &= ~kIOServiceSyncPubState
;
562 unlockForArbitration();
565 assert_wait( (event_t
) this/*&__state[1]*/, THREAD_UNINT
);
567 IOLockUnlock( gIOServiceBusyLock
);
569 thread_block(THREAD_CONTINUE_NULL
);
571 } while( waitAgain
);
575 IOReturn
IOService::catalogNewDrivers( OSOrderedSet
* newTables
)
577 OSDictionary
* table
;
587 while( (table
= (OSDictionary
*) newTables
->getFirstObject())) {
590 set
= (OSSet
*) getExistingServices( table
,
591 kIOServiceRegisteredState
,
592 kIOServiceExistingSet
);
597 count
+= set
->getCount();
600 allSet
->merge((const OSSet
*) set
);
608 if( getDebugFlags( table
) & kIOLogMatch
)
609 LOG("Matching service count = %ld\n", count
);
611 newTables
->removeObject(table
);
615 while( (service
= (IOService
*) allSet
->getAnyObject())) {
616 service
->startMatching(kIOServiceAsynchronous
);
617 allSet
->removeObject(service
);
622 newTables
->release();
624 return( kIOReturnSuccess
);
627 _IOServiceJob
* _IOServiceJob::startJob( IOService
* nub
, int type
,
628 IOOptionBits options
)
632 job
= new _IOServiceJob
;
633 if( job
&& !job
->init()) {
641 job
->options
= options
;
642 nub
->retain(); // thread will release()
650 * Called on a registered service to see if it matches
654 bool IOService::matchPropertyTable( OSDictionary
* table
, SInt32
* score
)
656 return( matchPropertyTable(table
) );
659 bool IOService::matchPropertyTable( OSDictionary
* table
)
665 * Called on a matched service to allocate resources
666 * before first driver is attached.
669 IOReturn
IOService::getResources( void )
671 return( kIOReturnSuccess
);
675 * Client/provider accessors
678 IOService
* IOService::getProvider( void ) const
680 IOService
* self
= (IOService
*) this;
685 generation
= getGenerationCount();
686 if( __providerGeneration
== generation
)
689 parent
= (IOService
*) getParentEntry( gIOServicePlane
);
690 if( parent
== IORegistryEntry::getRegistryRoot())
691 /* root is not an IOService */
694 self
->__provider
= parent
;
695 // save the count before getParentEntry()
696 self
->__providerGeneration
= generation
;
701 IOWorkLoop
* IOService::getWorkLoop() const
703 IOService
*provider
= getProvider();
706 return provider
->getWorkLoop();
711 OSIterator
* IOService::getProviderIterator( void ) const
713 return( getParentIterator( gIOServicePlane
));
716 IOService
* IOService::getClient( void ) const
718 return( (IOService
*) getChildEntry( gIOServicePlane
));
721 OSIterator
* IOService::getClientIterator( void ) const
723 return( getChildIterator( gIOServicePlane
));
726 OSIterator
* _IOOpenServiceIterator::iterator( OSIterator
* _iter
,
727 const IOService
* client
,
728 const IOService
* provider
)
730 _IOOpenServiceIterator
* inst
;
735 inst
= new _IOOpenServiceIterator
;
737 if( inst
&& !inst
->init()) {
743 inst
->client
= client
;
744 inst
->provider
= provider
;
750 void _IOOpenServiceIterator::free()
754 last
->unlockForArbitration();
758 OSObject
* _IOOpenServiceIterator::getNextObject()
763 last
->unlockForArbitration();
765 while( (next
= (IOService
*) iter
->getNextObject())) {
767 next
->lockForArbitration();
768 if( (client
&& (next
->isOpen( client
)))
769 || (provider
&& (provider
->isOpen( next
))) )
771 next
->unlockForArbitration();
779 bool _IOOpenServiceIterator::isValid()
781 return( iter
->isValid() );
784 void _IOOpenServiceIterator::reset()
787 last
->unlockForArbitration();
793 OSIterator
* IOService::getOpenProviderIterator( void ) const
795 return( _IOOpenServiceIterator::iterator( getProviderIterator(), this, 0 ));
798 OSIterator
* IOService::getOpenClientIterator( void ) const
800 return( _IOOpenServiceIterator::iterator( getClientIterator(), 0, this ));
804 IOReturn
IOService::callPlatformFunction( const OSSymbol
* functionName
,
805 bool waitForFunction
,
806 void *param1
, void *param2
,
807 void *param3
, void *param4
)
809 IOReturn result
= kIOReturnUnsupported
;
810 IOService
*provider
= getProvider();
813 result
= provider
->callPlatformFunction(functionName
, waitForFunction
,
814 param1
, param2
, param3
, param4
);
820 IOReturn
IOService::callPlatformFunction( const char * functionName
,
821 bool waitForFunction
,
822 void *param1
, void *param2
,
823 void *param3
, void *param4
)
825 IOReturn result
= kIOReturnNoMemory
;
826 const OSSymbol
*functionSymbol
= OSSymbol::withCString(functionName
);
828 if (functionSymbol
!= 0) {
829 result
= callPlatformFunction(functionSymbol
, waitForFunction
,
830 param1
, param2
, param3
, param4
);
831 functionSymbol
->release();
839 * Accessors for global services
842 IOPlatformExpert
* IOService::getPlatform( void )
844 return( gIOPlatform
);
847 class IOPMrootDomain
* IOService::getPMRootDomain( void )
849 return( gIOPMRootDomain
);
852 IOService
* IOService::getResourceService( void )
854 return( gIOResources
);
857 void IOService::setPlatform( IOPlatformExpert
* platform
)
859 gIOPlatform
= platform
;
860 gIOResources
->attachToParent( gIOServiceRoot
, gIOServicePlane
);
863 void IOService::setPMRootDomain( class IOPMrootDomain
* rootDomain
)
865 gIOPMRootDomain
= rootDomain
;
866 publishResource("IOKit");
873 bool IOService::lockForArbitration( bool isSuccessRequired
)
877 ArbitrationLockQueueElement
* element
;
878 ArbitrationLockQueueElement
* active
;
879 ArbitrationLockQueueElement
* waiting
;
881 enum { kPutOnFreeQueue
, kPutOnActiveQueue
, kPutOnWaitingQueue
} action
;
883 // lock global access
884 IOTakeLock( gArbitrationLockQueueLock
);
886 // obtain an unused queue element
887 if( !queue_empty( &gArbitrationLockQueueFree
)) {
888 queue_remove_first( &gArbitrationLockQueueFree
,
890 ArbitrationLockQueueElement
*,
893 element
= IONew( ArbitrationLockQueueElement
, 1 );
897 // prepare the queue element
898 element
->thread
= IOThreadSelf();
899 element
->service
= this;
901 element
->required
= isSuccessRequired
;
902 element
->aborted
= false;
904 // determine whether this object is already locked (ie. on active queue)
906 queue_iterate( &gArbitrationLockQueueActive
,
908 ArbitrationLockQueueElement
*,
911 if( active
->service
== element
->service
) {
917 if( found
) { // this object is already locked
919 // determine whether it is the same or a different thread trying to lock
920 if( active
->thread
!= element
->thread
) { // it is a different thread
922 ArbitrationLockQueueElement
* victim
= 0;
924 // before placing this new thread on the waiting queue, we look for
925 // a deadlock cycle...
928 // determine whether the active thread holding the object we
929 // want is waiting for another object to be unlocked
931 queue_iterate( &gArbitrationLockQueueWaiting
,
933 ArbitrationLockQueueElement
*,
936 if( waiting
->thread
== active
->thread
) {
937 assert( false == waiting
->aborted
);
943 if( found
) { // yes, active thread waiting for another object
945 // this may be a candidate for rejection if the required
946 // flag is not set, should we detect a deadlock later on
947 if( false == waiting
->required
)
950 // find the thread that is holding this other object, that
951 // is blocking the active thread from proceeding (fun :-)
953 queue_iterate( &gArbitrationLockQueueActive
,
954 active
, // (reuse active queue element)
955 ArbitrationLockQueueElement
*,
958 if( active
->service
== waiting
->service
) {
964 // someone must be holding it or it wouldn't be waiting
967 if( active
->thread
== element
->thread
) {
969 // doh, it's waiting for the thread that originated
970 // this whole lock (ie. current thread) -> deadlock
971 if( false == element
->required
) { // willing to fail?
973 // the originating thread doesn't have the required
974 // flag, so it can fail
975 success
= false; // (fail originating lock request)
976 break; // (out of while)
978 } else { // originating thread is not willing to fail
980 // see if we came across a waiting thread that did
981 // not have the 'required' flag set: we'll fail it
984 // we do have a willing victim, fail it's lock
985 victim
->aborted
= true;
987 // take the victim off the waiting queue
988 queue_remove( &gArbitrationLockQueueWaiting
,
990 ArbitrationLockQueueElement
*,
994 IOLockWakeup( gArbitrationLockQueueLock
,
996 /* one thread */ true );
998 // allow this thread to proceed (ie. wait)
999 success
= true; // (put request on wait queue)
1000 break; // (out of while)
1003 // all the waiting threads we came across in
1004 // finding this loop had the 'required' flag
1005 // set, so we've got a deadlock we can't avoid
1006 panic("I/O Kit: Unrecoverable deadlock.");
1010 // repeat while loop, redefining active thread to be the
1011 // thread holding "this other object" (see above), and
1012 // looking for threads waiting on it; note the active
1013 // variable points to "this other object" already... so
1014 // there nothing to do in this else clause.
1016 } else { // no, active thread is not waiting for another object
1018 success
= true; // (put request on wait queue)
1019 break; // (out of while)
1023 if( success
) { // put the request on the waiting queue?
1024 kern_return_t wait_result
;
1026 // place this thread on the waiting queue and put it to sleep;
1027 // we place it at the tail of the queue...
1028 queue_enter( &gArbitrationLockQueueWaiting
,
1030 ArbitrationLockQueueElement
*,
1033 // declare that this thread will wait for a given event
1034 restart_sleep
: wait_result
= assert_wait( element
,
1035 element
->required
? THREAD_UNINT
1036 : THREAD_INTERRUPTIBLE
);
1038 // unlock global access
1039 IOUnlock( gArbitrationLockQueueLock
);
1041 // put thread to sleep, waiting for our event to fire...
1042 if (wait_result
== THREAD_WAITING
)
1043 wait_result
= thread_block(THREAD_CONTINUE_NULL
);
1046 // ...and we've been woken up; we might be in one of two states:
1047 // (a) we've been aborted and our queue element is not on
1048 // any of the three queues, but is floating around
1049 // (b) we're allowed to proceed with the lock and we have
1050 // already been moved from the waiting queue to the
1052 // ...plus a 3rd state, should the thread have been interrupted:
1053 // (c) we're still on the waiting queue
1055 // determine whether we were interrupted out of our sleep
1056 if( THREAD_INTERRUPTED
== wait_result
) {
1058 // re-lock global access
1059 IOTakeLock( gArbitrationLockQueueLock
);
1061 // determine whether we're still on the waiting queue
1063 queue_iterate( &gArbitrationLockQueueWaiting
,
1064 waiting
, // (reuse waiting queue element)
1065 ArbitrationLockQueueElement
*,
1068 if( waiting
== element
) {
1074 if( found
) { // yes, we're still on the waiting queue
1076 // determine whether we're willing to fail
1077 if( false == element
->required
) {
1079 // mark us as aborted
1080 element
->aborted
= true;
1082 // take us off the waiting queue
1083 queue_remove( &gArbitrationLockQueueWaiting
,
1085 ArbitrationLockQueueElement
*,
1087 } else { // we are not willing to fail
1089 // ignore interruption, go back to sleep
1094 // unlock global access
1095 IOUnlock( gArbitrationLockQueueLock
);
1097 // proceed as though this were a normal wake up
1098 wait_result
= THREAD_AWAKENED
;
1101 assert( THREAD_AWAKENED
== wait_result
);
1103 // determine whether we've been aborted while we were asleep
1104 if( element
->aborted
) {
1105 assert( false == element
->required
);
1107 // re-lock global access
1108 IOTakeLock( gArbitrationLockQueueLock
);
1110 action
= kPutOnFreeQueue
;
1112 } else { // we weren't aborted, so we must be ready to go :-)
1114 // we've already been moved from waiting to active queue
1118 } else { // the lock request is to be failed
1120 // return unused queue element to queue
1121 action
= kPutOnFreeQueue
;
1123 } else { // it is the same thread, recursive access is allowed
1125 // add one level of recursion
1128 // return unused queue element to queue
1129 action
= kPutOnFreeQueue
;
1132 } else { // this object is not already locked, so let this thread through
1133 action
= kPutOnActiveQueue
;
1137 // put the new element on a queue
1138 if( kPutOnActiveQueue
== action
) {
1139 queue_enter( &gArbitrationLockQueueActive
,
1141 ArbitrationLockQueueElement
*,
1143 } else if( kPutOnFreeQueue
== action
) {
1144 queue_enter( &gArbitrationLockQueueFree
,
1146 ArbitrationLockQueueElement
*,
1149 assert( 0 ); // kPutOnWaitingQueue never occurs, handled specially above
1152 // unlock global access
1153 IOUnlock( gArbitrationLockQueueLock
);
1158 void IOService::unlockForArbitration( void )
1161 ArbitrationLockQueueElement
* element
;
1163 // lock global access
1164 IOTakeLock( gArbitrationLockQueueLock
);
1166 // find the lock element for this object (ie. on active queue)
1168 queue_iterate( &gArbitrationLockQueueActive
,
1170 ArbitrationLockQueueElement
*,
1173 if( element
->service
== this ) {
1181 // determine whether the lock has been taken recursively
1182 if( element
->count
> 1 ) {
1183 // undo one level of recursion
1188 // remove it from the active queue
1189 queue_remove( &gArbitrationLockQueueActive
,
1191 ArbitrationLockQueueElement
*,
1194 // put it on the free queue
1195 queue_enter( &gArbitrationLockQueueFree
,
1197 ArbitrationLockQueueElement
*,
1200 // determine whether a thread is waiting for object (head to tail scan)
1202 queue_iterate( &gArbitrationLockQueueWaiting
,
1204 ArbitrationLockQueueElement
*,
1207 if( element
->service
== this ) {
1213 if ( found
) { // we found an interested thread on waiting queue
1215 // remove it from the waiting queue
1216 queue_remove( &gArbitrationLockQueueWaiting
,
1218 ArbitrationLockQueueElement
*,
1221 // put it on the active queue
1222 queue_enter( &gArbitrationLockQueueActive
,
1224 ArbitrationLockQueueElement
*,
1227 // wake the waiting thread
1228 IOLockWakeup( gArbitrationLockQueueLock
,
1230 /* one thread */ true );
1234 // unlock global access
1235 IOUnlock( gArbitrationLockQueueLock
);
1238 void IOService::applyToProviders( IOServiceApplierFunction applier
,
1241 applyToParents( (IORegistryEntryApplierFunction
) applier
,
1242 context
, gIOServicePlane
);
1245 void IOService::applyToClients( IOServiceApplierFunction applier
,
1248 applyToChildren( (IORegistryEntryApplierFunction
) applier
,
1249 context
, gIOServicePlane
);
1258 // send a message to a client or interested party of this service
1259 IOReturn
IOService::messageClient( UInt32 type
, OSObject
* client
,
1260 void * argument
, vm_size_t argSize
)
1263 IOService
* service
;
1264 _IOServiceInterestNotifier
* notify
;
1266 if( (service
= OSDynamicCast( IOService
, client
)))
1267 ret
= service
->message( type
, this, argument
);
1269 else if( (notify
= OSDynamicCast( _IOServiceInterestNotifier
, client
))) {
1271 _IOServiceNotifierInvocation invocation
;
1274 invocation
.thread
= current_thread();
1277 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
1280 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
1281 _IOServiceNotifierInvocation
*, link
);
1287 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
,
1288 type
, this, argument
, argSize
);
1291 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
1292 _IOServiceNotifierInvocation
*, link
);
1293 if( kIOServiceNotifyWaiter
& notify
->state
) {
1294 notify
->state
&= ~kIOServiceNotifyWaiter
;
1295 WAKEUPNOTIFY( notify
);
1300 ret
= kIOReturnSuccess
;
1303 ret
= kIOReturnBadArgument
;
1309 applyToInterestNotifiers(const IORegistryEntry
*target
,
1310 const OSSymbol
* typeOfInterest
,
1311 OSObjectApplierFunction applier
,
1314 OSArray
* copyArray
= 0;
1318 IOCommand
*notifyList
=
1319 OSDynamicCast( IOCommand
, target
->getProperty( typeOfInterest
));
1322 copyArray
= OSArray::withCapacity(1);
1324 // iterate over queue, entry is set to each element in the list
1325 iterqueue(¬ifyList
->fCommandChain
, entry
) {
1326 _IOServiceInterestNotifier
* notify
;
1328 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1329 copyArray
->setObject(notify
);
1338 for( index
= 0; (next
= copyArray
->getObject( index
)); index
++)
1339 (*applier
)(next
, context
);
1340 copyArray
->release();
1344 void IOService::applyToInterested( const OSSymbol
* typeOfInterest
,
1345 OSObjectApplierFunction applier
,
1348 applyToClients( (IOServiceApplierFunction
) applier
, context
);
1349 applyToInterestNotifiers(this, typeOfInterest
, applier
, context
);
1352 struct MessageClientsContext
{
1353 IOService
* service
;
1360 static void messageClientsApplier( OSObject
* object
, void * ctx
)
1363 MessageClientsContext
* context
= (MessageClientsContext
*) ctx
;
1365 ret
= context
->service
->messageClient( context
->type
,
1366 object
, context
->argument
, context
->argSize
);
1367 if( kIOReturnSuccess
!= ret
)
1371 // send a message to all clients
1372 IOReturn
IOService::messageClients( UInt32 type
,
1373 void * argument
, vm_size_t argSize
)
1375 MessageClientsContext context
;
1377 context
.service
= this;
1378 context
.type
= type
;
1379 context
.argument
= argument
;
1380 context
.argSize
= argSize
;
1381 context
.ret
= kIOReturnSuccess
;
1383 applyToInterested( gIOGeneralInterest
,
1384 &messageClientsApplier
, &context
);
1386 return( context
.ret
);
1389 IOReturn
IOService::acknowledgeNotification( IONotificationRef notification
,
1390 IOOptionBits response
)
1392 return( kIOReturnUnsupported
);
1395 IONotifier
* IOService::registerInterest( const OSSymbol
* typeOfInterest
,
1396 IOServiceInterestHandler handler
, void * target
, void * ref
)
1398 _IOServiceInterestNotifier
* notify
= 0;
1400 if( (typeOfInterest
!= gIOGeneralInterest
)
1401 && (typeOfInterest
!= gIOBusyInterest
)
1402 && (typeOfInterest
!= gIOAppPowerStateInterest
)
1403 && (typeOfInterest
!= gIOPriorityPowerStateInterest
))
1406 lockForArbitration();
1407 if( 0 == (__state
[0] & kIOServiceInactiveState
)) {
1409 notify
= new _IOServiceInterestNotifier
;
1410 if( notify
&& !notify
->init()) {
1416 notify
->handler
= handler
;
1417 notify
->target
= target
;
1419 notify
->state
= kIOServiceNotifyEnable
;
1420 queue_init( ¬ify
->handlerInvocations
);
1426 // Get the head of the notifier linked list
1427 IOCommand
*notifyList
= (IOCommand
*) getProperty( typeOfInterest
);
1428 if (!notifyList
|| !OSDynamicCast(IOCommand
, notifyList
)) {
1429 notifyList
= OSTypeAlloc(IOCommand
);
1432 setProperty( typeOfInterest
, notifyList
);
1433 notifyList
->release();
1438 enqueue(¬ifyList
->fCommandChain
, ¬ify
->chain
);
1439 notify
->retain(); // ref'ed while in list
1445 unlockForArbitration();
1450 static void cleanInterestList( OSObject
* head
)
1452 IOCommand
*notifyHead
= OSDynamicCast(IOCommand
, head
);
1457 while ( queue_entry_t entry
= dequeue(¬ifyHead
->fCommandChain
) ) {
1458 queue_next(entry
) = queue_prev(entry
) = 0;
1460 _IOServiceInterestNotifier
* notify
;
1462 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1468 void IOService::unregisterAllInterest( void )
1470 cleanInterestList( getProperty( gIOGeneralInterest
));
1471 cleanInterestList( getProperty( gIOBusyInterest
));
1472 cleanInterestList( getProperty( gIOAppPowerStateInterest
));
1473 cleanInterestList( getProperty( gIOPriorityPowerStateInterest
));
1477 * _IOServiceInterestNotifier
1480 // wait for all threads, other than the current one,
1481 // to exit the handler
1483 void _IOServiceInterestNotifier::wait()
1485 _IOServiceNotifierInvocation
* next
;
1490 queue_iterate( &handlerInvocations
, next
,
1491 _IOServiceNotifierInvocation
*, link
) {
1492 if( next
->thread
!= current_thread() ) {
1498 state
|= kIOServiceNotifyWaiter
;
1505 void _IOServiceInterestNotifier::free()
1507 assert( queue_empty( &handlerInvocations
));
1511 void _IOServiceInterestNotifier::remove()
1515 if( queue_next( &chain
)) {
1516 remqueue( 0, &chain
);
1517 queue_next( &chain
) = queue_prev( &chain
) = 0;
1521 state
&= ~kIOServiceNotifyEnable
;
1530 bool _IOServiceInterestNotifier::disable()
1536 ret
= (0 != (kIOServiceNotifyEnable
& state
));
1537 state
&= ~kIOServiceNotifyEnable
;
1546 void _IOServiceInterestNotifier::enable( bool was
)
1550 state
|= kIOServiceNotifyEnable
;
1552 state
&= ~kIOServiceNotifyEnable
;
1556 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1562 #define tailQ(o) setObject(o)
1563 #define headQ(o) setObject(0, o)
1564 #define TLOG(fmt, args...) { if(kIOLogYield & gIOKitDebug) IOLog(fmt, ## args); }
1566 inline void _workLoopAction( IOWorkLoop::Action action
,
1567 IOService
* service
,
1568 void * p0
= 0, void * p1
= 0,
1569 void * p2
= 0, void * p3
= 0 )
1573 if( (wl
= service
->getWorkLoop())) {
1575 wl
->runAction( action
, service
, p0
, p1
, p2
, p3
);
1578 (*action
)( service
, p0
, p1
, p2
, p3
);
1581 bool IOService::requestTerminate( IOService
* provider
, IOOptionBits options
)
1585 // if its our only provider
1586 ok
= isParent( provider
, gIOServicePlane
, true);
1590 provider
->terminateClient( this, options
| kIOServiceRecursing
);
1591 ok
= (0 != (__state
[1] & kIOServiceRecursing
));
1598 bool IOService::terminatePhase1( IOOptionBits options
)
1603 OSArray
* makeInactive
;
1606 bool startPhase2
= false;
1608 TLOG("%s::terminatePhase1(%08lx)\n", getName(), options
);
1611 if( options
& kIOServiceRecursing
) {
1612 __state
[1] |= kIOServiceRecursing
;
1617 makeInactive
= OSArray::withCapacity( 16 );
1626 didInactive
= victim
->lockForArbitration( true );
1628 didInactive
= (0 == (victim
->__state
[0] & kIOServiceInactiveState
));
1630 victim
->__state
[0] |= kIOServiceInactiveState
;
1631 victim
->__state
[0] &= ~(kIOServiceRegisteredState
| kIOServiceMatchedState
1632 | kIOServiceFirstPublishState
| kIOServiceFirstMatchState
);
1633 victim
->_adjustBusy( 1 );
1635 victim
->unlockForArbitration();
1638 startPhase2
= didInactive
;
1641 victim
->deliverNotification( gIOTerminatedNotification
, 0, 0xffffffff );
1642 IOUserClient::destroyUserReferences( victim
);
1644 iter
= victim
->getClientIterator();
1646 while( (client
= (IOService
*) iter
->getNextObject())) {
1647 TLOG("%s::requestTerminate(%s, %08lx)\n",
1648 client
->getName(), victim
->getName(), options
);
1649 ok
= client
->requestTerminate( victim
, options
);
1650 TLOG("%s::requestTerminate(%s, ok = %d)\n",
1651 client
->getName(), victim
->getName(), ok
);
1653 makeInactive
->setObject( client
);
1659 victim
= (IOService
*) makeInactive
->getObject(0);
1662 makeInactive
->removeObject(0);
1666 makeInactive
->release();
1669 scheduleTerminatePhase2( options
);
1674 void IOService::scheduleTerminatePhase2( IOOptionBits options
)
1676 AbsoluteTime deadline
;
1677 int waitResult
= THREAD_AWAKENED
;
1678 bool wait
, haveDeadline
= false;
1680 options
|= kIOServiceRequired
;
1684 IOLockLock( gJobsLock
);
1686 if( (options
& kIOServiceSynchronous
)
1687 && (current_thread() != gIOTerminateThread
)) {
1690 wait
= (gIOTerminateThread
!= 0);
1692 // wait to become the terminate thread
1693 IOLockSleep( gJobsLock
, &gIOTerminateThread
, THREAD_UNINT
);
1697 gIOTerminateThread
= current_thread();
1698 gIOTerminatePhase2List
->setObject( this );
1702 while( gIOTerminateWork
)
1703 terminateWorker( options
);
1704 wait
= (0 != (__state
[1] & kIOServiceBusyStateMask
));
1706 // wait for the victim to go non-busy
1707 if( !haveDeadline
) {
1708 clock_interval_to_deadline( 15, kSecondScale
, &deadline
);
1709 haveDeadline
= true;
1711 waitResult
= IOLockSleepDeadline( gJobsLock
, &gIOTerminateWork
,
1712 deadline
, THREAD_UNINT
);
1713 if( waitResult
== THREAD_TIMED_OUT
) {
1714 TLOG("%s::terminate(kIOServiceSynchronous) timeout", getName());
1717 } while(gIOTerminateWork
|| (wait
&& (waitResult
!= THREAD_TIMED_OUT
)));
1719 gIOTerminateThread
= 0;
1720 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1723 // ! kIOServiceSynchronous
1725 gIOTerminatePhase2List
->setObject( this );
1726 if( 0 == gIOTerminateWork
++) {
1727 if( !gIOTerminateThread
)
1728 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) options
);
1730 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1734 IOLockUnlock( gJobsLock
);
1739 void IOService::terminateThread( void * arg
)
1741 IOLockLock( gJobsLock
);
1743 while (gIOTerminateWork
)
1744 terminateWorker( (IOOptionBits
) arg
);
1746 gIOTerminateThread
= 0;
1747 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1749 IOLockUnlock( gJobsLock
);
1752 void IOService::scheduleStop( IOService
* provider
)
1754 TLOG("%s::scheduleStop(%s)\n", getName(), provider
->getName());
1756 IOLockLock( gJobsLock
);
1757 gIOStopList
->tailQ( this );
1758 gIOStopProviderList
->tailQ( provider
);
1760 if( 0 == gIOTerminateWork
++) {
1761 if( !gIOTerminateThread
)
1762 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) 0 );
1764 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1767 IOLockUnlock( gJobsLock
);
1770 void IOService::scheduleFinalize( void )
1772 TLOG("%s::scheduleFinalize\n", getName());
1774 IOLockLock( gJobsLock
);
1775 gIOFinalizeList
->tailQ( this );
1777 if( 0 == gIOTerminateWork
++) {
1778 if( !gIOTerminateThread
)
1779 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) 0 );
1781 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1784 IOLockUnlock( gJobsLock
);
1787 bool IOService::willTerminate( IOService
* provider
, IOOptionBits options
)
1792 bool IOService::didTerminate( IOService
* provider
, IOOptionBits options
, bool * defer
)
1794 if( false == *defer
) {
1796 if( lockForArbitration( true )) {
1797 if( false == provider
->handleIsOpen( this ))
1798 scheduleStop( provider
);
1801 message( kIOMessageServiceIsRequestingClose
, provider
, (void *) options
);
1802 if( false == provider
->handleIsOpen( this ))
1803 scheduleStop( provider
);
1806 unlockForArbitration();
1813 void IOService::actionWillTerminate( IOService
* victim
, IOOptionBits options
,
1814 OSArray
* doPhase2List
)
1820 iter
= victim
->getClientIterator();
1822 while( (client
= (IOService
*) iter
->getNextObject())) {
1823 TLOG("%s::willTerminate(%s, %08lx)\n",
1824 client
->getName(), victim
->getName(), options
);
1825 ok
= client
->willTerminate( victim
, options
);
1826 doPhase2List
->tailQ( client
);
1832 void IOService::actionDidTerminate( IOService
* victim
, IOOptionBits options
)
1838 victim
->messageClients( kIOMessageServiceIsTerminated
, (void *) options
);
1840 iter
= victim
->getClientIterator();
1842 while( (client
= (IOService
*) iter
->getNextObject())) {
1843 TLOG("%s::didTerminate(%s, %08lx)\n",
1844 client
->getName(), victim
->getName(), options
);
1845 client
->didTerminate( victim
, options
, &defer
);
1846 TLOG("%s::didTerminate(%s, defer %d)\n",
1847 client
->getName(), victim
->getName(), defer
);
1853 void IOService::actionFinalize( IOService
* victim
, IOOptionBits options
)
1855 TLOG("%s::finalize(%08lx)\n", victim
->getName(), options
);
1856 victim
->finalize( options
);
1859 void IOService::actionStop( IOService
* provider
, IOService
* client
)
1861 TLOG("%s::stop(%s)\n", client
->getName(), provider
->getName());
1862 client
->stop( provider
);
1863 if( provider
->isOpen( client
))
1864 provider
->close( client
);
1865 TLOG("%s::detach(%s)\n", client
->getName(), provider
->getName());
1866 client
->detach( provider
);
1869 void IOService::terminateWorker( IOOptionBits options
)
1871 OSArray
* doPhase2List
;
1872 OSArray
* didPhase2List
;
1877 IOService
* provider
;
1883 options
|= kIOServiceRequired
;
1885 doPhase2List
= OSArray::withCapacity( 16 );
1886 didPhase2List
= OSArray::withCapacity( 16 );
1887 freeList
= OSSet::withCapacity( 16 );
1888 if( (0 == doPhase2List
) || (0 == didPhase2List
) || (0 == freeList
))
1892 workDone
= gIOTerminateWork
;
1894 while( (victim
= (IOService
*) gIOTerminatePhase2List
->getObject(0) )) {
1897 gIOTerminatePhase2List
->removeObject(0);
1898 IOLockUnlock( gJobsLock
);
1902 doPhase2
= victim
->lockForArbitration( true );
1904 doPhase2
= (0 != (kIOServiceInactiveState
& victim
->__state
[0]));
1906 doPhase2
= (0 == (victim
->__state
[1] & kIOServiceTermPhase2State
))
1907 && (0 == (victim
->__state
[1] & kIOServiceConfigState
));
1909 victim
->__state
[1] |= kIOServiceTermPhase2State
;
1911 victim
->unlockForArbitration();
1914 if( 0 == victim
->getClient()) {
1915 // no clients - will go to finalize
1916 IOLockLock( gJobsLock
);
1917 gIOFinalizeList
->tailQ( victim
);
1918 IOLockUnlock( gJobsLock
);
1920 _workLoopAction( (IOWorkLoop::Action
) &actionWillTerminate
,
1921 victim
, (void *) options
, (void *) doPhase2List
);
1923 didPhase2List
->headQ( victim
);
1926 victim
= (IOService
*) doPhase2List
->getObject(0);
1929 doPhase2List
->removeObject(0);
1933 while( (victim
= (IOService
*) didPhase2List
->getObject(0)) ) {
1935 if( victim
->lockForArbitration( true )) {
1936 victim
->__state
[1] |= kIOServiceTermPhase3State
;
1937 victim
->unlockForArbitration();
1939 _workLoopAction( (IOWorkLoop::Action
) &actionDidTerminate
,
1940 victim
, (void *) options
);
1941 didPhase2List
->removeObject(0);
1943 IOLockLock( gJobsLock
);
1950 while( (victim
= (IOService
*) gIOFinalizeList
->getObject(0))) {
1952 IOLockUnlock( gJobsLock
);
1953 _workLoopAction( (IOWorkLoop::Action
) &actionFinalize
,
1954 victim
, (void *) options
);
1955 IOLockLock( gJobsLock
);
1957 freeList
->setObject( victim
);
1958 // safe if finalize list is append only
1959 gIOFinalizeList
->removeObject(0);
1963 (!doPhase3
) && (client
= (IOService
*) gIOStopList
->getObject(idx
)); ) {
1965 provider
= (IOService
*) gIOStopProviderList
->getObject(idx
);
1968 if( !provider
->isChild( client
, gIOServicePlane
)) {
1969 // may be multiply queued - nop it
1970 TLOG("%s::nop stop(%s)\n", client
->getName(), provider
->getName());
1972 // not ready for stop if it has clients, skip it
1973 if( (client
->__state
[1] & kIOServiceTermPhase3State
) && client
->getClient()) {
1974 TLOG("%s::defer stop(%s)\n", client
->getName(), provider
->getName());
1979 IOLockUnlock( gJobsLock
);
1980 _workLoopAction( (IOWorkLoop::Action
) &actionStop
,
1981 provider
, (void *) client
);
1982 IOLockLock( gJobsLock
);
1983 // check the finalize list now
1987 freeList
->setObject( client
);
1988 freeList
->setObject( provider
);
1990 // safe if stop list is append only
1991 gIOStopList
->removeObject( idx
);
1992 gIOStopProviderList
->removeObject( idx
);
1996 } while( doPhase3
);
1998 gIOTerminateWork
-= workDone
;
1999 moreToDo
= (gIOTerminateWork
!= 0);
2002 TLOG("iokit terminate done, %d stops remain\n", gIOStopList
->getCount());
2005 } while( moreToDo
);
2007 IOLockUnlock( gJobsLock
);
2009 freeList
->release();
2010 doPhase2List
->release();
2011 didPhase2List
->release();
2013 IOLockLock( gJobsLock
);
2016 bool IOService::finalize( IOOptionBits options
)
2019 IOService
* provider
;
2021 iter
= getProviderIterator();
2025 while( (provider
= (IOService
*) iter
->getNextObject())) {
2028 if( 0 == (__state
[1] & kIOServiceTermPhase3State
)) {
2029 /* we come down here on programmatic terminate */
2031 if( provider
->isOpen( this ))
2032 provider
->close( this );
2036 if( provider
->lockForArbitration( true )) {
2037 if( 0 == (provider
->__state
[1] & kIOServiceTermPhase3State
))
2038 scheduleStop( provider
);
2039 provider
->unlockForArbitration();
2056 void IOService::doServiceTerminate( IOOptionBits options
)
2060 // a method in case someone needs to override it
2061 bool IOService::terminateClient( IOService
* client
, IOOptionBits options
)
2065 if( client
->isParent( this, gIOServicePlane
, true))
2066 // we are the clients only provider
2067 ok
= client
->terminate( options
);
2074 bool IOService::terminate( IOOptionBits options
)
2076 options
|= kIOServiceTerminate
;
2078 return( terminatePhase1( options
));
2081 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2087 struct ServiceOpenMessageContext
2089 IOService
* service
;
2091 IOService
* excludeClient
;
2092 IOOptionBits options
;
2095 static void serviceOpenMessageApplier( OSObject
* object
, void * ctx
)
2097 ServiceOpenMessageContext
* context
= (ServiceOpenMessageContext
*) ctx
;
2099 if( object
!= context
->excludeClient
)
2100 context
->service
->messageClient( context
->type
, object
, (void *) context
->options
);
2103 bool IOService::open( IOService
* forClient
,
2104 IOOptionBits options
,
2108 ServiceOpenMessageContext context
;
2110 context
.service
= this;
2111 context
.type
= kIOMessageServiceIsAttemptingOpen
;
2112 context
.excludeClient
= forClient
;
2113 context
.options
= options
;
2115 applyToInterested( gIOGeneralInterest
,
2116 &serviceOpenMessageApplier
, &context
);
2118 if( false == lockForArbitration(false) )
2121 ok
= (0 == (__state
[0] & kIOServiceInactiveState
));
2123 ok
= handleOpen( forClient
, options
, arg
);
2125 unlockForArbitration();
2130 void IOService::close( IOService
* forClient
,
2131 IOOptionBits options
)
2136 lockForArbitration();
2138 wasClosed
= handleIsOpen( forClient
);
2140 handleClose( forClient
, options
);
2141 last
= (__state
[1] & kIOServiceTermPhase3State
);
2144 unlockForArbitration();
2147 forClient
->scheduleStop( this );
2149 else if( wasClosed
) {
2151 ServiceOpenMessageContext context
;
2153 context
.service
= this;
2154 context
.type
= kIOMessageServiceWasClosed
;
2155 context
.excludeClient
= forClient
;
2156 context
.options
= options
;
2158 applyToInterested( gIOGeneralInterest
,
2159 &serviceOpenMessageApplier
, &context
);
2163 bool IOService::isOpen( const IOService
* forClient
) const
2165 IOService
* self
= (IOService
*) this;
2168 self
->lockForArbitration();
2170 ok
= handleIsOpen( forClient
);
2172 self
->unlockForArbitration();
2177 bool IOService::handleOpen( IOService
* forClient
,
2178 IOOptionBits options
,
2183 ok
= (0 == __owner
);
2185 __owner
= forClient
;
2187 else if( options
& kIOServiceSeize
) {
2188 ok
= (kIOReturnSuccess
== messageClient( kIOMessageServiceIsRequestingClose
,
2189 __owner
, (void *) options
));
2190 if( ok
&& (0 == __owner
))
2191 __owner
= forClient
;
2198 void IOService::handleClose( IOService
* forClient
,
2199 IOOptionBits options
)
2201 if( __owner
== forClient
)
2205 bool IOService::handleIsOpen( const IOService
* forClient
) const
2208 return( __owner
== forClient
);
2210 return( __owner
!= forClient
);
2214 * Probing & starting
2216 static SInt32
IONotifyOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2218 const _IOServiceNotifier
* obj1
= (const _IOServiceNotifier
*) inObj1
;
2219 const _IOServiceNotifier
* obj2
= (const _IOServiceNotifier
*) inObj2
;
2227 val1
= obj1
->priority
;
2230 val2
= obj2
->priority
;
2232 return ( val1
- val2
);
2235 static SInt32
IOServiceObjectOrder( const OSObject
* entry
, void * ref
)
2237 OSDictionary
* dict
;
2238 IOService
* service
;
2239 _IOServiceNotifier
* notify
;
2240 OSSymbol
* key
= (OSSymbol
*) ref
;
2243 if( (notify
= OSDynamicCast( _IOServiceNotifier
, entry
)))
2244 return( notify
->priority
);
2246 else if( (service
= OSDynamicCast( IOService
, entry
)))
2247 offset
= OSDynamicCast(OSNumber
, service
->getProperty( key
));
2248 else if( (dict
= OSDynamicCast( OSDictionary
, entry
)))
2249 offset
= OSDynamicCast(OSNumber
, dict
->getObject( key
));
2256 return( (SInt32
) offset
->unsigned32BitValue());
2258 return( kIODefaultProbeScore
);
2261 SInt32
IOServiceOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2263 const OSObject
* obj1
= (const OSObject
*) inObj1
;
2264 const OSObject
* obj2
= (const OSObject
*) inObj2
;
2272 val1
= IOServiceObjectOrder( obj1
, ref
);
2275 val2
= IOServiceObjectOrder( obj2
, ref
);
2277 return ( val1
- val2
);
2280 IOService
* IOService::getClientWithCategory( const OSSymbol
* category
)
2282 IOService
* service
= 0;
2284 const OSSymbol
* nextCat
;
2286 iter
= getClientIterator();
2288 while( (service
= (IOService
*) iter
->getNextObject())) {
2289 if( kIOServiceInactiveState
& service
->__state
[0])
2291 nextCat
= (const OSSymbol
*) OSDynamicCast( OSSymbol
,
2292 service
->getProperty( gIOMatchCategoryKey
));
2293 if( category
== nextCat
)
2301 bool IOService::invokeNotifer( _IOServiceNotifier
* notify
)
2303 _IOServiceNotifierInvocation invocation
;
2307 invocation
.thread
= current_thread();
2310 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
2313 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
2314 _IOServiceNotifierInvocation
*, link
);
2320 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
, this );
2323 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
2324 _IOServiceNotifierInvocation
*, link
);
2325 if( kIOServiceNotifyWaiter
& notify
->state
) {
2326 notify
->state
&= ~kIOServiceNotifyWaiter
;
2327 WAKEUPNOTIFY( notify
);
2336 * Alloc and probe matching classes,
2337 * called on the provider instance
2340 void IOService::probeCandidates( OSOrderedSet
* matches
)
2342 OSDictionary
* match
= 0;
2345 IOService
* newInst
;
2346 OSDictionary
* props
;
2349 OSOrderedSet
* familyMatches
= 0;
2350 OSOrderedSet
* startList
;
2351 OSDictionary
* startDict
= 0;
2352 const OSSymbol
* category
;
2354 _IOServiceNotifier
* notify
;
2355 OSObject
* nextMatch
= 0;
2357 bool needReloc
= false;
2363 while( !needReloc
&& (nextMatch
= matches
->getFirstObject())) {
2365 nextMatch
->retain();
2366 matches
->removeObject(nextMatch
);
2368 if( (notify
= OSDynamicCast( _IOServiceNotifier
, nextMatch
))) {
2370 lockForArbitration();
2371 if( 0 == (__state
[0] & kIOServiceInactiveState
))
2372 invokeNotifer( notify
);
2373 unlockForArbitration();
2374 nextMatch
->release();
2378 } else if( !(match
= OSDynamicCast( OSDictionary
, nextMatch
))) {
2379 nextMatch
->release();
2386 debugFlags
= getDebugFlags( match
);
2390 category
= OSDynamicCast( OSSymbol
,
2391 match
->getObject( gIOMatchCategoryKey
));
2393 category
= gIODefaultMatchCategoryKey
;
2395 if( getClientWithCategory( category
)) {
2397 if( debugFlags
& kIOLogMatch
)
2398 LOG("%s: match category %s exists\n", getName(),
2399 category
->getCStringNoCopy());
2401 nextMatch
->release();
2406 // create a copy now in case its modified during matching
2407 props
= OSDictionary::withDictionary( match
, match
->getCount());
2410 props
->setCapacityIncrement(1);
2412 // check the nub matches
2413 if( false == passiveMatch( props
, true ))
2416 // Check to see if driver reloc has been loaded.
2417 needReloc
= (false == gIOCatalogue
->isModuleLoaded( match
));
2420 if( debugFlags
& kIOLogCatalogue
)
2421 LOG("%s: stalling for module\n", getName());
2423 // If reloc hasn't been loaded, exit;
2424 // reprobing will occur after reloc has been loaded.
2428 // reorder on family matchPropertyTable score.
2429 if( 0 == familyMatches
)
2430 familyMatches
= OSOrderedSet::withCapacity( 1,
2431 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2433 familyMatches
->setObject( props
);
2438 nextMatch
->release();
2447 if( familyMatches
) {
2450 && (props
= (OSDictionary
*) familyMatches
->getFirstObject())) {
2453 familyMatches
->removeObject( props
);
2458 debugFlags
= getDebugFlags( props
);
2461 symbol
= OSDynamicCast( OSSymbol
,
2462 props
->getObject( gIOClassKey
));
2466 // alloc the driver instance
2467 inst
= (IOService
*) OSMetaClass::allocClassWithName( symbol
);
2470 IOLog("Couldn't alloc class \"%s\"\n",
2471 symbol
->getCStringNoCopy());
2475 // init driver instance
2476 if( !(inst
->init( props
))) {
2478 if( debugFlags
& kIOLogStart
)
2479 IOLog("%s::init fails\n", symbol
->getCStringNoCopy());
2483 if( __state
[1] & kIOServiceSynchronousState
)
2484 inst
->__state
[1] |= kIOServiceSynchronousState
;
2486 // give the driver the default match category if not specified
2487 category
= OSDynamicCast( OSSymbol
,
2488 props
->getObject( gIOMatchCategoryKey
));
2490 category
= gIODefaultMatchCategoryKey
;
2491 inst
->setProperty( gIOMatchCategoryKey
, (OSObject
*) category
);
2493 // attach driver instance
2494 if( !(inst
->attach( this )))
2497 // pass in score from property table
2498 score
= familyMatches
->orderObject( props
);
2500 // & probe the new driver instance
2502 if( debugFlags
& kIOLogProbe
)
2503 LOG("%s::probe(%s)\n",
2504 inst
->getMetaClass()->getClassName(), getName());
2507 newInst
= inst
->probe( this, &score
);
2508 inst
->detach( this );
2511 if( debugFlags
& kIOLogProbe
)
2512 IOLog("%s::probe fails\n", symbol
->getCStringNoCopy());
2518 newPri
= OSNumber::withNumber( score
, 32 );
2520 newInst
->setProperty( gIOProbeScoreKey
, newPri
);
2524 // add to start list for the match category
2526 startDict
= OSDictionary::withCapacity( 1 );
2527 assert( startDict
);
2528 startList
= (OSOrderedSet
*)
2529 startDict
->getObject( category
);
2530 if( 0 == startList
) {
2531 startList
= OSOrderedSet::withCapacity( 1,
2532 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2533 if( startDict
&& startList
) {
2534 startDict
->setObject( category
, startList
);
2535 startList
->release();
2538 assert( startList
);
2540 startList
->setObject( newInst
);
2548 familyMatches
->release();
2552 // start the best (until success) of each category
2554 iter
= OSCollectionIterator::withCollection( startDict
);
2556 while( (category
= (const OSSymbol
*) iter
->getNextObject())) {
2558 startList
= (OSOrderedSet
*) startDict
->getObject( category
);
2559 assert( startList
);
2564 while( true // (!started)
2565 && (inst
= (IOService
*)startList
->getFirstObject())) {
2568 startList
->removeObject(inst
);
2571 debugFlags
= getDebugFlags( inst
->getPropertyTable() );
2573 if( debugFlags
& kIOLogStart
) {
2575 LOG( "match category exists, skipping " );
2576 LOG( "%s::start(%s) <%d>\n", inst
->getName(),
2577 getName(), inst
->getRetainCount());
2580 if( false == started
)
2581 started
= startCandidate( inst
);
2583 if( (debugFlags
& kIOLogStart
) && (false == started
))
2584 LOG( "%s::start(%s) <%d> failed\n", inst
->getName(), getName(),
2585 inst
->getRetainCount());
2594 // adjust the busy count by -1 if matching is stalled for a module,
2595 // or +1 if a previously stalled matching is complete.
2596 lockForArbitration();
2599 adjBusy
= (__state
[1] & kIOServiceModuleStallState
) ? 0 : 1;
2601 __state
[1] |= kIOServiceModuleStallState
;
2603 } else if( __state
[1] & kIOServiceModuleStallState
) {
2604 __state
[1] &= ~kIOServiceModuleStallState
;
2608 _adjustBusy( adjBusy
);
2609 unlockForArbitration();
2612 startDict
->release();
2616 * Start a previously attached & probed instance,
2617 * called on exporting object instance
2620 bool IOService::startCandidate( IOService
* service
)
2624 ok
= service
->attach( this );
2628 if (this != gIOResources
)
2630 // stall for any nub resources
2632 // stall for any driver resources
2633 service
->checkResources();
2636 AbsoluteTime startTime
;
2637 AbsoluteTime endTime
;
2640 if (kIOLogStart
& gIOKitDebug
)
2641 clock_get_uptime(&startTime
);
2643 ok
= service
->start(this);
2645 if (kIOLogStart
& gIOKitDebug
)
2647 clock_get_uptime(&endTime
);
2649 if (CMP_ABSOLUTETIME(&endTime
, &startTime
) > 0)
2651 SUB_ABSOLUTETIME(&endTime
, &startTime
);
2652 absolutetime_to_nanoseconds(endTime
, &nano
);
2653 if (nano
> 500000000ULL)
2654 IOLog("%s::start took %ld ms\n", service
->getName(), (UInt32
)(nano
/ 1000000ULL));
2658 service
->detach( this );
2663 IOService
* IOService::resources( void )
2665 return( gIOResources
);
2668 void IOService::publishResource( const char * key
, OSObject
* value
)
2670 const OSSymbol
* sym
;
2672 if( (sym
= OSSymbol::withCString( key
))) {
2673 publishResource( sym
, value
);
2678 void IOService::publishResource( const OSSymbol
* key
, OSObject
* value
)
2681 value
= (OSObject
*) gIOServiceKey
;
2683 gIOResources
->setProperty( key
, value
);
2685 if( IORecursiveLockHaveLock( gNotificationLock
))
2688 gIOResourceGenerationCount
++;
2689 gIOResources
->registerService();
2692 bool IOService::addNeededResource( const char * key
)
2694 OSObject
* resourcesProp
;
2699 resourcesProp
= getProperty( gIOResourceMatchKey
);
2701 newKey
= OSString::withCString( key
);
2702 if( (0 == resourcesProp
) || (0 == newKey
))
2705 set
= OSDynamicCast( OSSet
, resourcesProp
);
2707 set
= OSSet::withCapacity( 1 );
2709 set
->setObject( resourcesProp
);
2714 set
->setObject( newKey
);
2716 ret
= setProperty( gIOResourceMatchKey
, set
);
2722 bool IOService::checkResource( OSObject
* matching
)
2725 OSDictionary
* table
;
2727 if( (str
= OSDynamicCast( OSString
, matching
))) {
2728 if( gIOResources
->getProperty( str
))
2733 table
= resourceMatching( str
);
2734 else if( (table
= OSDynamicCast( OSDictionary
, matching
)))
2737 IOLog("%s: Can't match using: %s\n", getName(),
2738 matching
->getMetaClass()->getClassName());
2739 /* false would stall forever */
2743 if( gIOKitDebug
& kIOLogConfig
)
2744 LOG("config(%x): stalling %s\n", (int) IOThreadSelf(), getName());
2746 waitForService( table
);
2748 if( gIOKitDebug
& kIOLogConfig
)
2749 LOG("config(%x): waking\n", (int) IOThreadSelf() );
2754 bool IOService::checkResources( void )
2756 OSObject
* resourcesProp
;
2761 resourcesProp
= getProperty( gIOResourceMatchKey
);
2762 if( 0 == resourcesProp
)
2765 if( (set
= OSDynamicCast( OSSet
, resourcesProp
))) {
2767 iter
= OSCollectionIterator::withCollection( set
);
2769 while( ok
&& (resourcesProp
= iter
->getNextObject()) )
2770 ok
= checkResource( resourcesProp
);
2775 ok
= checkResource( resourcesProp
);
2781 void _IOConfigThread::configThread( void )
2783 _IOConfigThread
* inst
;
2786 if( !(inst
= new _IOConfigThread
))
2790 if( !(IOCreateThread((IOThreadFunc
) &_IOConfigThread::main
, inst
)))
2803 void _IOConfigThread::free( void )
2808 void IOService::doServiceMatch( IOOptionBits options
)
2810 _IOServiceNotifier
* notify
;
2812 OSOrderedSet
* matches
;
2813 SInt32 catalogGeneration
;
2814 bool keepGuessing
= true;
2815 bool reRegistered
= true;
2817 // job->nub->deliverNotification( gIOPublishNotification,
2818 // kIOServiceRegisteredState, 0xffffffff );
2820 while( keepGuessing
) {
2822 matches
= gIOCatalogue
->findDrivers( this, &catalogGeneration
);
2823 // the matches list should always be created by findDrivers()
2826 lockForArbitration();
2827 if( 0 == (__state
[0] & kIOServiceFirstPublishState
))
2828 deliverNotification( gIOFirstPublishNotification
,
2829 kIOServiceFirstPublishState
, 0xffffffff );
2831 __state
[1] &= ~kIOServiceNeedConfigState
;
2832 __state
[1] |= kIOServiceConfigState
;
2833 __state
[0] |= kIOServiceRegisteredState
;
2835 if( reRegistered
&& (0 == (__state
[0] & kIOServiceInactiveState
))) {
2837 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
2838 gNotifications
->getObject( gIOPublishNotification
) );
2840 while((notify
= (_IOServiceNotifier
*)
2841 iter
->getNextObject())) {
2843 if( passiveMatch( notify
->matching
)
2844 && (kIOServiceNotifyEnable
& notify
->state
))
2845 matches
->setObject( notify
);
2852 unlockForArbitration();
2854 if( matches
->getCount() && (kIOReturnSuccess
== getResources()))
2855 probeCandidates( matches
);
2860 lockForArbitration();
2861 reRegistered
= (0 != (__state
[1] & kIOServiceNeedConfigState
));
2863 (reRegistered
|| (catalogGeneration
!=
2864 gIOCatalogue
->getGenerationCount()))
2865 && (0 == (__state
[0] & kIOServiceInactiveState
));
2868 unlockForArbitration();
2871 if( (0 == (__state
[0] & kIOServiceInactiveState
))
2872 && (0 == (__state
[1] & kIOServiceModuleStallState
)) ) {
2873 deliverNotification( gIOMatchedNotification
,
2874 kIOServiceMatchedState
, 0xffffffff );
2875 if( 0 == (__state
[0] & kIOServiceFirstMatchState
))
2876 deliverNotification( gIOFirstMatchNotification
,
2877 kIOServiceFirstMatchState
, 0xffffffff );
2880 __state
[1] &= ~kIOServiceConfigState
;
2881 if( __state
[0] & kIOServiceInactiveState
)
2882 scheduleTerminatePhase2();
2885 unlockForArbitration();
2888 UInt32
IOService::_adjustBusy( SInt32 delta
)
2893 bool wasQuiet
, nowQuiet
, needWake
;
2896 result
= __state
[1] & kIOServiceBusyStateMask
;
2900 next
->lockForArbitration();
2901 count
= next
->__state
[1] & kIOServiceBusyStateMask
;
2902 assert( count
< kIOServiceBusyMax
);
2903 wasQuiet
= (0 == count
);
2904 assert( (!wasQuiet
) || (delta
> 0));
2905 next
->__state
[1] += delta
;
2906 nowQuiet
= (0 == (next
->__state
[1] & kIOServiceBusyStateMask
));
2907 needWake
= (0 != (kIOServiceBusyWaiterState
& next
->__state
[1]));
2910 next
->__state
[1] &= ~kIOServiceBusyWaiterState
;
2911 IOLockLock( gIOServiceBusyLock
);
2912 thread_wakeup( (event_t
) next
);
2913 IOLockUnlock( gIOServiceBusyLock
);
2916 next
->unlockForArbitration();
2918 if( (wasQuiet
|| nowQuiet
) ) {
2919 MessageClientsContext context
;
2921 context
.service
= next
;
2922 context
.type
= kIOMessageServiceBusyStateChange
;
2923 context
.argument
= (void *) wasQuiet
; // busy now
2924 context
.argSize
= 0;
2926 applyToInterestNotifiers( next
, gIOBusyInterest
,
2927 &messageClientsApplier
, &context
);
2929 if( nowQuiet
&& (next
== gIOServiceRoot
))
2930 OSMetaClass::considerUnloads();
2933 delta
= nowQuiet
? -1 : +1;
2935 } while( (wasQuiet
|| nowQuiet
) && (next
= next
->getProvider()));
2940 void IOService::adjustBusy( SInt32 delta
)
2942 lockForArbitration();
2943 _adjustBusy( delta
);
2944 unlockForArbitration();
2947 UInt32
IOService::getBusyState( void )
2949 return( __state
[1] & kIOServiceBusyStateMask
);
2952 IOReturn
IOService::waitForState( UInt32 mask
, UInt32 value
,
2953 mach_timespec_t
* timeout
)
2956 int waitResult
= THREAD_AWAKENED
;
2957 bool computeDeadline
= true;
2958 AbsoluteTime abstime
;
2961 lockForArbitration();
2962 IOLockLock( gIOServiceBusyLock
);
2963 wait
= (value
!= (__state
[1] & mask
));
2965 __state
[1] |= kIOServiceBusyWaiterState
;
2966 unlockForArbitration();
2968 if( computeDeadline
) {
2969 AbsoluteTime nsinterval
;
2970 clock_interval_to_absolutetime_interval(
2971 timeout
->tv_sec
, kSecondScale
, &abstime
);
2972 clock_interval_to_absolutetime_interval(
2973 timeout
->tv_nsec
, kNanosecondScale
, &nsinterval
);
2974 ADD_ABSOLUTETIME( &abstime
, &nsinterval
);
2975 clock_absolutetime_interval_to_deadline(
2976 abstime
, &abstime
);
2977 computeDeadline
= false;
2980 assert_wait_deadline((event_t
)this, THREAD_UNINT
, __OSAbsoluteTime(abstime
));
2983 assert_wait((event_t
)this, THREAD_UNINT
);
2985 unlockForArbitration();
2986 IOLockUnlock( gIOServiceBusyLock
);
2988 waitResult
= thread_block(THREAD_CONTINUE_NULL
);
2990 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
2992 if( waitResult
== THREAD_TIMED_OUT
)
2993 return( kIOReturnTimeout
);
2995 return( kIOReturnSuccess
);
2998 IOReturn
IOService::waitQuiet( mach_timespec_t
* timeout
)
3000 return( waitForState( kIOServiceBusyStateMask
, 0, timeout
));
3003 bool IOService::serializeProperties( OSSerialize
* s
) const
3006 ((IOService
*)this)->setProperty( ((IOService
*)this)->__state
,
3007 sizeof( __state
), "__state");
3009 return( super::serializeProperties(s
) );
3013 void _IOConfigThread::main( _IOConfigThread
* self
)
3015 _IOServiceJob
* job
;
3023 semaphore_wait( gJobsSemaphore
);
3025 IOTakeLock( gJobsLock
);
3026 job
= (_IOServiceJob
*) gJobs
->getFirstObject();
3028 gJobs
->removeObject(job
);
3031 // gNumConfigThreads--; // we're out of service
3032 gNumWaitingThreads
--; // we're out of service
3034 IOUnlock( gJobsLock
);
3040 if( gIOKitDebug
& kIOLogConfig
)
3041 LOG("config(%x): starting on %s, %d\n",
3042 (int) IOThreadSelf(), job
->nub
->getName(), job
->type
);
3044 switch( job
->type
) {
3047 nub
->doServiceMatch( job
->options
);
3051 LOG("config(%x): strange type (%d)\n",
3052 (int) IOThreadSelf(), job
->type
);
3059 IOTakeLock( gJobsLock
);
3060 alive
= (gOutstandingJobs
> gNumWaitingThreads
);
3062 gNumWaitingThreads
++; // back in service
3063 // gNumConfigThreads++;
3065 if( 0 == --gNumConfigThreads
) {
3066 // IOLog("MATCH IDLE\n");
3067 IOLockWakeup( gJobsLock
, (event_t
) &gNumConfigThreads
, /* one-thread */ false );
3070 IOUnlock( gJobsLock
);
3075 if( gIOKitDebug
& kIOLogConfig
)
3076 LOG("config(%x): terminating\n", (int) IOThreadSelf() );
3081 IOReturn
IOService::waitMatchIdle( UInt32 msToWait
)
3084 int waitResult
= THREAD_AWAKENED
;
3085 bool computeDeadline
= true;
3086 AbsoluteTime abstime
;
3088 IOLockLock( gJobsLock
);
3090 wait
= (0 != gNumConfigThreads
);
3093 if( computeDeadline
) {
3094 clock_interval_to_absolutetime_interval(
3095 msToWait
, kMillisecondScale
, &abstime
);
3096 clock_absolutetime_interval_to_deadline(
3097 abstime
, &abstime
);
3098 computeDeadline
= false;
3100 waitResult
= IOLockSleepDeadline( gJobsLock
, &gNumConfigThreads
,
3101 abstime
, THREAD_UNINT
);
3103 waitResult
= IOLockSleep( gJobsLock
, &gNumConfigThreads
,
3107 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
3108 IOLockUnlock( gJobsLock
);
3110 if( waitResult
== THREAD_TIMED_OUT
)
3111 return( kIOReturnTimeout
);
3113 return( kIOReturnSuccess
);
3116 void _IOServiceJob::pingConfig( _IOServiceJob
* job
)
3123 IOTakeLock( gJobsLock
);
3126 gJobs
->setLastObject( job
);
3128 count
= gNumWaitingThreads
;
3129 // if( gNumConfigThreads) count++;// assume we're called from a config thread
3131 create
= ( (gOutstandingJobs
> count
)
3132 && (gNumConfigThreads
< kMaxConfigThreads
) );
3134 gNumConfigThreads
++;
3135 gNumWaitingThreads
++;
3138 IOUnlock( gJobsLock
);
3143 if( gIOKitDebug
& kIOLogConfig
)
3144 LOG("config(%d): creating\n", gNumConfigThreads
- 1);
3145 _IOConfigThread::configThread();
3148 semaphore_signal( gJobsSemaphore
);
3151 // internal - call with gNotificationLock
3152 OSObject
* IOService::getExistingServices( OSDictionary
* matching
,
3153 IOOptionBits inState
, IOOptionBits options
)
3155 OSObject
* current
= 0;
3157 IOService
* service
;
3164 && (obj
= matching
->getObject(gIOProviderClassKey
))
3166 && gIOResourcesKey
->isEqualTo(obj
)
3167 && (service
= gIOResources
))
3169 if( (inState
== (service
->__state
[0] & inState
))
3170 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3171 && service
->passiveMatch( matching
))
3173 if( options
& kIONotifyOnce
)
3176 current
= OSSet::withObjects(
3177 (const OSObject
**) &service
, 1, 1 );
3182 iter
= IORegistryIterator::iterateOver( gIOServicePlane
,
3183 kIORegistryIterateRecursively
);
3187 while( (service
= (IOService
*) iter
->getNextObject())) {
3188 if( (inState
== (service
->__state
[0] & inState
))
3189 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3190 && service
->passiveMatch( matching
)) {
3192 if( options
& kIONotifyOnce
) {
3197 ((OSSet
*)current
)->setObject( service
);
3199 current
= OSSet::withObjects(
3200 (const OSObject
**) &service
, 1, 1 );
3203 } while( !service
&& !iter
->isValid());
3208 if( current
&& (0 == (options
& (kIONotifyOnce
| kIOServiceExistingSet
)))) {
3209 iter
= OSCollectionIterator::withCollection( (OSSet
*)current
);
3218 OSIterator
* IOService::getMatchingServices( OSDictionary
* matching
)
3222 // is a lock even needed?
3225 iter
= (OSIterator
*) getExistingServices( matching
,
3226 kIOServiceMatchedState
);
3234 // internal - call with gNotificationLock
3235 IONotifier
* IOService::setNotification(
3236 const OSSymbol
* type
, OSDictionary
* matching
,
3237 IOServiceNotificationHandler handler
, void * target
, void * ref
,
3240 _IOServiceNotifier
* notify
= 0;
3246 notify
= new _IOServiceNotifier
;
3247 if( notify
&& !notify
->init()) {
3253 notify
->matching
= matching
;
3254 notify
->handler
= handler
;
3255 notify
->target
= target
;
3257 notify
->priority
= priority
;
3258 notify
->state
= kIOServiceNotifyEnable
;
3259 queue_init( ¬ify
->handlerInvocations
);
3263 if( 0 == (set
= (OSOrderedSet
*) gNotifications
->getObject( type
))) {
3264 set
= OSOrderedSet::withCapacity( 1,
3265 IONotifyOrdering
, 0 );
3267 gNotifications
->setObject( type
, set
);
3271 notify
->whence
= set
;
3273 set
->setObject( notify
);
3279 // internal - call with gNotificationLock
3280 IONotifier
* IOService::doInstallNotification(
3281 const OSSymbol
* type
, OSDictionary
* matching
,
3282 IOServiceNotificationHandler handler
,
3283 void * target
, void * ref
,
3284 SInt32 priority
, OSIterator
** existing
)
3287 IONotifier
* notify
;
3288 IOOptionBits inState
;
3293 if( type
== gIOPublishNotification
)
3294 inState
= kIOServiceRegisteredState
;
3296 else if( type
== gIOFirstPublishNotification
)
3297 inState
= kIOServiceFirstPublishState
;
3299 else if( (type
== gIOMatchedNotification
)
3300 || (type
== gIOFirstMatchNotification
))
3301 inState
= kIOServiceMatchedState
;
3302 else if( type
== gIOTerminatedNotification
)
3307 notify
= setNotification( type
, matching
, handler
, target
, ref
, priority
);
3310 // get the current set
3311 exist
= (OSIterator
*) getExistingServices( matching
, inState
);
3321 IONotifier
* IOService::installNotification(
3322 const OSSymbol
* type
, OSDictionary
* matching
,
3323 IOServiceNotificationHandler handler
,
3324 void * target
, void * ref
,
3325 SInt32 priority
, OSIterator
** existing
)
3327 IONotifier
* notify
;
3331 notify
= doInstallNotification( type
, matching
, handler
, target
, ref
,
3332 priority
, existing
);
3339 IONotifier
* IOService::addNotification(
3340 const OSSymbol
* type
, OSDictionary
* matching
,
3341 IOServiceNotificationHandler handler
,
3342 void * target
, void * ref
,
3345 OSIterator
* existing
;
3346 _IOServiceNotifier
* notify
;
3349 notify
= (_IOServiceNotifier
*) installNotification( type
, matching
,
3350 handler
, target
, ref
, priority
, &existing
);
3352 // send notifications for existing set
3355 notify
->retain(); // in case handler remove()s
3356 while( (next
= (IOService
*) existing
->getNextObject())) {
3358 next
->lockForArbitration();
3359 if( 0 == (next
->__state
[0] & kIOServiceInactiveState
))
3360 next
->invokeNotifer( notify
);
3361 next
->unlockForArbitration();
3364 existing
->release();
3370 struct SyncNotifyVars
{
3371 semaphore_port_t waitHere
;
3375 bool IOService::syncNotificationHandler(
3376 void * /* target */, void * ref
,
3377 IOService
* newService
)
3380 // result may get written more than once before the
3381 // notification is removed!
3382 ((SyncNotifyVars
*) ref
)->result
= newService
;
3383 semaphore_signal( ((SyncNotifyVars
*) ref
)->waitHere
);
3388 IOService
* IOService::waitForService( OSDictionary
* matching
,
3389 mach_timespec_t
* timeout
)
3391 IONotifier
* notify
= 0;
3392 // priority doesn't help us much since we need a thread wakeup
3393 SInt32 priority
= 0;
3394 SyncNotifyVars state
;
3395 kern_return_t err
= kIOReturnBadArgument
;
3407 state
.result
= (IOService
*) getExistingServices( matching
,
3408 kIOServiceMatchedState
, kIONotifyOnce
);
3412 err
= semaphore_create( kernel_task
, &state
.waitHere
,
3413 SYNC_POLICY_FIFO
, 0 );
3414 if( KERN_SUCCESS
!= err
)
3417 notify
= IOService::setNotification( gIOMatchedNotification
, matching
,
3418 &IOService::syncNotificationHandler
, (void *) 0,
3419 (void *) &state
, priority
);
3427 err
= semaphore_timedwait( state
.waitHere
, *timeout
);
3429 err
= semaphore_wait( state
.waitHere
);
3433 notify
->remove(); // dequeues
3435 matching
->release();
3437 semaphore_destroy( kernel_task
, state
.waitHere
);
3439 return( state
.result
);
3442 void IOService::deliverNotification( const OSSymbol
* type
,
3443 IOOptionBits orNewState
, IOOptionBits andNewState
)
3445 _IOServiceNotifier
* notify
;
3447 OSArray
* willSend
= 0;
3449 lockForArbitration();
3451 if( (0 == (__state
[0] & kIOServiceInactiveState
))
3452 || (type
== gIOTerminatedNotification
)) {
3456 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
3457 gNotifications
->getObject( type
) );
3460 while( (notify
= (_IOServiceNotifier
*) iter
->getNextObject())) {
3462 if( passiveMatch( notify
->matching
)
3463 && (kIOServiceNotifyEnable
& notify
->state
)) {
3465 willSend
= OSArray::withCapacity(8);
3467 willSend
->setObject( notify
);
3473 __state
[0] = (__state
[0] | orNewState
) & andNewState
;
3479 for( unsigned int idx
= 0;
3480 (notify
= (_IOServiceNotifier
*) willSend
->getObject(idx
));
3482 invokeNotifer( notify
);
3484 willSend
->release();
3486 unlockForArbitration();
3489 IOOptionBits
IOService::getState( void ) const
3491 return( __state
[0] );
3495 * Helpers to make matching objects for simple cases
3498 OSDictionary
* IOService::serviceMatching( const OSString
* name
,
3499 OSDictionary
* table
)
3502 table
= OSDictionary::withCapacity( 2 );
3504 table
->setObject(gIOProviderClassKey
, (OSObject
*)name
);
3509 OSDictionary
* IOService::serviceMatching( const char * name
,
3510 OSDictionary
* table
)
3512 const OSString
* str
;
3514 str
= OSSymbol::withCString( name
);
3518 table
= serviceMatching( str
, table
);
3523 OSDictionary
* IOService::nameMatching( const OSString
* name
,
3524 OSDictionary
* table
)
3527 table
= OSDictionary::withCapacity( 2 );
3529 table
->setObject( gIONameMatchKey
, (OSObject
*)name
);
3534 OSDictionary
* IOService::nameMatching( const char * name
,
3535 OSDictionary
* table
)
3537 const OSString
* str
;
3539 str
= OSSymbol::withCString( name
);
3543 table
= nameMatching( str
, table
);
3548 OSDictionary
* IOService::resourceMatching( const OSString
* str
,
3549 OSDictionary
* table
)
3551 table
= serviceMatching( gIOResourcesKey
, table
);
3553 table
->setObject( gIOResourceMatchKey
, (OSObject
*) str
);
3558 OSDictionary
* IOService::resourceMatching( const char * name
,
3559 OSDictionary
* table
)
3561 const OSSymbol
* str
;
3563 str
= OSSymbol::withCString( name
);
3567 table
= resourceMatching( str
, table
);
3574 * _IOServiceNotifier
3577 // wait for all threads, other than the current one,
3578 // to exit the handler
3580 void _IOServiceNotifier::wait()
3582 _IOServiceNotifierInvocation
* next
;
3587 queue_iterate( &handlerInvocations
, next
,
3588 _IOServiceNotifierInvocation
*, link
) {
3589 if( next
->thread
!= current_thread() ) {
3595 state
|= kIOServiceNotifyWaiter
;
3602 void _IOServiceNotifier::free()
3604 assert( queue_empty( &handlerInvocations
));
3608 void _IOServiceNotifier::remove()
3613 whence
->removeObject( (OSObject
*) this );
3617 matching
->release();
3621 state
&= ~kIOServiceNotifyEnable
;
3630 bool _IOServiceNotifier::disable()
3636 ret
= (0 != (kIOServiceNotifyEnable
& state
));
3637 state
&= ~kIOServiceNotifyEnable
;
3646 void _IOServiceNotifier::enable( bool was
)
3650 state
|= kIOServiceNotifyEnable
;
3652 state
&= ~kIOServiceNotifyEnable
;
3660 IOService
* IOResources::resources( void )
3664 inst
= new IOResources
;
3665 if( inst
&& !inst
->init()) {
3673 IOWorkLoop
* IOResources::getWorkLoop() const
3675 // If we are the resource root then bringe over to the
3676 // platform to get its workloop
3677 if (this == (IOResources
*) gIOResources
)
3678 return getPlatform()->getWorkLoop();
3680 return IOService::getWorkLoop();
3683 bool IOResources::matchPropertyTable( OSDictionary
* table
)
3691 prop
= table
->getObject( gIOResourceMatchKey
);
3692 str
= OSDynamicCast( OSString
, prop
);
3694 ok
= (0 != getProperty( str
));
3696 else if( (set
= OSDynamicCast( OSSet
, prop
))) {
3698 iter
= OSCollectionIterator::withCollection( set
);
3700 while( ok
&& (str
= OSDynamicCast( OSString
, iter
->getNextObject()) ))
3701 ok
= (0 != getProperty( str
));
3710 IOReturn
IOResources::setProperties( OSObject
* properties
)
3713 const OSSymbol
* key
;
3714 OSDictionary
* dict
;
3715 OSCollectionIterator
* iter
;
3717 err
= IOUserClient::clientHasPrivilege(current_task(), kIOClientPrivilegeAdministrator
);
3718 if ( kIOReturnSuccess
!= err
)
3721 dict
= OSDynamicCast(OSDictionary
, properties
);
3723 return( kIOReturnBadArgument
);
3725 iter
= OSCollectionIterator::withCollection( dict
);
3727 return( kIOReturnBadArgument
);
3729 while( (key
= OSDynamicCast(OSSymbol
, iter
->getNextObject()))) {
3731 if (gIOConsoleUsersKey
== key
)
3733 IORegistryEntry::getRegistryRoot()->setProperty(key
, dict
->getObject(key
));
3734 OSIncrementAtomic( &gIOConsoleUsersSeed
);
3735 publishResource( gIOConsoleUsersSeedKey
, gIOConsoleUsersSeedValue
);
3739 publishResource( key
, dict
->getObject(key
) );
3744 return( kIOReturnSuccess
);
3748 * Helpers for matching dictionaries.
3749 * Keys existing in matching are checked in properties.
3750 * Keys may be a string or OSCollection of IOStrings
3753 bool IOService::compareProperty( OSDictionary
* matching
,
3759 value
= matching
->getObject( key
);
3761 ok
= value
->isEqualTo( getProperty( key
));
3769 bool IOService::compareProperty( OSDictionary
* matching
,
3770 const OSString
* key
)
3775 value
= matching
->getObject( key
);
3777 ok
= value
->isEqualTo( getProperty( key
));
3784 bool IOService::compareProperties( OSDictionary
* matching
,
3785 OSCollection
* keys
)
3787 OSCollectionIterator
* iter
;
3788 const OSString
* key
;
3791 if( !matching
|| !keys
)
3794 iter
= OSCollectionIterator::withCollection( keys
);
3797 while( ok
&& (key
= OSDynamicCast( OSString
, iter
->getNextObject())))
3798 ok
= compareProperty( matching
, key
);
3802 keys
->release(); // !! consume a ref !!
3807 /* Helper to add a location matching dict to the table */
3809 OSDictionary
* IOService::addLocation( OSDictionary
* table
)
3811 OSDictionary
* dict
;
3816 dict
= OSDictionary::withCapacity( 1 );
3818 table
->setObject( gIOLocationMatchKey
, dict
);
3826 * Go looking for a provider to match a location dict.
3829 IOService
* IOService::matchLocation( IOService
* /* client */ )
3833 parent
= getProvider();
3836 parent
= parent
->matchLocation( this );
3841 bool IOService::passiveMatch( OSDictionary
* table
, bool changesOK
)
3847 IORegistryEntry
* entry
;
3852 bool matchParent
= false;
3863 str
= OSDynamicCast( OSString
, table
->getObject( gIOProviderClassKey
));
3866 match
= (0 != where
->metaCast( str
));
3871 obj
= table
->getObject( gIONameMatchKey
);
3874 match
= where
->compareNames( obj
, changesOK
? &matched
: 0 );
3877 if( changesOK
&& matched
) {
3878 // leave a hint as to which name matched
3879 table
->setObject( gIONameMatchedKey
, matched
);
3884 str
= OSDynamicCast( OSString
, table
->getObject( gIOLocationMatchKey
));
3887 const OSSymbol
* sym
;
3891 sym
= where
->copyLocation();
3893 match
= sym
->isEqualTo( str
);
3900 obj
= table
->getObject( gIOPropertyMatchKey
);
3903 OSDictionary
* dict
;
3904 OSDictionary
* nextDict
;
3909 dict
= where
->dictionaryWithProperties();
3911 nextDict
= OSDynamicCast( OSDictionary
, obj
);
3915 iter
= OSCollectionIterator::withCollection(
3916 OSDynamicCast(OSCollection
, obj
));
3919 || (iter
&& (0 != (nextDict
= OSDynamicCast(OSDictionary
,
3920 iter
->getNextObject()))))) {
3921 match
= dict
->isEqualTo( nextDict
, nextDict
);
3934 str
= OSDynamicCast( OSString
, table
->getObject( gIOPathMatchKey
));
3937 entry
= IORegistryEntry::fromPath( str
->getCStringNoCopy() );
3938 match
= (where
== entry
);
3945 num
= OSDynamicCast( OSNumber
, table
->getObject( gIOMatchedServiceCountKey
));
3949 IOService
* service
= 0;
3950 UInt32 serviceCount
= 0;
3953 iter
= where
->getClientIterator();
3955 while( (service
= (IOService
*) iter
->getNextObject())) {
3956 if( kIOServiceInactiveState
& service
->__state
[0])
3958 if( 0 == service
->getProperty( gIOMatchCategoryKey
))
3964 match
= (serviceCount
== num
->unsigned32BitValue());
3969 if( done
== table
->getCount()) {
3970 // don't call family if we've done all the entries in the table
3971 matchParent
= false;
3975 // pass in score from property table
3976 score
= IOServiceObjectOrder( table
, (void *) gIOProbeScoreKey
);
3978 // do family specific matching
3979 match
= where
->matchPropertyTable( table
, &score
);
3983 if( kIOLogMatch
& getDebugFlags( table
))
3984 LOG("%s: family specific matching fails\n", where
->getName());
3991 newPri
= OSNumber::withNumber( score
, 32 );
3993 table
->setObject( gIOProbeScoreKey
, newPri
);
3998 if( !(match
= where
->compareProperty( table
, kIOBSDNameKey
)))
4001 matchParent
= false;
4003 obj
= OSDynamicCast( OSDictionary
,
4004 table
->getObject( gIOParentMatchKey
));
4008 table
= (OSDictionary
*) obj
;
4012 table
= OSDynamicCast( OSDictionary
,
4013 table
->getObject( gIOLocationMatchKey
));
4016 where
= where
->getProvider();
4018 where
= where
->matchLocation( where
);
4021 } while( table
&& where
);
4023 } while( matchParent
&& (where
= where
->getProvider()) );
4025 if( kIOLogMatch
& gIOKitDebug
)
4027 LOG("match parent @ %s = %d\n",
4028 where
->getName(), match
);
4034 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
4035 UInt32 type
, OSDictionary
* properties
,
4036 IOUserClient
** handler
)
4038 const OSSymbol
*userClientClass
= 0;
4039 IOUserClient
*client
;
4042 if (kIOReturnSuccess
== newUserClient( owningTask
, securityID
, type
, handler
))
4043 return kIOReturnSuccess
;
4045 // First try my own properties for a user client class name
4046 temp
= getProperty(gIOUserClientClassKey
);
4048 if (OSDynamicCast(OSSymbol
, temp
))
4049 userClientClass
= (const OSSymbol
*) temp
;
4050 else if (OSDynamicCast(OSString
, temp
)) {
4051 userClientClass
= OSSymbol::withString((OSString
*) temp
);
4052 if (userClientClass
)
4053 setProperty(kIOUserClientClassKey
,
4054 (OSObject
*) userClientClass
);
4058 // Didn't find one so lets just bomb out now without further ado.
4059 if (!userClientClass
)
4060 return kIOReturnUnsupported
;
4062 // This reference is consumed by the IOServiceOpen call
4063 temp
= OSMetaClass::allocClassWithName(userClientClass
);
4065 return kIOReturnNoMemory
;
4067 if (OSDynamicCast(IOUserClient
, temp
))
4068 client
= (IOUserClient
*) temp
;
4071 return kIOReturnUnsupported
;
4074 if ( !client
->initWithTask(owningTask
, securityID
, type
, properties
) ) {
4076 return kIOReturnBadArgument
;
4079 if ( !client
->attach(this) ) {
4081 return kIOReturnUnsupported
;
4084 if ( !client
->start(this) ) {
4085 client
->detach(this);
4087 return kIOReturnUnsupported
;
4091 return kIOReturnSuccess
;
4094 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
4095 UInt32 type
, IOUserClient
** handler
)
4097 return( kIOReturnUnsupported
);
4100 IOReturn
IOService::requestProbe( IOOptionBits options
)
4102 return( kIOReturnUnsupported
);
4106 * Convert an IOReturn to text. Subclasses which add additional
4107 * IOReturn's should override this method and call
4108 * super::stringFromReturn if the desired value is not found.
4111 const char * IOService::stringFromReturn( IOReturn rtn
)
4113 static const IONamedValue IOReturn_values
[] = {
4114 {kIOReturnSuccess
, "success" },
4115 {kIOReturnError
, "general error" },
4116 {kIOReturnNoMemory
, "memory allocation error" },
4117 {kIOReturnNoResources
, "resource shortage" },
4118 {kIOReturnIPCError
, "Mach IPC failure" },
4119 {kIOReturnNoDevice
, "no such device" },
4120 {kIOReturnNotPrivileged
, "privilege violation" },
4121 {kIOReturnBadArgument
, "invalid argument" },
4122 {kIOReturnLockedRead
, "device is read locked" },
4123 {kIOReturnLockedWrite
, "device is write locked" },
4124 {kIOReturnExclusiveAccess
, "device is exclusive access" },
4125 {kIOReturnBadMessageID
, "bad IPC message ID" },
4126 {kIOReturnUnsupported
, "unsupported function" },
4127 {kIOReturnVMError
, "virtual memory error" },
4128 {kIOReturnInternalError
, "internal driver error" },
4129 {kIOReturnIOError
, "I/O error" },
4130 {kIOReturnCannotLock
, "cannot acquire lock" },
4131 {kIOReturnNotOpen
, "device is not open" },
4132 {kIOReturnNotReadable
, "device is not readable" },
4133 {kIOReturnNotWritable
, "device is not writeable" },
4134 {kIOReturnNotAligned
, "alignment error" },
4135 {kIOReturnBadMedia
, "media error" },
4136 {kIOReturnStillOpen
, "device is still open" },
4137 {kIOReturnRLDError
, "rld failure" },
4138 {kIOReturnDMAError
, "DMA failure" },
4139 {kIOReturnBusy
, "device is busy" },
4140 {kIOReturnTimeout
, "I/O timeout" },
4141 {kIOReturnOffline
, "device is offline" },
4142 {kIOReturnNotReady
, "device is not ready" },
4143 {kIOReturnNotAttached
, "device/channel is not attached" },
4144 {kIOReturnNoChannels
, "no DMA channels available" },
4145 {kIOReturnNoSpace
, "no space for data" },
4146 {kIOReturnPortExists
, "device port already exists" },
4147 {kIOReturnCannotWire
, "cannot wire physical memory" },
4148 {kIOReturnNoInterrupt
, "no interrupt attached" },
4149 {kIOReturnNoFrames
, "no DMA frames enqueued" },
4150 {kIOReturnMessageTooLarge
, "message is too large" },
4151 {kIOReturnNotPermitted
, "operation is not permitted" },
4152 {kIOReturnNoPower
, "device is without power" },
4153 {kIOReturnNoMedia
, "media is not present" },
4154 {kIOReturnUnformattedMedia
, "media is not formatted" },
4155 {kIOReturnUnsupportedMode
, "unsupported mode" },
4156 {kIOReturnUnderrun
, "data underrun" },
4157 {kIOReturnOverrun
, "data overrun" },
4158 {kIOReturnDeviceError
, "device error" },
4159 {kIOReturnNoCompletion
, "no completion routine" },
4160 {kIOReturnAborted
, "operation was aborted" },
4161 {kIOReturnNoBandwidth
, "bus bandwidth would be exceeded" },
4162 {kIOReturnNotResponding
, "device is not responding" },
4163 {kIOReturnInvalid
, "unanticipated driver error" },
4167 return IOFindNameForValue(rtn
, IOReturn_values
);
4171 * Convert an IOReturn to an errno.
4173 int IOService::errnoFromReturn( IOReturn rtn
)
4177 case kIOReturnSuccess
:
4179 case kIOReturnNoMemory
:
4181 case kIOReturnNoDevice
:
4183 case kIOReturnVMError
:
4185 case kIOReturnNotPermitted
:
4187 case kIOReturnNotPrivileged
:
4189 case kIOReturnIOError
:
4191 case kIOReturnNotWritable
:
4193 case kIOReturnBadArgument
:
4195 case kIOReturnUnsupported
:
4199 case kIOReturnNoPower
:
4201 case kIOReturnDeviceError
:
4203 case kIOReturnTimeout
:
4205 case kIOReturnMessageTooLarge
:
4207 case kIOReturnNoSpace
:
4209 case kIOReturnCannotLock
:
4213 case kIOReturnBadMessageID
:
4214 case kIOReturnNoCompletion
:
4215 case kIOReturnNotAligned
:
4217 case kIOReturnNotReady
:
4219 case kIOReturnRLDError
:
4221 case kIOReturnPortExists
:
4222 case kIOReturnStillOpen
:
4224 case kIOReturnExclusiveAccess
:
4225 case kIOReturnLockedRead
:
4226 case kIOReturnLockedWrite
:
4227 case kIOReturnNotAttached
:
4228 case kIOReturnNotOpen
:
4229 case kIOReturnNotReadable
:
4231 case kIOReturnCannotWire
:
4232 case kIOReturnNoResources
:
4234 case kIOReturnAborted
:
4235 case kIOReturnOffline
:
4236 case kIOReturnNotResponding
:
4238 case kIOReturnBadMedia
:
4239 case kIOReturnNoMedia
:
4240 case kIOReturnUnformattedMedia
:
4241 return(ENXIO
); // (media error)
4242 case kIOReturnDMAError
:
4243 case kIOReturnOverrun
:
4244 case kIOReturnUnderrun
:
4245 return(EIO
); // (transfer error)
4246 case kIOReturnNoBandwidth
:
4247 case kIOReturnNoChannels
:
4248 case kIOReturnNoFrames
:
4249 case kIOReturnNoInterrupt
:
4250 return(EIO
); // (hardware error)
4251 case kIOReturnError
:
4252 case kIOReturnInternalError
:
4253 case kIOReturnInvalid
:
4254 return(EIO
); // (generic error)
4255 case kIOReturnIPCError
:
4256 return(EIO
); // (ipc error)
4258 return(EIO
); // (all other errors)
4262 IOReturn
IOService::message( UInt32 type
, IOService
* provider
,
4266 * Generic entry point for calls from the provider. A return value of
4267 * kIOReturnSuccess indicates that the message was received, and where
4268 * applicable, that it was successful.
4271 return kIOReturnUnsupported
;
4278 IOItemCount
IOService::getDeviceMemoryCount( void )
4283 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4285 count
= array
->getCount();
4292 IODeviceMemory
* IOService::getDeviceMemoryWithIndex( unsigned int index
)
4295 IODeviceMemory
* range
;
4297 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4299 range
= (IODeviceMemory
*) array
->getObject( index
);
4306 IOMemoryMap
* IOService::mapDeviceMemoryWithIndex( unsigned int index
,
4307 IOOptionBits options
)
4309 IODeviceMemory
* range
;
4312 range
= getDeviceMemoryWithIndex( index
);
4314 map
= range
->map( options
);
4321 OSArray
* IOService::getDeviceMemory( void )
4323 return( OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
)));
4327 void IOService::setDeviceMemory( OSArray
* array
)
4329 setProperty( gIODeviceMemoryKey
, array
);
4333 * For machines where the transfers on an I/O bus can stall because
4334 * the CPU is in an idle mode, These APIs allow a driver to specify
4335 * the maximum bus stall that they can handle. 0 indicates no limit.
4338 setCPUSnoopDelay(UInt32 __unused ns
)
4341 ml_set_maxsnoop(ns
);
4342 #endif /* __i386__ */
4349 return ml_get_maxsnoop();
4352 #endif /* __i386__ */
4356 requireMaxBusStall(UInt32 __unused ns
)
4359 static const UInt kNoReplace
= -1U; // Must be an illegal index
4360 UInt replace
= kNoReplace
;
4362 IOLockLock(sBusStallLock
);
4364 UInt count
= sBusStall
->getLength() / sizeof(BusStallEntry
);
4365 BusStallEntry
*entries
= (BusStallEntry
*) sBusStall
->getBytesNoCopy();
4368 const BusStallEntry ne
= {this, ns
};
4370 // Set Maximum bus delay.
4371 for (UInt i
= 0; i
< count
; i
++) {
4372 const IOService
*thisService
= entries
[i
].fService
;
4373 if (this == thisService
)
4375 else if (!thisService
) {
4376 if (kNoReplace
== replace
)
4380 const UInt32 thisMax
= entries
[i
].fMaxDelay
;
4386 // Must be safe to call from locked context
4387 ml_set_maxbusdelay(ns
);
4389 if (kNoReplace
== replace
)
4390 sBusStall
->appendBytes(&ne
, sizeof(ne
));
4392 entries
[replace
] = ne
;
4395 ns
= -1U; // Set to max unsigned, i.e. no restriction
4397 for (UInt i
= 0; i
< count
; i
++) {
4398 // Clear a maximum bus delay.
4399 const IOService
*thisService
= entries
[i
].fService
;
4400 UInt32 thisMax
= entries
[i
].fMaxDelay
;
4401 if (this == thisService
)
4403 else if (thisService
&& thisMax
< ns
)
4407 // Check if entry found
4408 if (kNoReplace
!= replace
) {
4409 entries
[replace
].fService
= 0; // Null the entry
4410 ml_set_maxbusdelay(ns
);
4414 IOLockUnlock(sBusStallLock
);
4415 #endif /* __i386__ */
4422 IOReturn
IOService::resolveInterrupt(IOService
*nub
, int source
)
4424 IOInterruptController
*interruptController
;
4427 OSSymbol
*interruptControllerName
;
4429 IOInterruptSource
*interruptSources
;
4431 // Get the parents list from the nub.
4432 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptControllersKey
));
4433 if (array
== 0) return kIOReturnNoResources
;
4435 // Allocate space for the IOInterruptSources if needed... then return early.
4436 if (nub
->_interruptSources
== 0) {
4437 numSources
= array
->getCount();
4438 interruptSources
= (IOInterruptSource
*)IOMalloc(numSources
* sizeof(IOInterruptSource
));
4439 if (interruptSources
== 0) return kIOReturnNoMemory
;
4441 bzero(interruptSources
, numSources
* sizeof(IOInterruptSource
));
4443 nub
->_numInterruptSources
= numSources
;
4444 nub
->_interruptSources
= interruptSources
;
4445 return kIOReturnSuccess
;
4448 interruptControllerName
= OSDynamicCast(OSSymbol
,array
->getObject(source
));
4449 if (interruptControllerName
== 0) return kIOReturnNoResources
;
4451 interruptController
= getPlatform()->lookUpInterruptController(interruptControllerName
);
4452 if (interruptController
== 0) return kIOReturnNoResources
;
4454 // Get the interrupt numbers from the nub.
4455 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptSpecifiersKey
));
4456 if (array
== 0) return kIOReturnNoResources
;
4457 data
= OSDynamicCast(OSData
, array
->getObject(source
));
4458 if (data
== 0) return kIOReturnNoResources
;
4460 // Set the interruptController and interruptSource in the nub's table.
4461 interruptSources
= nub
->_interruptSources
;
4462 interruptSources
[source
].interruptController
= interruptController
;
4463 interruptSources
[source
].vectorData
= data
;
4465 return kIOReturnSuccess
;
4468 IOReturn
IOService::lookupInterrupt(int source
, bool resolve
, IOInterruptController
**interruptController
)
4472 /* Make sure the _interruptSources are set */
4473 if (_interruptSources
== 0) {
4474 ret
= resolveInterrupt(this, source
);
4475 if (ret
!= kIOReturnSuccess
) return ret
;
4478 /* Make sure the local source number is valid */
4479 if ((source
< 0) || (source
>= _numInterruptSources
))
4480 return kIOReturnNoInterrupt
;
4482 /* Look up the contoller for the local source */
4483 *interruptController
= _interruptSources
[source
].interruptController
;
4485 if (*interruptController
== NULL
) {
4486 if (!resolve
) return kIOReturnNoInterrupt
;
4488 /* Try to reslove the interrupt */
4489 ret
= resolveInterrupt(this, source
);
4490 if (ret
!= kIOReturnSuccess
) return ret
;
4492 *interruptController
= _interruptSources
[source
].interruptController
;
4495 return kIOReturnSuccess
;
4498 IOReturn
IOService::registerInterrupt(int source
, OSObject
*target
,
4499 IOInterruptAction handler
,
4502 IOInterruptController
*interruptController
;
4505 ret
= lookupInterrupt(source
, true, &interruptController
);
4506 if (ret
!= kIOReturnSuccess
) return ret
;
4508 /* Register the source */
4509 return interruptController
->registerInterrupt(this, source
, target
,
4510 (IOInterruptHandler
)handler
,
4514 IOReturn
IOService::unregisterInterrupt(int source
)
4516 IOInterruptController
*interruptController
;
4519 ret
= lookupInterrupt(source
, false, &interruptController
);
4520 if (ret
!= kIOReturnSuccess
) return ret
;
4522 /* Unregister the source */
4523 return interruptController
->unregisterInterrupt(this, source
);
4526 IOReturn
IOService::getInterruptType(int source
, int *interruptType
)
4528 IOInterruptController
*interruptController
;
4531 ret
= lookupInterrupt(source
, true, &interruptController
);
4532 if (ret
!= kIOReturnSuccess
) return ret
;
4534 /* Return the type */
4535 return interruptController
->getInterruptType(this, source
, interruptType
);
4538 IOReturn
IOService::enableInterrupt(int source
)
4540 IOInterruptController
*interruptController
;
4543 ret
= lookupInterrupt(source
, false, &interruptController
);
4544 if (ret
!= kIOReturnSuccess
) return ret
;
4546 /* Enable the source */
4547 return interruptController
->enableInterrupt(this, source
);
4550 IOReturn
IOService::disableInterrupt(int source
)
4552 IOInterruptController
*interruptController
;
4555 ret
= lookupInterrupt(source
, false, &interruptController
);
4556 if (ret
!= kIOReturnSuccess
) return ret
;
4558 /* Disable the source */
4559 return interruptController
->disableInterrupt(this, source
);
4562 IOReturn
IOService::causeInterrupt(int source
)
4564 IOInterruptController
*interruptController
;
4567 ret
= lookupInterrupt(source
, false, &interruptController
);
4568 if (ret
!= kIOReturnSuccess
) return ret
;
4570 /* Cause an interrupt for the source */
4571 return interruptController
->causeInterrupt(this, source
);
4574 OSMetaClassDefineReservedUsed(IOService
, 0);
4575 OSMetaClassDefineReservedUsed(IOService
, 1);
4576 OSMetaClassDefineReservedUsed(IOService
, 2);
4577 OSMetaClassDefineReservedUsed(IOService
, 3);
4579 OSMetaClassDefineReservedUnused(IOService
, 4);
4580 OSMetaClassDefineReservedUnused(IOService
, 5);
4581 OSMetaClassDefineReservedUnused(IOService
, 6);
4582 OSMetaClassDefineReservedUnused(IOService
, 7);
4583 OSMetaClassDefineReservedUnused(IOService
, 8);
4584 OSMetaClassDefineReservedUnused(IOService
, 9);
4585 OSMetaClassDefineReservedUnused(IOService
, 10);
4586 OSMetaClassDefineReservedUnused(IOService
, 11);
4587 OSMetaClassDefineReservedUnused(IOService
, 12);
4588 OSMetaClassDefineReservedUnused(IOService
, 13);
4589 OSMetaClassDefineReservedUnused(IOService
, 14);
4590 OSMetaClassDefineReservedUnused(IOService
, 15);
4591 OSMetaClassDefineReservedUnused(IOService
, 16);
4592 OSMetaClassDefineReservedUnused(IOService
, 17);
4593 OSMetaClassDefineReservedUnused(IOService
, 18);
4594 OSMetaClassDefineReservedUnused(IOService
, 19);
4595 OSMetaClassDefineReservedUnused(IOService
, 20);
4596 OSMetaClassDefineReservedUnused(IOService
, 21);
4597 OSMetaClassDefineReservedUnused(IOService
, 22);
4598 OSMetaClassDefineReservedUnused(IOService
, 23);
4599 OSMetaClassDefineReservedUnused(IOService
, 24);
4600 OSMetaClassDefineReservedUnused(IOService
, 25);
4601 OSMetaClassDefineReservedUnused(IOService
, 26);
4602 OSMetaClassDefineReservedUnused(IOService
, 27);
4603 OSMetaClassDefineReservedUnused(IOService
, 28);
4604 OSMetaClassDefineReservedUnused(IOService
, 29);
4605 OSMetaClassDefineReservedUnused(IOService
, 30);
4606 OSMetaClassDefineReservedUnused(IOService
, 31);
4607 OSMetaClassDefineReservedUnused(IOService
, 32);
4608 OSMetaClassDefineReservedUnused(IOService
, 33);
4609 OSMetaClassDefineReservedUnused(IOService
, 34);
4610 OSMetaClassDefineReservedUnused(IOService
, 35);
4611 OSMetaClassDefineReservedUnused(IOService
, 36);
4612 OSMetaClassDefineReservedUnused(IOService
, 37);
4613 OSMetaClassDefineReservedUnused(IOService
, 38);
4614 OSMetaClassDefineReservedUnused(IOService
, 39);
4615 OSMetaClassDefineReservedUnused(IOService
, 40);
4616 OSMetaClassDefineReservedUnused(IOService
, 41);
4617 OSMetaClassDefineReservedUnused(IOService
, 42);
4618 OSMetaClassDefineReservedUnused(IOService
, 43);
4619 OSMetaClassDefineReservedUnused(IOService
, 44);
4620 OSMetaClassDefineReservedUnused(IOService
, 45);
4621 OSMetaClassDefineReservedUnused(IOService
, 46);
4622 OSMetaClassDefineReservedUnused(IOService
, 47);
4625 OSMetaClassDefineReservedUnused(IOService
, 48);
4626 OSMetaClassDefineReservedUnused(IOService
, 49);
4627 OSMetaClassDefineReservedUnused(IOService
, 50);
4628 OSMetaClassDefineReservedUnused(IOService
, 51);
4629 OSMetaClassDefineReservedUnused(IOService
, 52);
4630 OSMetaClassDefineReservedUnused(IOService
, 53);
4631 OSMetaClassDefineReservedUnused(IOService
, 54);
4632 OSMetaClassDefineReservedUnused(IOService
, 55);
4633 OSMetaClassDefineReservedUnused(IOService
, 56);
4634 OSMetaClassDefineReservedUnused(IOService
, 57);
4635 OSMetaClassDefineReservedUnused(IOService
, 58);
4636 OSMetaClassDefineReservedUnused(IOService
, 59);
4637 OSMetaClassDefineReservedUnused(IOService
, 60);
4638 OSMetaClassDefineReservedUnused(IOService
, 61);
4639 OSMetaClassDefineReservedUnused(IOService
, 62);
4640 OSMetaClassDefineReservedUnused(IOService
, 63);