2 * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
26 * Copyright (c) 1991-1999 Apple Computer, Inc. All rights reserved.
30 * 29-Jan-91 Portions from IODevice.m, Doug Mitchell at NeXT, Created.
31 * 18-Jun-98 start IOKit objc
32 * 10-Nov-98 start iokit cpp
33 * 25-Feb-99 sdouglas, add threads and locks to ensure deadlock
37 #include <IOKit/system.h>
39 #include <IOKit/IOService.h>
40 #include <libkern/c++/OSContainers.h>
41 #include <libkern/c++/OSUnserialize.h>
42 #include <IOKit/IOCatalogue.h>
43 #include <IOKit/IODeviceMemory.h>
44 #include <IOKit/IOInterrupts.h>
45 #include <IOKit/IOInterruptController.h>
46 #include <IOKit/IOPlatformExpert.h>
47 #include <IOKit/IOMessage.h>
48 #include <IOKit/IOLib.h>
49 #include <IOKit/IOKitKeys.h>
50 #include <IOKit/IOBSD.h>
51 #include <IOKit/IOUserClient.h>
52 #include <IOKit/IOWorkLoop.h>
53 #include <mach/sync_policy.h>
54 #include <IOKit/assert.h>
55 #include <sys/errno.h>
60 #include "IOServicePrivate.h"
62 // take lockForArbitration before LOCKNOTIFY
64 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
66 #define super IORegistryEntry
68 OSDefineMetaClassAndStructors(IOService
, IORegistryEntry
)
70 OSDefineMetaClassAndStructors(_IOServiceNotifier
, IONotifier
)
72 OSDefineMetaClassAndStructors(_IOServiceInterestNotifier
, IONotifier
)
74 OSDefineMetaClassAndStructors(_IOConfigThread
, OSObject
)
76 OSDefineMetaClassAndStructors(_IOServiceJob
, OSObject
)
78 OSDefineMetaClassAndStructors(IOResources
, IOService
)
80 OSDefineMetaClassAndStructors(_IOOpenServiceIterator
, OSIterator
)
82 OSDefineMetaClassAndAbstractStructors(IONotifier
, OSObject
)
84 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
86 static IOPlatformExpert
* gIOPlatform
;
87 static class IOPMrootDomain
* gIOPMRootDomain
;
88 const IORegistryPlane
* gIOServicePlane
;
89 const IORegistryPlane
* gIOPowerPlane
;
90 const OSSymbol
* gIODeviceMemoryKey
;
91 const OSSymbol
* gIOInterruptControllersKey
;
92 const OSSymbol
* gIOInterruptSpecifiersKey
;
94 const OSSymbol
* gIOResourcesKey
;
95 const OSSymbol
* gIOResourceMatchKey
;
96 const OSSymbol
* gIOProviderClassKey
;
97 const OSSymbol
* gIONameMatchKey
;
98 const OSSymbol
* gIONameMatchedKey
;
99 const OSSymbol
* gIOPropertyMatchKey
;
100 const OSSymbol
* gIOLocationMatchKey
;
101 const OSSymbol
* gIOParentMatchKey
;
102 const OSSymbol
* gIOPathMatchKey
;
103 const OSSymbol
* gIOMatchCategoryKey
;
104 const OSSymbol
* gIODefaultMatchCategoryKey
;
105 const OSSymbol
* gIOMatchedServiceCountKey
;
107 const OSSymbol
* gIOUserClientClassKey
;
108 const OSSymbol
* gIOKitDebugKey
;
110 const OSSymbol
* gIOCommandPoolSizeKey
;
112 static int gIOResourceGenerationCount
;
114 const OSSymbol
* gIOServiceKey
;
115 const OSSymbol
* gIOPublishNotification
;
116 const OSSymbol
* gIOFirstPublishNotification
;
117 const OSSymbol
* gIOMatchedNotification
;
118 const OSSymbol
* gIOFirstMatchNotification
;
119 const OSSymbol
* gIOTerminatedNotification
;
121 const OSSymbol
* gIOGeneralInterest
;
122 const OSSymbol
* gIOBusyInterest
;
123 const OSSymbol
* gIOAppPowerStateInterest
;
124 const OSSymbol
* gIOPriorityPowerStateInterest
;
126 static OSDictionary
* gNotifications
;
127 static IORecursiveLock
* gNotificationLock
;
129 static IOService
* gIOResources
;
130 static IOService
* gIOServiceRoot
;
132 static OSOrderedSet
* gJobs
;
133 static semaphore_port_t gJobsSemaphore
;
134 static IOLock
* gJobsLock
;
135 static int gOutstandingJobs
;
136 static int gNumConfigThreads
;
137 static int gNumWaitingThreads
;
138 static IOLock
* gIOServiceBusyLock
;
140 static thread_t gIOTerminateThread
;
141 static UInt32 gIOTerminateWork
;
142 static OSArray
* gIOTerminatePhase2List
;
143 static OSArray
* gIOStopList
;
144 static OSArray
* gIOStopProviderList
;
145 static OSArray
* gIOFinalizeList
;
147 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
149 #define LOCKREADNOTIFY() \
150 IORecursiveLockLock( gNotificationLock )
151 #define LOCKWRITENOTIFY() \
152 IORecursiveLockLock( gNotificationLock )
153 #define LOCKWRITE2READNOTIFY()
154 #define UNLOCKNOTIFY() \
155 IORecursiveLockUnlock( gNotificationLock )
156 #define SLEEPNOTIFY(event) \
157 IORecursiveLockSleep( gNotificationLock, (void *)(event), THREAD_UNINT )
158 #define WAKEUPNOTIFY(event) \
159 IORecursiveLockWakeup( gNotificationLock, (void *)(event), /* wake one */ false )
161 #define randomDelay() \
162 int del = read_processor_clock(); \
163 del = (((int)IOThreadSelf()) ^ del ^ (del >> 10)) & 0x3ff; \
166 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
168 struct ArbitrationLockQueueElement
{
177 static queue_head_t gArbitrationLockQueueActive
;
178 static queue_head_t gArbitrationLockQueueWaiting
;
179 static queue_head_t gArbitrationLockQueueFree
;
180 static IOLock
* gArbitrationLockQueueLock
;
182 bool IOService::isInactive( void ) const
183 { return( 0 != (kIOServiceInactiveState
& getState())); }
185 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
187 void IOService::initialize( void )
191 gIOServicePlane
= IORegistryEntry::makePlane( kIOServicePlane
);
192 gIOPowerPlane
= IORegistryEntry::makePlane( kIOPowerPlane
);
194 gIOProviderClassKey
= OSSymbol::withCStringNoCopy( kIOProviderClassKey
);
195 gIONameMatchKey
= OSSymbol::withCStringNoCopy( kIONameMatchKey
);
196 gIONameMatchedKey
= OSSymbol::withCStringNoCopy( kIONameMatchedKey
);
197 gIOPropertyMatchKey
= OSSymbol::withCStringNoCopy( kIOPropertyMatchKey
);
198 gIOPathMatchKey
= OSSymbol::withCStringNoCopy( kIOPathMatchKey
);
199 gIOLocationMatchKey
= OSSymbol::withCStringNoCopy( kIOLocationMatchKey
);
200 gIOParentMatchKey
= OSSymbol::withCStringNoCopy( kIOParentMatchKey
);
202 gIOMatchCategoryKey
= OSSymbol::withCStringNoCopy( kIOMatchCategoryKey
);
203 gIODefaultMatchCategoryKey
= OSSymbol::withCStringNoCopy(
204 kIODefaultMatchCategoryKey
);
205 gIOMatchedServiceCountKey
= OSSymbol::withCStringNoCopy(
206 kIOMatchedServiceCountKey
);
208 gIOUserClientClassKey
= OSSymbol::withCStringNoCopy( kIOUserClientClassKey
);
210 gIOResourcesKey
= OSSymbol::withCStringNoCopy( kIOResourcesClass
);
211 gIOResourceMatchKey
= OSSymbol::withCStringNoCopy( kIOResourceMatchKey
);
213 gIODeviceMemoryKey
= OSSymbol::withCStringNoCopy( "IODeviceMemory" );
214 gIOInterruptControllersKey
215 = OSSymbol::withCStringNoCopy("IOInterruptControllers");
216 gIOInterruptSpecifiersKey
217 = OSSymbol::withCStringNoCopy("IOInterruptSpecifiers");
219 gIOKitDebugKey
= OSSymbol::withCStringNoCopy( kIOKitDebugKey
);
221 gIOCommandPoolSizeKey
= OSSymbol::withCStringNoCopy( kIOCommandPoolSizeKey
);
223 gIOGeneralInterest
= OSSymbol::withCStringNoCopy( kIOGeneralInterest
);
224 gIOBusyInterest
= OSSymbol::withCStringNoCopy( kIOBusyInterest
);
225 gIOAppPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOAppPowerStateInterest
);
226 gIOPriorityPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOPriorityPowerStateInterest
);
228 gNotifications
= OSDictionary::withCapacity( 1 );
229 gIOPublishNotification
= OSSymbol::withCStringNoCopy(
230 kIOPublishNotification
);
231 gIOFirstPublishNotification
= OSSymbol::withCStringNoCopy(
232 kIOFirstPublishNotification
);
233 gIOMatchedNotification
= OSSymbol::withCStringNoCopy(
234 kIOMatchedNotification
);
235 gIOFirstMatchNotification
= OSSymbol::withCStringNoCopy(
236 kIOFirstMatchNotification
);
237 gIOTerminatedNotification
= OSSymbol::withCStringNoCopy(
238 kIOTerminatedNotification
);
239 gIOServiceKey
= OSSymbol::withCStringNoCopy( kIOServiceClass
);
241 gNotificationLock
= IORecursiveLockAlloc();
243 assert( gIOServicePlane
&& gIODeviceMemoryKey
244 && gIOInterruptControllersKey
&& gIOInterruptSpecifiersKey
245 && gIOResourcesKey
&& gNotifications
&& gNotificationLock
246 && gIOProviderClassKey
&& gIONameMatchKey
&& gIONameMatchedKey
247 && gIOMatchCategoryKey
&& gIODefaultMatchCategoryKey
248 && gIOPublishNotification
&& gIOMatchedNotification
249 && gIOTerminatedNotification
&& gIOServiceKey
);
251 gJobsLock
= IOLockAlloc();
252 gJobs
= OSOrderedSet::withCapacity( 10 );
254 gIOServiceBusyLock
= IOLockAlloc();
256 err
= semaphore_create(kernel_task
, &gJobsSemaphore
, SYNC_POLICY_FIFO
, 0);
258 assert( gIOServiceBusyLock
&& gJobs
&& gJobsLock
&& (err
== KERN_SUCCESS
) );
260 gIOResources
= IOResources::resources();
261 assert( gIOResources
);
263 gArbitrationLockQueueLock
= IOLockAlloc();
264 queue_init(&gArbitrationLockQueueActive
);
265 queue_init(&gArbitrationLockQueueWaiting
);
266 queue_init(&gArbitrationLockQueueFree
);
268 assert( gArbitrationLockQueueLock
);
270 gIOTerminatePhase2List
= OSArray::withCapacity( 2 );
271 gIOStopList
= OSArray::withCapacity( 16 );
272 gIOStopProviderList
= OSArray::withCapacity( 16 );
273 gIOFinalizeList
= OSArray::withCapacity( 16 );
274 assert( gIOTerminatePhase2List
&& gIOStopList
&& gIOStopProviderList
&& gIOFinalizeList
);
277 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
280 static UInt64
getDebugFlags( OSDictionary
* props
)
282 OSNumber
* debugProp
;
285 debugProp
= OSDynamicCast( OSNumber
,
286 props
->getObject( gIOKitDebugKey
));
288 debugFlags
= debugProp
->unsigned64BitValue();
290 debugFlags
= gIOKitDebug
;
292 return( debugFlags
);
296 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
298 // Probe a matched service and return an instance to be started.
299 // The default score is from the property table, & may be altered
300 // during probe to change the start order.
302 IOService
* IOService::probe( IOService
* provider
,
308 bool IOService::start( IOService
* provider
)
313 void IOService::stop( IOService
* provider
)
317 void IOService::free( void )
319 if( getPropertyTable())
320 unregisterAllInterest();
326 * Attach in service plane
328 bool IOService::attach( IOService
* provider
)
334 if( gIOKitDebug
& kIOLogAttach
)
335 LOG( "%s::attach(%s)\n", getName(),
336 provider
->getName());
338 provider
->lockForArbitration();
339 if( provider
->__state
[0] & kIOServiceInactiveState
)
342 ok
= attachToParent( provider
, gIOServicePlane
);
343 provider
->unlockForArbitration();
346 gIOServiceRoot
= this;
347 ok
= attachToParent( getRegistryRoot(), gIOServicePlane
);
353 IOService
* IOService::getServiceRoot( void )
355 return( gIOServiceRoot
);
358 void IOService::detach( IOService
* provider
)
360 IOService
* newProvider
= 0;
364 if( gIOKitDebug
& kIOLogAttach
)
365 LOG("%s::detach(%s)\n", getName(), provider
->getName());
367 lockForArbitration();
369 adjParent
= ((busy
= (__state
[1] & kIOServiceBusyStateMask
))
370 && (provider
== getProvider()));
372 detachFromParent( provider
, gIOServicePlane
);
375 newProvider
= getProvider();
376 if( busy
&& (__state
[1] & kIOServiceTermPhase3State
) && (0 == newProvider
))
377 _adjustBusy( -busy
);
380 unlockForArbitration();
383 newProvider
->lockForArbitration();
384 newProvider
->_adjustBusy(1);
385 newProvider
->unlockForArbitration();
388 // check for last client detach from a terminated service
389 if( provider
->lockForArbitration( true )) {
391 provider
->_adjustBusy( -1 );
392 if( (provider
->__state
[1] & kIOServiceTermPhase3State
)
393 && (0 == provider
->getClient())) {
394 provider
->scheduleFinalize();
396 provider
->unlockForArbitration();
401 * Register instance - publish it for matching
404 void IOService::registerService( IOOptionBits options
= 0 )
410 enum { kMaxPathLen
= 256 };
411 enum { kMaxChars
= 63 };
413 IORegistryEntry
* parent
= this;
414 IORegistryEntry
* root
= getRegistryRoot();
415 while( parent
&& (parent
!= root
))
416 parent
= parent
->getParentEntry( gIOServicePlane
);
418 if( parent
!= root
) {
419 IOLog("%s: not registry member at registerService()\n", getName());
423 // Allow the Platform Expert to adjust this node.
424 if( gIOPlatform
&& (!gIOPlatform
->platformAdjustService(this)))
427 if( (this != gIOResources
)
428 && (kIOLogRegister
& gIOKitDebug
)) {
430 pathBuf
= (char *) IOMalloc( kMaxPathLen
);
432 IOLog( "Registering: " );
435 if( pathBuf
&& getPath( pathBuf
, &len
, gIOServicePlane
)) {
438 if( len
> kMaxChars
) {
442 if( (skip
= strchr( path
, '/')))
448 IOLog( "%s\n", path
);
451 IOFree( pathBuf
, kMaxPathLen
);
454 startMatching( options
);
457 void IOService::startMatching( IOOptionBits options
= 0 )
459 IOService
* provider
;
462 bool needWake
= false;
467 lockForArbitration();
469 sync
= (options
& kIOServiceSynchronous
)
470 || ((provider
= getProvider())
471 && (provider
->__state
[1] & kIOServiceSynchronousState
));
474 needConfig
= (0 == (__state
[1] & (kIOServiceNeedConfigState
| kIOServiceConfigState
)))
475 && (0 == (__state
[0] & kIOServiceInactiveState
));
477 __state
[1] |= kIOServiceNeedConfigState
;
479 // __state[0] &= ~kIOServiceInactiveState;
481 // if( sync) LOG("OSKernelStackRemaining = %08x @ %s\n",
482 // OSKernelStackRemaining(), getName());
485 prevBusy
= _adjustBusy( 1 );
486 needWake
= (0 != (kIOServiceSyncPubState
& __state
[1]));
490 __state
[1] |= kIOServiceSynchronousState
;
492 __state
[1] &= ~kIOServiceSynchronousState
;
494 unlockForArbitration();
499 IOLockLock( gIOServiceBusyLock
);
500 thread_wakeup( (event_t
) this/*&__state[1]*/ );
501 IOLockUnlock( gIOServiceBusyLock
);
503 } else if( !sync
|| (kIOServiceAsynchronous
& options
)) {
505 ok
= (0 != _IOServiceJob::startJob( this, kMatchNubJob
, options
));
509 if( (__state
[1] & kIOServiceNeedConfigState
))
510 doServiceMatch( options
);
512 lockForArbitration();
513 IOLockLock( gIOServiceBusyLock
);
515 waitAgain
= (prevBusy
!= (__state
[1] & kIOServiceBusyStateMask
));
517 __state
[1] |= kIOServiceSyncPubState
| kIOServiceBusyWaiterState
;
519 __state
[1] &= ~kIOServiceSyncPubState
;
521 unlockForArbitration();
524 assert_wait( (event_t
) this/*&__state[1]*/, THREAD_UNINT
);
526 IOLockUnlock( gIOServiceBusyLock
);
528 thread_block(THREAD_CONTINUE_NULL
);
530 } while( waitAgain
);
534 IOReturn
IOService::catalogNewDrivers( OSOrderedSet
* newTables
)
536 OSDictionary
* table
;
545 while( (table
= (OSDictionary
*) newTables
->getFirstObject())) {
548 iter
= (OSIterator
*) getExistingServices( table
,
549 kIOServiceRegisteredState
);
552 while( (service
= (IOService
*) iter
->getNextObject())) {
553 service
->startMatching(kIOServiceAsynchronous
);
561 if( getDebugFlags( table
) & kIOLogMatch
)
562 LOG("Matching service count = %ld\n", count
);
564 newTables
->removeObject(table
);
567 newTables
->release();
569 return( kIOReturnSuccess
);
572 _IOServiceJob
* _IOServiceJob::startJob( IOService
* nub
, int type
,
573 IOOptionBits options
= 0 )
577 job
= new _IOServiceJob
;
578 if( job
&& !job
->init()) {
586 job
->options
= options
;
587 nub
->retain(); // thread will release()
595 * Called on a registered service to see if it matches
599 bool IOService::matchPropertyTable( OSDictionary
* table
, SInt32
* score
)
601 return( matchPropertyTable(table
) );
604 bool IOService::matchPropertyTable( OSDictionary
* table
)
610 * Called on a matched service to allocate resources
611 * before first driver is attached.
614 IOReturn
IOService::getResources( void )
616 return( kIOReturnSuccess
);
620 * Client/provider accessors
623 IOService
* IOService::getProvider( void ) const
625 IOService
* self
= (IOService
*) this;
630 generation
= getGenerationCount();
631 if( __providerGeneration
== generation
)
634 parent
= (IOService
*) getParentEntry( gIOServicePlane
);
635 if( parent
== IORegistryEntry::getRegistryRoot())
636 /* root is not an IOService */
639 self
->__provider
= parent
;
640 // save the count before getParentEntry()
641 self
->__providerGeneration
= generation
;
646 IOWorkLoop
* IOService::getWorkLoop() const
648 IOService
*provider
= getProvider();
651 return provider
->getWorkLoop();
656 OSIterator
* IOService::getProviderIterator( void ) const
658 return( getParentIterator( gIOServicePlane
));
661 IOService
* IOService::getClient( void ) const
663 return( (IOService
*) getChildEntry( gIOServicePlane
));
666 OSIterator
* IOService::getClientIterator( void ) const
668 return( getChildIterator( gIOServicePlane
));
671 OSIterator
* _IOOpenServiceIterator::iterator( OSIterator
* _iter
,
672 const IOService
* client
,
673 const IOService
* provider
)
675 _IOOpenServiceIterator
* inst
;
680 inst
= new _IOOpenServiceIterator
;
682 if( inst
&& !inst
->init()) {
688 inst
->client
= client
;
689 inst
->provider
= provider
;
695 void _IOOpenServiceIterator::free()
699 last
->unlockForArbitration();
703 OSObject
* _IOOpenServiceIterator::getNextObject()
708 last
->unlockForArbitration();
710 while( (next
= (IOService
*) iter
->getNextObject())) {
712 next
->lockForArbitration();
713 if( (client
&& (next
->isOpen( client
)))
714 || (provider
&& (provider
->isOpen( next
))) )
716 next
->unlockForArbitration();
724 bool _IOOpenServiceIterator::isValid()
726 return( iter
->isValid() );
729 void _IOOpenServiceIterator::reset()
732 last
->unlockForArbitration();
738 OSIterator
* IOService::getOpenProviderIterator( void ) const
740 return( _IOOpenServiceIterator::iterator( getProviderIterator(), this, 0 ));
743 OSIterator
* IOService::getOpenClientIterator( void ) const
745 return( _IOOpenServiceIterator::iterator( getClientIterator(), 0, this ));
749 IOReturn
IOService::callPlatformFunction( const OSSymbol
* functionName
,
750 bool waitForFunction
,
751 void *param1
, void *param2
,
752 void *param3
, void *param4
)
754 IOReturn result
= kIOReturnUnsupported
;
755 IOService
*provider
= getProvider();
758 result
= provider
->callPlatformFunction(functionName
, waitForFunction
,
759 param1
, param2
, param3
, param4
);
765 IOReturn
IOService::callPlatformFunction( const char * functionName
,
766 bool waitForFunction
,
767 void *param1
, void *param2
,
768 void *param3
, void *param4
)
770 IOReturn result
= kIOReturnNoMemory
;
771 const OSSymbol
*functionSymbol
= OSSymbol::withCString(functionName
);
773 if (functionSymbol
!= 0) {
774 result
= callPlatformFunction(functionSymbol
, waitForFunction
,
775 param1
, param2
, param3
, param4
);
776 functionSymbol
->release();
784 * Accessors for global services
787 IOPlatformExpert
* IOService::getPlatform( void )
789 return( gIOPlatform
);
792 class IOPMrootDomain
* IOService::getPMRootDomain( void )
794 return( gIOPMRootDomain
);
797 IOService
* IOService::getResourceService( void )
799 return( gIOResources
);
802 void IOService::setPlatform( IOPlatformExpert
* platform
)
804 gIOPlatform
= platform
;
805 gIOResources
->attachToParent( gIOServiceRoot
, gIOServicePlane
);
808 void IOService::setPMRootDomain( class IOPMrootDomain
* rootDomain
)
810 gIOPMRootDomain
= rootDomain
;
811 publishResource("IOKit");
818 bool IOService::lockForArbitration( bool isSuccessRequired
= true )
822 ArbitrationLockQueueElement
* element
;
823 ArbitrationLockQueueElement
* active
;
824 ArbitrationLockQueueElement
* waiting
;
826 enum { kPutOnFreeQueue
, kPutOnActiveQueue
, kPutOnWaitingQueue
} action
;
828 // lock global access
829 IOTakeLock( gArbitrationLockQueueLock
);
831 // obtain an unused queue element
832 if( !queue_empty( &gArbitrationLockQueueFree
)) {
833 queue_remove_first( &gArbitrationLockQueueFree
,
835 ArbitrationLockQueueElement
*,
838 element
= IONew( ArbitrationLockQueueElement
, 1 );
842 // prepare the queue element
843 element
->thread
= IOThreadSelf();
844 element
->service
= this;
846 element
->required
= isSuccessRequired
;
847 element
->aborted
= false;
849 // determine whether this object is already locked (ie. on active queue)
851 queue_iterate( &gArbitrationLockQueueActive
,
853 ArbitrationLockQueueElement
*,
856 if( active
->service
== element
->service
) {
862 if( found
) { // this object is already locked
864 // determine whether it is the same or a different thread trying to lock
865 if( active
->thread
!= element
->thread
) { // it is a different thread
867 ArbitrationLockQueueElement
* victim
= 0;
869 // before placing this new thread on the waiting queue, we look for
870 // a deadlock cycle...
873 // determine whether the active thread holding the object we
874 // want is waiting for another object to be unlocked
876 queue_iterate( &gArbitrationLockQueueWaiting
,
878 ArbitrationLockQueueElement
*,
881 if( waiting
->thread
== active
->thread
) {
882 assert( false == waiting
->aborted
);
888 if( found
) { // yes, active thread waiting for another object
890 // this may be a candidate for rejection if the required
891 // flag is not set, should we detect a deadlock later on
892 if( false == waiting
->required
)
895 // find the thread that is holding this other object, that
896 // is blocking the active thread from proceeding (fun :-)
898 queue_iterate( &gArbitrationLockQueueActive
,
899 active
, // (reuse active queue element)
900 ArbitrationLockQueueElement
*,
903 if( active
->service
== waiting
->service
) {
909 // someone must be holding it or it wouldn't be waiting
912 if( active
->thread
== element
->thread
) {
914 // doh, it's waiting for the thread that originated
915 // this whole lock (ie. current thread) -> deadlock
916 if( false == element
->required
) { // willing to fail?
918 // the originating thread doesn't have the required
919 // flag, so it can fail
920 success
= false; // (fail originating lock request)
921 break; // (out of while)
923 } else { // originating thread is not willing to fail
925 // see if we came across a waiting thread that did
926 // not have the 'required' flag set: we'll fail it
929 // we do have a willing victim, fail it's lock
930 victim
->aborted
= true;
932 // take the victim off the waiting queue
933 queue_remove( &gArbitrationLockQueueWaiting
,
935 ArbitrationLockQueueElement
*,
939 IOLockWakeup( gArbitrationLockQueueLock
,
941 /* one thread */ true );
943 // allow this thread to proceed (ie. wait)
944 success
= true; // (put request on wait queue)
945 break; // (out of while)
948 // all the waiting threads we came across in
949 // finding this loop had the 'required' flag
950 // set, so we've got a deadlock we can't avoid
951 panic("I/O Kit: Unrecoverable deadlock.");
955 // repeat while loop, redefining active thread to be the
956 // thread holding "this other object" (see above), and
957 // looking for threads waiting on it; note the active
958 // variable points to "this other object" already... so
959 // there nothing to do in this else clause.
961 } else { // no, active thread is not waiting for another object
963 success
= true; // (put request on wait queue)
964 break; // (out of while)
968 if( success
) { // put the request on the waiting queue?
969 kern_return_t wait_result
;
971 // place this thread on the waiting queue and put it to sleep;
972 // we place it at the tail of the queue...
973 queue_enter( &gArbitrationLockQueueWaiting
,
975 ArbitrationLockQueueElement
*,
978 // declare that this thread will wait for a given event
979 restart_sleep
: wait_result
= assert_wait( element
,
980 element
->required
? THREAD_UNINT
981 : THREAD_INTERRUPTIBLE
);
983 // unlock global access
984 IOUnlock( gArbitrationLockQueueLock
);
986 // put thread to sleep, waiting for our event to fire...
987 if (wait_result
== THREAD_WAITING
)
988 wait_result
= thread_block(THREAD_CONTINUE_NULL
);
991 // ...and we've been woken up; we might be in one of two states:
992 // (a) we've been aborted and our queue element is not on
993 // any of the three queues, but is floating around
994 // (b) we're allowed to proceed with the lock and we have
995 // already been moved from the waiting queue to the
997 // ...plus a 3rd state, should the thread have been interrupted:
998 // (c) we're still on the waiting queue
1000 // determine whether we were interrupted out of our sleep
1001 if( THREAD_INTERRUPTED
== wait_result
) {
1003 // re-lock global access
1004 IOTakeLock( gArbitrationLockQueueLock
);
1006 // determine whether we're still on the waiting queue
1008 queue_iterate( &gArbitrationLockQueueWaiting
,
1009 waiting
, // (reuse waiting queue element)
1010 ArbitrationLockQueueElement
*,
1013 if( waiting
== element
) {
1019 if( found
) { // yes, we're still on the waiting queue
1021 // determine whether we're willing to fail
1022 if( false == element
->required
) {
1024 // mark us as aborted
1025 element
->aborted
= true;
1027 // take us off the waiting queue
1028 queue_remove( &gArbitrationLockQueueWaiting
,
1030 ArbitrationLockQueueElement
*,
1032 } else { // we are not willing to fail
1034 // ignore interruption, go back to sleep
1039 // unlock global access
1040 IOUnlock( gArbitrationLockQueueLock
);
1042 // proceed as though this were a normal wake up
1043 wait_result
= THREAD_AWAKENED
;
1046 assert( THREAD_AWAKENED
== wait_result
);
1048 // determine whether we've been aborted while we were asleep
1049 if( element
->aborted
) {
1050 assert( false == element
->required
);
1052 // re-lock global access
1053 IOTakeLock( gArbitrationLockQueueLock
);
1055 action
= kPutOnFreeQueue
;
1057 } else { // we weren't aborted, so we must be ready to go :-)
1059 // we've already been moved from waiting to active queue
1063 } else { // the lock request is to be failed
1065 // return unused queue element to queue
1066 action
= kPutOnFreeQueue
;
1068 } else { // it is the same thread, recursive access is allowed
1070 // add one level of recursion
1073 // return unused queue element to queue
1074 action
= kPutOnFreeQueue
;
1077 } else { // this object is not already locked, so let this thread through
1078 action
= kPutOnActiveQueue
;
1082 // put the new element on a queue
1083 if( kPutOnActiveQueue
== action
) {
1084 queue_enter( &gArbitrationLockQueueActive
,
1086 ArbitrationLockQueueElement
*,
1088 } else if( kPutOnFreeQueue
== action
) {
1089 queue_enter( &gArbitrationLockQueueFree
,
1091 ArbitrationLockQueueElement
*,
1094 assert( 0 ); // kPutOnWaitingQueue never occurs, handled specially above
1097 // unlock global access
1098 IOUnlock( gArbitrationLockQueueLock
);
1103 void IOService::unlockForArbitration( void )
1106 ArbitrationLockQueueElement
* element
;
1108 // lock global access
1109 IOTakeLock( gArbitrationLockQueueLock
);
1111 // find the lock element for this object (ie. on active queue)
1113 queue_iterate( &gArbitrationLockQueueActive
,
1115 ArbitrationLockQueueElement
*,
1118 if( element
->service
== this ) {
1126 // determine whether the lock has been taken recursively
1127 if( element
->count
> 1 ) {
1128 // undo one level of recursion
1133 // remove it from the active queue
1134 queue_remove( &gArbitrationLockQueueActive
,
1136 ArbitrationLockQueueElement
*,
1139 // put it on the free queue
1140 queue_enter( &gArbitrationLockQueueFree
,
1142 ArbitrationLockQueueElement
*,
1145 // determine whether a thread is waiting for object (head to tail scan)
1147 queue_iterate( &gArbitrationLockQueueWaiting
,
1149 ArbitrationLockQueueElement
*,
1152 if( element
->service
== this ) {
1158 if ( found
) { // we found an interested thread on waiting queue
1160 // remove it from the waiting queue
1161 queue_remove( &gArbitrationLockQueueWaiting
,
1163 ArbitrationLockQueueElement
*,
1166 // put it on the active queue
1167 queue_enter( &gArbitrationLockQueueActive
,
1169 ArbitrationLockQueueElement
*,
1172 // wake the waiting thread
1173 IOLockWakeup( gArbitrationLockQueueLock
,
1175 /* one thread */ true );
1179 // unlock global access
1180 IOUnlock( gArbitrationLockQueueLock
);
1183 void IOService::applyToProviders( IOServiceApplierFunction applier
,
1186 applyToParents( (IORegistryEntryApplierFunction
) applier
,
1187 context
, gIOServicePlane
);
1190 void IOService::applyToClients( IOServiceApplierFunction applier
,
1193 applyToChildren( (IORegistryEntryApplierFunction
) applier
,
1194 context
, gIOServicePlane
);
1203 // send a message to a client or interested party of this service
1204 IOReturn
IOService::messageClient( UInt32 type
, OSObject
* client
,
1205 void * argument
= 0, vm_size_t argSize
= 0 )
1208 IOService
* service
;
1209 _IOServiceInterestNotifier
* notify
;
1211 if( (service
= OSDynamicCast( IOService
, client
)))
1212 ret
= service
->message( type
, this, argument
);
1214 else if( (notify
= OSDynamicCast( _IOServiceInterestNotifier
, client
))) {
1216 _IOServiceNotifierInvocation invocation
;
1219 invocation
.thread
= current_thread();
1222 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
1225 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
1226 _IOServiceNotifierInvocation
*, link
);
1232 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
,
1233 type
, this, argument
, argSize
);
1236 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
1237 _IOServiceNotifierInvocation
*, link
);
1238 if( kIOServiceNotifyWaiter
& notify
->state
) {
1239 notify
->state
&= ~kIOServiceNotifyWaiter
;
1240 WAKEUPNOTIFY( notify
);
1245 ret
= kIOReturnSuccess
;
1248 ret
= kIOReturnBadArgument
;
1253 void IOService::applyToInterested( const OSSymbol
* typeOfInterest
,
1254 OSObjectApplierFunction applier
,
1260 OSArray
* copyArray
;
1262 applyToClients( (IOServiceApplierFunction
) applier
, context
);
1265 array
= OSDynamicCast( OSArray
, getProperty( typeOfInterest
));
1267 copyArray
= OSArray::withArray( array
);
1271 (next
= array
->getObject( index
));
1273 (*applier
)(next
, context
);
1275 copyArray
->release();
1281 struct MessageClientsContext
{
1282 IOService
* service
;
1289 static void messageClientsApplier( OSObject
* object
, void * ctx
)
1292 MessageClientsContext
* context
= (MessageClientsContext
*) ctx
;
1294 ret
= context
->service
->messageClient( context
->type
,
1295 object
, context
->argument
, context
->argSize
);
1296 if( kIOReturnSuccess
!= ret
)
1300 // send a message to all clients
1301 IOReturn
IOService::messageClients( UInt32 type
,
1302 void * argument
= 0, vm_size_t argSize
= 0 )
1304 MessageClientsContext context
;
1306 context
.service
= this;
1307 context
.type
= type
;
1308 context
.argument
= argument
;
1309 context
.argSize
= argSize
;
1310 context
.ret
= kIOReturnSuccess
;
1312 applyToInterested( gIOGeneralInterest
,
1313 &messageClientsApplier
, &context
);
1315 return( context
.ret
);
1318 IOReturn
IOService::acknowledgeNotification( IONotificationRef notification
,
1319 IOOptionBits response
)
1321 return( kIOReturnUnsupported
);
1324 IONotifier
* IOService::registerInterest( const OSSymbol
* typeOfInterest
,
1325 IOServiceInterestHandler handler
, void * target
, void * ref
)
1327 _IOServiceInterestNotifier
* notify
= 0;
1330 if( (typeOfInterest
!= gIOGeneralInterest
)
1331 && (typeOfInterest
!= gIOBusyInterest
)
1332 && (typeOfInterest
!= gIOAppPowerStateInterest
)
1333 && (typeOfInterest
!= gIOPriorityPowerStateInterest
))
1336 lockForArbitration();
1337 if( 0 == (__state
[0] & kIOServiceInactiveState
)) {
1339 notify
= new _IOServiceInterestNotifier
;
1340 if( notify
&& !notify
->init()) {
1346 notify
->handler
= handler
;
1347 notify
->target
= target
;
1349 notify
->state
= kIOServiceNotifyEnable
;
1350 queue_init( ¬ify
->handlerInvocations
);
1355 if( 0 == (set
= (OSArray
*) getProperty( typeOfInterest
))) {
1356 set
= OSArray::withCapacity( 1 );
1358 setProperty( typeOfInterest
, set
);
1362 notify
->whence
= set
;
1364 set
->setObject( notify
);
1368 unlockForArbitration();
1373 static void cleanInterestArray( OSObject
* object
)
1377 _IOServiceInterestNotifier
* next
;
1379 if( (array
= OSDynamicCast( OSArray
, object
))) {
1382 (next
= (_IOServiceInterestNotifier
*)
1383 array
->getObject( index
));
1391 void IOService::unregisterAllInterest( void )
1393 cleanInterestArray( getProperty( gIOGeneralInterest
));
1394 cleanInterestArray( getProperty( gIOBusyInterest
));
1395 cleanInterestArray( getProperty( gIOAppPowerStateInterest
));
1396 cleanInterestArray( getProperty( gIOPriorityPowerStateInterest
));
1400 * _IOServiceInterestNotifier
1403 // wait for all threads, other than the current one,
1404 // to exit the handler
1406 void _IOServiceInterestNotifier::wait()
1408 _IOServiceNotifierInvocation
* next
;
1413 queue_iterate( &handlerInvocations
, next
,
1414 _IOServiceNotifierInvocation
*, link
) {
1415 if( next
->thread
!= current_thread() ) {
1421 state
|= kIOServiceNotifyWaiter
;
1428 void _IOServiceInterestNotifier::free()
1430 assert( queue_empty( &handlerInvocations
));
1434 void _IOServiceInterestNotifier::remove()
1439 whence
->removeObject(whence
->getNextIndexOfObject(
1440 (OSObject
*) this, 0 ));
1444 state
&= ~kIOServiceNotifyEnable
;
1453 bool _IOServiceInterestNotifier::disable()
1459 ret
= (0 != (kIOServiceNotifyEnable
& state
));
1460 state
&= ~kIOServiceNotifyEnable
;
1469 void _IOServiceInterestNotifier::enable( bool was
)
1473 state
|= kIOServiceNotifyEnable
;
1475 state
&= ~kIOServiceNotifyEnable
;
1479 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1485 #define tailQ(o) setObject(o)
1486 #define headQ(o) setObject(0, o)
1487 #define TLOG(fmt, args...) { if(kIOLogYield & gIOKitDebug) IOLog(fmt, ## args); }
1489 inline void _workLoopAction( IOWorkLoop::Action action
,
1490 IOService
* service
,
1491 void * p0
= 0, void * p1
= 0,
1492 void * p2
= 0, void * p3
= 0 )
1496 if( (wl
= service
->getWorkLoop())) {
1498 wl
->runAction( action
, service
, p0
, p1
, p2
, p3
);
1501 (*action
)( service
, p0
, p1
, p2
, p3
);
1504 bool IOService::requestTerminate( IOService
* provider
, IOOptionBits options
)
1508 // if its our only provider
1509 ok
= isParent( provider
, gIOServicePlane
, true);
1513 provider
->terminateClient( this, options
| kIOServiceRecursing
);
1514 ok
= (0 != (__state
[1] & kIOServiceRecursing
));
1521 bool IOService::terminatePhase1( IOOptionBits options
= 0 )
1526 OSArray
* makeInactive
;
1529 bool startPhase2
= false;
1531 TLOG("%s::terminatePhase1(%08lx)\n", getName(), options
);
1534 if( options
& kIOServiceRecursing
) {
1535 __state
[1] |= kIOServiceRecursing
;
1540 makeInactive
= OSArray::withCapacity( 16 );
1549 didInactive
= victim
->lockForArbitration( true );
1551 didInactive
= (0 == (victim
->__state
[0] & kIOServiceInactiveState
));
1553 victim
->__state
[0] |= kIOServiceInactiveState
;
1554 victim
->__state
[0] &= ~(kIOServiceRegisteredState
| kIOServiceMatchedState
1555 | kIOServiceFirstPublishState
| kIOServiceFirstMatchState
);
1556 victim
->_adjustBusy( 1 );
1558 victim
->unlockForArbitration();
1561 startPhase2
= didInactive
;
1564 victim
->deliverNotification( gIOTerminatedNotification
, 0, 0xffffffff );
1565 IOUserClient::destroyUserReferences( victim
);
1566 victim
->unregisterAllInterest();
1568 iter
= victim
->getClientIterator();
1570 while( (client
= (IOService
*) iter
->getNextObject())) {
1571 TLOG("%s::requestTerminate(%s, %08lx)\n",
1572 client
->getName(), victim
->getName(), options
);
1573 ok
= client
->requestTerminate( victim
, options
);
1574 TLOG("%s::requestTerminate(%s, ok = %d)\n",
1575 client
->getName(), victim
->getName(), ok
);
1577 makeInactive
->setObject( client
);
1583 victim
= (IOService
*) makeInactive
->getObject(0);
1586 makeInactive
->removeObject(0);
1590 makeInactive
->release();
1593 scheduleTerminatePhase2( options
);
1598 void IOService::scheduleTerminatePhase2( IOOptionBits options
= 0 )
1600 AbsoluteTime deadline
;
1602 bool wait
, haveDeadline
= false;
1604 options
|= kIOServiceRequired
;
1608 IOLockLock( gJobsLock
);
1610 if( (options
& kIOServiceSynchronous
)
1611 && (current_thread() != gIOTerminateThread
)) {
1614 wait
= (gIOTerminateThread
!= 0);
1616 // wait to become the terminate thread
1617 IOLockSleep( gJobsLock
, &gIOTerminateThread
, THREAD_UNINT
);
1621 gIOTerminateThread
= current_thread();
1622 gIOTerminatePhase2List
->setObject( this );
1626 terminateWorker( options
);
1627 wait
= (0 != (__state
[1] & kIOServiceBusyStateMask
));
1629 // wait for the victim to go non-busy
1630 if( !haveDeadline
) {
1631 clock_interval_to_deadline( 15, kSecondScale
, &deadline
);
1632 haveDeadline
= true;
1634 waitResult
= IOLockSleepDeadline( gJobsLock
, &gIOTerminateWork
,
1635 deadline
, THREAD_UNINT
);
1636 if( waitResult
== THREAD_TIMED_OUT
) {
1637 TLOG("%s::terminate(kIOServiceSynchronous) timeout", getName());
1639 thread_cancel_timer();
1641 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
1643 gIOTerminateThread
= 0;
1644 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1647 // ! kIOServiceSynchronous
1649 gIOTerminatePhase2List
->setObject( this );
1650 if( 0 == gIOTerminateWork
++)
1651 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) options
);
1654 IOLockUnlock( gJobsLock
);
1659 void IOService::terminateThread( void * arg
)
1661 IOLockLock( gJobsLock
);
1663 terminateWorker( (IOOptionBits
) arg
);
1665 gIOTerminateThread
= 0;
1666 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1668 IOLockUnlock( gJobsLock
);
1671 void IOService::scheduleStop( IOService
* provider
)
1673 TLOG("%s::scheduleStop(%s)\n", getName(), provider
->getName());
1675 IOLockLock( gJobsLock
);
1676 gIOStopList
->tailQ( this );
1677 gIOStopProviderList
->tailQ( provider
);
1679 if( 0 == gIOTerminateWork
++) {
1680 if( !gIOTerminateThread
)
1681 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) 0 );
1683 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1686 IOLockUnlock( gJobsLock
);
1689 void IOService::scheduleFinalize( void )
1691 TLOG("%s::scheduleFinalize\n", getName());
1693 IOLockLock( gJobsLock
);
1694 gIOFinalizeList
->tailQ( this );
1696 if( 0 == gIOTerminateWork
++) {
1697 if( !gIOTerminateThread
)
1698 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) 0 );
1700 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1703 IOLockUnlock( gJobsLock
);
1706 bool IOService::willTerminate( IOService
* provider
, IOOptionBits options
)
1711 bool IOService::didTerminate( IOService
* provider
, IOOptionBits options
, bool * defer
)
1713 if( false == *defer
) {
1715 if( lockForArbitration( true )) {
1716 if( false == provider
->handleIsOpen( this ))
1717 scheduleStop( provider
);
1720 message( kIOMessageServiceIsRequestingClose
, provider
, (void *) options
);
1721 if( false == provider
->handleIsOpen( this ))
1722 scheduleStop( provider
);
1725 unlockForArbitration();
1732 void IOService::actionWillTerminate( IOService
* victim
, IOOptionBits options
,
1733 OSArray
* doPhase2List
)
1739 iter
= victim
->getClientIterator();
1741 while( (client
= (IOService
*) iter
->getNextObject())) {
1742 TLOG("%s::willTerminate(%s, %08lx)\n",
1743 client
->getName(), victim
->getName(), options
);
1744 ok
= client
->willTerminate( victim
, options
);
1745 doPhase2List
->tailQ( client
);
1751 void IOService::actionDidTerminate( IOService
* victim
, IOOptionBits options
)
1757 victim
->messageClients( kIOMessageServiceIsTerminated
, (void *) options
);
1759 iter
= victim
->getClientIterator();
1761 while( (client
= (IOService
*) iter
->getNextObject())) {
1762 TLOG("%s::didTerminate(%s, %08lx)\n",
1763 client
->getName(), victim
->getName(), options
);
1764 client
->didTerminate( victim
, options
, &defer
);
1765 TLOG("%s::didTerminate(%s, defer %d)\n",
1766 client
->getName(), victim
->getName(), defer
);
1772 void IOService::actionFinalize( IOService
* victim
, IOOptionBits options
)
1774 TLOG("%s::finalize(%08lx)\n", victim
->getName(), options
);
1775 victim
->finalize( options
);
1778 void IOService::actionStop( IOService
* provider
, IOService
* client
)
1780 TLOG("%s::stop(%s)\n", client
->getName(), provider
->getName());
1781 client
->stop( provider
);
1782 if( provider
->isOpen( client
))
1783 provider
->close( client
);
1784 TLOG("%s::detach(%s)\n", client
->getName(), provider
->getName());
1785 client
->detach( provider
);
1788 void IOService::terminateWorker( IOOptionBits options
)
1790 OSArray
* doPhase2List
;
1791 OSArray
* didPhase2List
;
1796 IOService
* provider
;
1802 options
|= kIOServiceRequired
;
1804 doPhase2List
= OSArray::withCapacity( 16 );
1805 didPhase2List
= OSArray::withCapacity( 16 );
1806 freeList
= OSSet::withCapacity( 16 );
1807 if( (0 == doPhase2List
) || (0 == didPhase2List
) || (0 == freeList
))
1811 workDone
= gIOTerminateWork
;
1813 while( (victim
= (IOService
*) gIOTerminatePhase2List
->getObject(0) )) {
1816 gIOTerminatePhase2List
->removeObject(0);
1817 IOLockUnlock( gJobsLock
);
1821 doPhase2
= victim
->lockForArbitration( true );
1823 doPhase2
= (0 != (kIOServiceInactiveState
& victim
->__state
[0]));
1825 doPhase2
= (0 == (victim
->__state
[1] & kIOServiceTermPhase2State
))
1826 && (0 == (victim
->__state
[1] & kIOServiceConfigState
));
1828 victim
->__state
[1] |= kIOServiceTermPhase2State
;
1830 victim
->unlockForArbitration();
1833 if( 0 == victim
->getClient()) {
1834 // no clients - will go to finalize
1835 IOLockLock( gJobsLock
);
1836 gIOFinalizeList
->tailQ( victim
);
1837 IOLockUnlock( gJobsLock
);
1839 _workLoopAction( (IOWorkLoop::Action
) &actionWillTerminate
,
1840 victim
, (void *) options
, (void *) doPhase2List
);
1842 didPhase2List
->headQ( victim
);
1845 victim
= (IOService
*) doPhase2List
->getObject(0);
1848 doPhase2List
->removeObject(0);
1852 while( (victim
= (IOService
*) didPhase2List
->getObject(0)) ) {
1854 if( victim
->lockForArbitration( true )) {
1855 victim
->__state
[1] |= kIOServiceTermPhase3State
;
1856 victim
->unlockForArbitration();
1858 _workLoopAction( (IOWorkLoop::Action
) &actionDidTerminate
,
1859 victim
, (void *) options
);
1860 didPhase2List
->removeObject(0);
1862 IOLockLock( gJobsLock
);
1869 while( (victim
= (IOService
*) gIOFinalizeList
->getObject(0))) {
1871 IOLockUnlock( gJobsLock
);
1872 _workLoopAction( (IOWorkLoop::Action
) &actionFinalize
,
1873 victim
, (void *) options
);
1874 IOLockLock( gJobsLock
);
1876 freeList
->setObject( victim
);
1877 // safe if finalize list is append only
1878 gIOFinalizeList
->removeObject(0);
1882 (!doPhase3
) && (client
= (IOService
*) gIOStopList
->getObject(idx
)); ) {
1884 provider
= (IOService
*) gIOStopProviderList
->getObject(idx
);
1887 if( !provider
->isChild( client
, gIOServicePlane
)) {
1888 // may be multiply queued - nop it
1889 TLOG("%s::nop stop(%s)\n", client
->getName(), provider
->getName());
1891 // not ready for stop if it has clients, skip it
1892 if( (client
->__state
[1] & kIOServiceTermPhase3State
) && client
->getClient()) {
1893 TLOG("%s::defer stop(%s)\n", client
->getName(), provider
->getName());
1898 IOLockUnlock( gJobsLock
);
1899 _workLoopAction( (IOWorkLoop::Action
) &actionStop
,
1900 provider
, (void *) client
);
1901 IOLockLock( gJobsLock
);
1902 // check the finalize list now
1906 freeList
->setObject( client
);
1907 freeList
->setObject( provider
);
1909 // safe if stop list is append only
1910 gIOStopList
->removeObject( idx
);
1911 gIOStopProviderList
->removeObject( idx
);
1915 } while( doPhase3
);
1917 gIOTerminateWork
-= workDone
;
1918 moreToDo
= (gIOTerminateWork
!= 0);
1921 TLOG("iokit terminate done, %d stops remain\n", gIOStopList
->getCount());
1924 } while( moreToDo
);
1926 IOLockUnlock( gJobsLock
);
1928 freeList
->release();
1929 doPhase2List
->release();
1930 didPhase2List
->release();
1932 IOLockLock( gJobsLock
);
1935 bool IOService::finalize( IOOptionBits options
)
1938 IOService
* provider
;
1940 iter
= getProviderIterator();
1944 while( (provider
= (IOService
*) iter
->getNextObject())) {
1947 if( 0 == (__state
[1] & kIOServiceTermPhase3State
)) {
1948 /* we come down here on programmatic terminate */
1950 if( provider
->isOpen( this ))
1951 provider
->close( this );
1955 if( provider
->lockForArbitration( true )) {
1956 if( 0 == (provider
->__state
[1] & kIOServiceTermPhase3State
))
1957 scheduleStop( provider
);
1958 provider
->unlockForArbitration();
1975 void IOService::doServiceTerminate( IOOptionBits options
)
1979 // a method in case someone needs to override it
1980 bool IOService::terminateClient( IOService
* client
, IOOptionBits options
)
1984 if( client
->isParent( this, gIOServicePlane
, true))
1985 // we are the clients only provider
1986 ok
= client
->terminate( options
);
1993 bool IOService::terminate( IOOptionBits options
= 0 )
1995 options
|= kIOServiceTerminate
;
1997 return( terminatePhase1( options
));
2000 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2006 struct ServiceOpenMessageContext
2008 IOService
* service
;
2010 IOService
* excludeClient
;
2011 IOOptionBits options
;
2014 static void serviceOpenMessageApplier( OSObject
* object
, void * ctx
)
2016 ServiceOpenMessageContext
* context
= (ServiceOpenMessageContext
*) ctx
;
2018 if( object
!= context
->excludeClient
)
2019 context
->service
->messageClient( context
->type
, object
, (void *) context
->options
);
2022 bool IOService::open( IOService
* forClient
,
2023 IOOptionBits options
= 0,
2027 ServiceOpenMessageContext context
;
2029 context
.service
= this;
2030 context
.type
= kIOMessageServiceIsAttemptingOpen
;
2031 context
.excludeClient
= forClient
;
2032 context
.options
= options
;
2034 applyToInterested( gIOGeneralInterest
,
2035 &serviceOpenMessageApplier
, &context
);
2037 if( false == lockForArbitration(false) )
2040 ok
= (0 == (__state
[0] & kIOServiceInactiveState
));
2042 ok
= handleOpen( forClient
, options
, arg
);
2044 unlockForArbitration();
2049 void IOService::close( IOService
* forClient
,
2050 IOOptionBits options
= 0 )
2055 lockForArbitration();
2057 wasClosed
= handleIsOpen( forClient
);
2059 handleClose( forClient
, options
);
2060 last
= (__state
[1] & kIOServiceTermPhase3State
);
2063 unlockForArbitration();
2066 forClient
->scheduleStop( this );
2068 else if( wasClosed
) {
2070 ServiceOpenMessageContext context
;
2072 context
.service
= this;
2073 context
.type
= kIOMessageServiceWasClosed
;
2074 context
.excludeClient
= forClient
;
2075 context
.options
= options
;
2077 applyToInterested( gIOGeneralInterest
,
2078 &serviceOpenMessageApplier
, &context
);
2082 bool IOService::isOpen( const IOService
* forClient
= 0 ) const
2084 IOService
* self
= (IOService
*) this;
2087 self
->lockForArbitration();
2089 ok
= handleIsOpen( forClient
);
2091 self
->unlockForArbitration();
2096 bool IOService::handleOpen( IOService
* forClient
,
2097 IOOptionBits options
,
2102 ok
= (0 == __owner
);
2104 __owner
= forClient
;
2106 else if( options
& kIOServiceSeize
) {
2107 ok
= (kIOReturnSuccess
== messageClient( kIOMessageServiceIsRequestingClose
,
2108 __owner
, (void *) options
));
2109 if( ok
&& (0 == __owner
))
2110 __owner
= forClient
;
2117 void IOService::handleClose( IOService
* forClient
,
2118 IOOptionBits options
)
2120 if( __owner
== forClient
)
2124 bool IOService::handleIsOpen( const IOService
* forClient
) const
2127 return( __owner
== forClient
);
2129 return( __owner
!= forClient
);
2133 * Probing & starting
2135 static SInt32
IONotifyOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2137 const _IOServiceNotifier
* obj1
= (const _IOServiceNotifier
*) inObj1
;
2138 const _IOServiceNotifier
* obj2
= (const _IOServiceNotifier
*) inObj2
;
2146 val1
= obj1
->priority
;
2149 val2
= obj2
->priority
;
2151 return ( val1
- val2
);
2154 static SInt32
IOServiceObjectOrder( const OSObject
* entry
, void * ref
)
2156 OSDictionary
* dict
;
2157 IOService
* service
;
2158 _IOServiceNotifier
* notify
;
2159 OSSymbol
* key
= (OSSymbol
*) ref
;
2162 if( (notify
= OSDynamicCast( _IOServiceNotifier
, entry
)))
2163 return( notify
->priority
);
2165 else if( (service
= OSDynamicCast( IOService
, entry
)))
2166 offset
= OSDynamicCast(OSNumber
, service
->getProperty( key
));
2167 else if( (dict
= OSDynamicCast( OSDictionary
, entry
)))
2168 offset
= OSDynamicCast(OSNumber
, dict
->getObject( key
));
2175 return( (SInt32
) offset
->unsigned32BitValue());
2177 return( kIODefaultProbeScore
);
2180 SInt32
IOServiceOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2182 const OSObject
* obj1
= (const OSObject
*) inObj1
;
2183 const OSObject
* obj2
= (const OSObject
*) inObj2
;
2191 val1
= IOServiceObjectOrder( obj1
, ref
);
2194 val2
= IOServiceObjectOrder( obj2
, ref
);
2196 return ( val1
- val2
);
2199 IOService
* IOService::getClientWithCategory( const OSSymbol
* category
)
2201 IOService
* service
= 0;
2203 const OSSymbol
* nextCat
;
2205 iter
= getClientIterator();
2207 while( (service
= (IOService
*) iter
->getNextObject())) {
2208 if( kIOServiceInactiveState
& service
->__state
[0])
2210 nextCat
= (const OSSymbol
*) OSDynamicCast( OSSymbol
,
2211 service
->getProperty( gIOMatchCategoryKey
));
2212 if( category
== nextCat
)
2220 bool IOService::invokeNotifer( _IOServiceNotifier
* notify
)
2222 _IOServiceNotifierInvocation invocation
;
2226 invocation
.thread
= current_thread();
2229 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
2232 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
2233 _IOServiceNotifierInvocation
*, link
);
2239 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
, this );
2242 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
2243 _IOServiceNotifierInvocation
*, link
);
2244 if( kIOServiceNotifyWaiter
& notify
->state
) {
2245 notify
->state
&= ~kIOServiceNotifyWaiter
;
2246 WAKEUPNOTIFY( notify
);
2255 * Alloc and probe matching classes,
2256 * called on the provider instance
2259 void IOService::probeCandidates( OSOrderedSet
* matches
)
2261 OSDictionary
* match
= 0;
2264 IOService
* newInst
;
2265 OSDictionary
* props
;
2268 OSOrderedSet
* familyMatches
= 0;
2269 OSOrderedSet
* startList
;
2270 OSDictionary
* startDict
= 0;
2271 const OSSymbol
* category
;
2273 _IOServiceNotifier
* notify
;
2274 OSObject
* nextMatch
= 0;
2276 bool needReloc
= false;
2282 while( !needReloc
&& (nextMatch
= matches
->getFirstObject())) {
2284 nextMatch
->retain();
2285 matches
->removeObject(nextMatch
);
2287 if( (notify
= OSDynamicCast( _IOServiceNotifier
, nextMatch
))) {
2289 lockForArbitration();
2290 if( 0 == (__state
[0] & kIOServiceInactiveState
))
2291 invokeNotifer( notify
);
2292 unlockForArbitration();
2293 nextMatch
->release();
2297 } else if( !(match
= OSDynamicCast( OSDictionary
, nextMatch
))) {
2298 nextMatch
->release();
2305 debugFlags
= getDebugFlags( match
);
2309 category
= OSDynamicCast( OSSymbol
,
2310 match
->getObject( gIOMatchCategoryKey
));
2312 category
= gIODefaultMatchCategoryKey
;
2314 if( getClientWithCategory( category
)) {
2316 if( debugFlags
& kIOLogMatch
)
2317 LOG("%s: match category %s exists\n", getName(),
2318 category
->getCStringNoCopy());
2320 nextMatch
->release();
2325 // create a copy now in case its modified during matching
2326 props
= OSDictionary::withDictionary( match
, match
->getCount());
2329 props
->setCapacityIncrement(1);
2331 // check the nub matches
2332 if( false == passiveMatch( props
, true ))
2335 // Check to see if driver reloc has been loaded.
2336 needReloc
= (false == gIOCatalogue
->isModuleLoaded( match
));
2339 if( debugFlags
& kIOLogCatalogue
)
2340 LOG("%s: stalling for module\n", getName());
2342 // If reloc hasn't been loaded, exit;
2343 // reprobing will occur after reloc has been loaded.
2347 // reorder on family matchPropertyTable score.
2348 if( 0 == familyMatches
)
2349 familyMatches
= OSOrderedSet::withCapacity( 1,
2350 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2352 familyMatches
->setObject( props
);
2357 nextMatch
->release();
2366 if( familyMatches
) {
2369 && (props
= (OSDictionary
*) familyMatches
->getFirstObject())) {
2372 familyMatches
->removeObject( props
);
2377 debugFlags
= getDebugFlags( props
);
2380 symbol
= OSDynamicCast( OSSymbol
,
2381 props
->getObject( gIOClassKey
));
2385 // alloc the driver instance
2386 inst
= (IOService
*) OSMetaClass::allocClassWithName( symbol
);
2389 IOLog("Couldn't alloc class \"%s\"\n",
2390 symbol
->getCStringNoCopy());
2394 // init driver instance
2395 if( !(inst
->init( props
))) {
2397 if( debugFlags
& kIOLogStart
)
2398 IOLog("%s::init fails\n", symbol
->getCStringNoCopy());
2402 if( __state
[1] & kIOServiceSynchronousState
)
2403 inst
->__state
[1] |= kIOServiceSynchronousState
;
2405 // give the driver the default match category if not specified
2406 category
= OSDynamicCast( OSSymbol
,
2407 props
->getObject( gIOMatchCategoryKey
));
2409 category
= gIODefaultMatchCategoryKey
;
2410 inst
->setProperty( gIOMatchCategoryKey
, (OSObject
*) category
);
2412 // attach driver instance
2413 if( !(inst
->attach( this )))
2416 // pass in score from property table
2417 score
= familyMatches
->orderObject( props
);
2419 // & probe the new driver instance
2421 if( debugFlags
& kIOLogProbe
)
2422 LOG("%s::probe(%s)\n",
2423 inst
->getMetaClass()->getClassName(), getName());
2426 newInst
= inst
->probe( this, &score
);
2427 inst
->detach( this );
2430 if( debugFlags
& kIOLogProbe
)
2431 IOLog("%s::probe fails\n", symbol
->getCStringNoCopy());
2437 newPri
= OSNumber::withNumber( score
, 32 );
2439 newInst
->setProperty( gIOProbeScoreKey
, newPri
);
2443 // add to start list for the match category
2445 startDict
= OSDictionary::withCapacity( 1 );
2446 assert( startDict
);
2447 startList
= (OSOrderedSet
*)
2448 startDict
->getObject( category
);
2449 if( 0 == startList
) {
2450 startList
= OSOrderedSet::withCapacity( 1,
2451 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2452 if( startDict
&& startList
) {
2453 startDict
->setObject( category
, startList
);
2454 startList
->release();
2457 assert( startList
);
2459 startList
->setObject( newInst
);
2467 familyMatches
->release();
2471 // start the best (until success) of each category
2473 iter
= OSCollectionIterator::withCollection( startDict
);
2475 while( (category
= (const OSSymbol
*) iter
->getNextObject())) {
2477 startList
= (OSOrderedSet
*) startDict
->getObject( category
);
2478 assert( startList
);
2483 while( true // (!started)
2484 && (inst
= (IOService
*)startList
->getFirstObject())) {
2487 startList
->removeObject(inst
);
2490 debugFlags
= getDebugFlags( inst
->getPropertyTable() );
2492 if( debugFlags
& kIOLogStart
) {
2494 LOG( "match category exists, skipping " );
2495 LOG( "%s::start(%s) <%d>\n", inst
->getName(),
2496 getName(), inst
->getRetainCount());
2499 if( false == started
)
2500 started
= startCandidate( inst
);
2502 if( (debugFlags
& kIOLogStart
) && (false == started
))
2503 LOG( "%s::start(%s) <%d> failed\n", inst
->getName(), getName(),
2504 inst
->getRetainCount());
2513 // adjust the busy count by -1 if matching is stalled for a module,
2514 // or +1 if a previously stalled matching is complete.
2515 lockForArbitration();
2518 adjBusy
= (__state
[1] & kIOServiceModuleStallState
) ? 0 : 1;
2520 __state
[1] |= kIOServiceModuleStallState
;
2522 } else if( __state
[1] & kIOServiceModuleStallState
) {
2523 __state
[1] &= ~kIOServiceModuleStallState
;
2527 _adjustBusy( adjBusy
);
2528 unlockForArbitration();
2531 startDict
->release();
2535 * Start a previously attached & probed instance,
2536 * called on exporting object instance
2539 bool IOService::startCandidate( IOService
* service
)
2543 ok
= service
->attach( this );
2546 // stall for any nub resources
2548 // stall for any driver resources
2549 service
->checkResources();
2552 ok
= service
->start( this );
2554 service
->detach( this );
2559 IOService
* IOService::resources( void )
2561 return( gIOResources
);
2564 void IOService::publishResource( const char * key
, OSObject
* value
= 0 )
2566 const OSSymbol
* sym
;
2568 if( (sym
= OSSymbol::withCString( key
))) {
2569 publishResource( sym
, value
);
2574 void IOService::publishResource( const OSSymbol
* key
, OSObject
* value
= 0 )
2577 value
= (OSObject
*) gIOServiceKey
;
2579 gIOResources
->setProperty( key
, value
);
2581 gIOResourceGenerationCount
++;
2582 gIOResources
->registerService();
2585 bool IOService::addNeededResource( const char * key
)
2587 OSObject
* resources
;
2592 resources
= getProperty( gIOResourceMatchKey
);
2594 newKey
= OSString::withCString( key
);
2595 if( (0 == resources
) || (0 == newKey
))
2598 set
= OSDynamicCast( OSSet
, resources
);
2600 set
= OSSet::withCapacity( 1 );
2602 set
->setObject( resources
);
2607 set
->setObject( newKey
);
2609 ret
= setProperty( gIOResourceMatchKey
, set
);
2615 bool IOService::checkResource( OSObject
* matching
)
2618 OSDictionary
* table
;
2620 if( (str
= OSDynamicCast( OSString
, matching
))) {
2621 if( gIOResources
->getProperty( str
))
2626 table
= resourceMatching( str
);
2627 else if( (table
= OSDynamicCast( OSDictionary
, matching
)))
2630 IOLog("%s: Can't match using: %s\n", getName(),
2631 matching
->getMetaClass()->getClassName());
2632 /* false would stall forever */
2636 if( gIOKitDebug
& kIOLogConfig
)
2637 LOG("config(%x): stalling %s\n", (int) IOThreadSelf(), getName());
2639 waitForService( table
);
2641 if( gIOKitDebug
& kIOLogConfig
)
2642 LOG("config(%x): waking\n", (int) IOThreadSelf() );
2647 bool IOService::checkResources( void )
2649 OSObject
* resources
;
2654 resources
= getProperty( gIOResourceMatchKey
);
2658 if( (set
= OSDynamicCast( OSSet
, resources
))) {
2660 iter
= OSCollectionIterator::withCollection( set
);
2662 while( ok
&& (resources
= iter
->getNextObject()) )
2663 ok
= checkResource( resources
);
2668 ok
= checkResource( resources
);
2674 _IOConfigThread
* _IOConfigThread::configThread( void )
2676 _IOConfigThread
* inst
;
2679 if( !(inst
= new _IOConfigThread
))
2683 if( !(inst
->thread
= IOCreateThread
2684 ( (IOThreadFunc
) &_IOConfigThread::main
, inst
)))
2697 void _IOConfigThread::free( void )
2702 void IOService::doServiceMatch( IOOptionBits options
)
2704 _IOServiceNotifier
* notify
;
2706 OSOrderedSet
* matches
;
2707 SInt32 catalogGeneration
;
2708 bool keepGuessing
= true;
2709 bool reRegistered
= true;
2711 // job->nub->deliverNotification( gIOPublishNotification,
2712 // kIOServiceRegisteredState, 0xffffffff );
2714 while( keepGuessing
) {
2716 matches
= gIOCatalogue
->findDrivers( this, &catalogGeneration
);
2717 // the matches list should always be created by findDrivers()
2720 lockForArbitration();
2721 if( 0 == (__state
[0] & kIOServiceFirstPublishState
))
2722 deliverNotification( gIOFirstPublishNotification
,
2723 kIOServiceFirstPublishState
, 0xffffffff );
2725 __state
[1] &= ~kIOServiceNeedConfigState
;
2726 __state
[1] |= kIOServiceConfigState
;
2727 __state
[0] |= kIOServiceRegisteredState
;
2729 if( reRegistered
&& (0 == (__state
[0] & kIOServiceInactiveState
))) {
2731 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
2732 gNotifications
->getObject( gIOPublishNotification
) );
2734 while((notify
= (_IOServiceNotifier
*)
2735 iter
->getNextObject())) {
2737 if( passiveMatch( notify
->matching
)
2738 && (kIOServiceNotifyEnable
& notify
->state
))
2739 matches
->setObject( notify
);
2746 unlockForArbitration();
2748 if( matches
->getCount() && (kIOReturnSuccess
== getResources()))
2749 probeCandidates( matches
);
2754 lockForArbitration();
2755 reRegistered
= (0 != (__state
[1] & kIOServiceNeedConfigState
));
2757 (reRegistered
|| (catalogGeneration
!=
2758 gIOCatalogue
->getGenerationCount()))
2759 && (0 == (__state
[0] & kIOServiceInactiveState
));
2762 unlockForArbitration();
2765 if( (0 == (__state
[0] & kIOServiceInactiveState
))
2766 && (0 == (__state
[1] & kIOServiceModuleStallState
)) ) {
2767 deliverNotification( gIOMatchedNotification
,
2768 kIOServiceMatchedState
, 0xffffffff );
2769 if( 0 == (__state
[0] & kIOServiceFirstMatchState
))
2770 deliverNotification( gIOFirstMatchNotification
,
2771 kIOServiceFirstMatchState
, 0xffffffff );
2774 __state
[1] &= ~kIOServiceConfigState
;
2775 if( __state
[0] & kIOServiceInactiveState
)
2776 scheduleTerminatePhase2();
2779 unlockForArbitration();
2782 UInt32
IOService::_adjustBusy( SInt32 delta
)
2787 bool wasQuiet
, nowQuiet
, needWake
;
2790 result
= __state
[1] & kIOServiceBusyStateMask
;
2794 next
->lockForArbitration();
2795 count
= next
->__state
[1] & kIOServiceBusyStateMask
;
2796 assert( count
< kIOServiceBusyMax
);
2797 wasQuiet
= (0 == count
);
2798 assert( (!wasQuiet
) || (delta
> 0));
2799 next
->__state
[1] += delta
;
2800 nowQuiet
= (0 == (next
->__state
[1] & kIOServiceBusyStateMask
));
2801 needWake
= (0 != (kIOServiceBusyWaiterState
& next
->__state
[1]));
2804 next
->__state
[1] &= ~kIOServiceBusyWaiterState
;
2805 IOLockLock( gIOServiceBusyLock
);
2806 thread_wakeup( (event_t
) next
);
2807 IOLockUnlock( gIOServiceBusyLock
);
2810 next
->unlockForArbitration();
2812 if( (wasQuiet
|| nowQuiet
) ) {
2815 OSObject
* interested
;
2817 array
= OSDynamicCast( OSArray
, next
->getProperty( gIOBusyInterest
));
2821 (interested
= array
->getObject( index
));
2823 next
->messageClient(kIOMessageServiceBusyStateChange
,
2824 interested
, (void *) wasQuiet
/* busy now */);
2829 if( nowQuiet
&& (next
== gIOServiceRoot
))
2830 OSMetaClass::considerUnloads();
2833 delta
= nowQuiet
? -1 : +1;
2835 } while( (wasQuiet
|| nowQuiet
) && (next
= next
->getProvider()));
2840 void IOService::adjustBusy( SInt32 delta
)
2842 lockForArbitration();
2843 _adjustBusy( delta
);
2844 unlockForArbitration();
2847 UInt32
IOService::getBusyState( void )
2849 return( __state
[1] & kIOServiceBusyStateMask
);
2852 IOReturn
IOService::waitForState( UInt32 mask
, UInt32 value
,
2853 mach_timespec_t
* timeout
= 0 )
2856 int waitResult
= THREAD_AWAKENED
;
2857 bool computeDeadline
= true;
2858 AbsoluteTime abstime
;
2861 lockForArbitration();
2862 IOLockLock( gIOServiceBusyLock
);
2863 wait
= (value
!= (__state
[1] & mask
));
2865 __state
[1] |= kIOServiceBusyWaiterState
;
2866 unlockForArbitration();
2867 assert_wait( (event_t
) this, THREAD_UNINT
);
2869 if( computeDeadline
) {
2870 AbsoluteTime nsinterval
;
2871 clock_interval_to_absolutetime_interval(
2872 timeout
->tv_sec
, kSecondScale
, &abstime
);
2873 clock_interval_to_absolutetime_interval(
2874 timeout
->tv_nsec
, kNanosecondScale
, &nsinterval
);
2875 ADD_ABSOLUTETIME( &abstime
, &nsinterval
);
2876 clock_absolutetime_interval_to_deadline(
2877 abstime
, &abstime
);
2878 computeDeadline
= false;
2880 thread_set_timer_deadline( abstime
);
2883 unlockForArbitration();
2884 IOLockUnlock( gIOServiceBusyLock
);
2886 waitResult
= thread_block(THREAD_CONTINUE_NULL
);
2887 if( timeout
&& (waitResult
!= THREAD_TIMED_OUT
))
2888 thread_cancel_timer();
2891 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
2893 if( waitResult
== THREAD_TIMED_OUT
)
2894 return( kIOReturnTimeout
);
2896 return( kIOReturnSuccess
);
2899 IOReturn
IOService::waitQuiet( mach_timespec_t
* timeout
= 0 )
2901 return( waitForState( kIOServiceBusyStateMask
, 0, timeout
));
2904 bool IOService::serializeProperties( OSSerialize
* s
) const
2907 ((IOService
*)this)->setProperty( ((IOService
*)this)->__state
,
2908 sizeof( __state
), "__state");
2910 return( super::serializeProperties(s
) );
2914 void _IOConfigThread::main( _IOConfigThread
* self
)
2916 _IOServiceJob
* job
;
2924 semaphore_wait( gJobsSemaphore
);
2926 IOTakeLock( gJobsLock
);
2927 job
= (_IOServiceJob
*) gJobs
->getFirstObject();
2929 gJobs
->removeObject(job
);
2932 // gNumConfigThreads--; // we're out of service
2933 gNumWaitingThreads
--; // we're out of service
2935 IOUnlock( gJobsLock
);
2941 if( gIOKitDebug
& kIOLogConfig
)
2942 LOG("config(%x): starting on %s, %d\n",
2943 (int) IOThreadSelf(), job
->nub
->getName(), job
->type
);
2945 switch( job
->type
) {
2948 nub
->doServiceMatch( job
->options
);
2952 LOG("config(%x): strange type (%d)\n",
2953 (int) IOThreadSelf(), job
->type
);
2960 IOTakeLock( gJobsLock
);
2961 alive
= (gOutstandingJobs
> gNumWaitingThreads
);
2963 gNumWaitingThreads
++; // back in service
2964 // gNumConfigThreads++;
2966 if( 0 == --gNumConfigThreads
) {
2967 // IOLog("MATCH IDLE\n");
2968 IOLockWakeup( gJobsLock
, (event_t
) &gNumConfigThreads
, /* one-thread */ false );
2971 IOUnlock( gJobsLock
);
2976 if( gIOKitDebug
& kIOLogConfig
)
2977 LOG("config(%x): terminating\n", (int) IOThreadSelf() );
2982 IOReturn
IOService::waitMatchIdle( UInt32 msToWait
)
2985 int waitResult
= THREAD_AWAKENED
;
2986 bool computeDeadline
= true;
2987 AbsoluteTime abstime
;
2989 IOLockLock( gJobsLock
);
2991 wait
= (0 != gNumConfigThreads
);
2994 if( computeDeadline
) {
2995 clock_interval_to_absolutetime_interval(
2996 msToWait
, kMillisecondScale
, &abstime
);
2997 clock_absolutetime_interval_to_deadline(
2998 abstime
, &abstime
);
2999 computeDeadline
= false;
3001 waitResult
= IOLockSleepDeadline( gJobsLock
, &gNumConfigThreads
,
3002 abstime
, THREAD_UNINT
);
3004 waitResult
= IOLockSleep( gJobsLock
, &gNumConfigThreads
,
3008 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
3009 IOLockUnlock( gJobsLock
);
3011 if( waitResult
== THREAD_TIMED_OUT
)
3012 return( kIOReturnTimeout
);
3014 return( kIOReturnSuccess
);
3017 void _IOServiceJob::pingConfig( _IOServiceJob
* job
)
3024 IOTakeLock( gJobsLock
);
3027 gJobs
->setLastObject( job
);
3029 count
= gNumWaitingThreads
;
3030 // if( gNumConfigThreads) count++;// assume we're called from a config thread
3032 create
= ( (gOutstandingJobs
> count
)
3033 && (gNumConfigThreads
< kMaxConfigThreads
) );
3035 gNumConfigThreads
++;
3036 gNumWaitingThreads
++;
3039 IOUnlock( gJobsLock
);
3044 if( gIOKitDebug
& kIOLogConfig
)
3045 LOG("config(%d): creating\n", gNumConfigThreads
- 1);
3046 _IOConfigThread::configThread();
3049 semaphore_signal( gJobsSemaphore
);
3053 // internal - call with gNotificationLock
3054 OSObject
* IOService::getExistingServices( OSDictionary
* matching
,
3055 IOOptionBits inState
, IOOptionBits options
= 0 )
3057 OSObject
* current
= 0;
3059 IOService
* service
;
3064 iter
= IORegistryIterator::iterateOver( gIOServicePlane
,
3065 kIORegistryIterateRecursively
);
3069 while( (service
= (IOService
*) iter
->getNextObject())) {
3070 if( (inState
== (service
->__state
[0] & inState
))
3071 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3072 && service
->passiveMatch( matching
)) {
3074 if( options
& kIONotifyOnce
) {
3079 ((OSSet
*)current
)->setObject( service
);
3081 current
= OSSet::withObjects(
3082 & (const OSObject
*) service
, 1, 1 );
3085 } while( !service
&& !iter
->isValid());
3089 if( current
&& (0 == (options
& kIONotifyOnce
))) {
3090 iter
= OSCollectionIterator::withCollection( (OSSet
*)current
);
3099 OSIterator
* IOService::getMatchingServices( OSDictionary
* matching
)
3103 // is a lock even needed?
3106 iter
= (OSIterator
*) getExistingServices( matching
,
3107 kIOServiceMatchedState
);
3115 // internal - call with gNotificationLock
3116 IONotifier
* IOService::setNotification(
3117 const OSSymbol
* type
, OSDictionary
* matching
,
3118 IOServiceNotificationHandler handler
, void * target
, void * ref
,
3119 SInt32 priority
= 0 )
3121 _IOServiceNotifier
* notify
= 0;
3127 notify
= new _IOServiceNotifier
;
3128 if( notify
&& !notify
->init()) {
3134 notify
->matching
= matching
;
3135 notify
->handler
= handler
;
3136 notify
->target
= target
;
3138 notify
->priority
= priority
;
3139 notify
->state
= kIOServiceNotifyEnable
;
3140 queue_init( ¬ify
->handlerInvocations
);
3144 if( 0 == (set
= (OSOrderedSet
*) gNotifications
->getObject( type
))) {
3145 set
= OSOrderedSet::withCapacity( 1,
3146 IONotifyOrdering
, 0 );
3148 gNotifications
->setObject( type
, set
);
3152 notify
->whence
= set
;
3154 set
->setObject( notify
);
3160 // internal - call with gNotificationLock
3161 IONotifier
* IOService::doInstallNotification(
3162 const OSSymbol
* type
, OSDictionary
* matching
,
3163 IOServiceNotificationHandler handler
,
3164 void * target
, void * ref
,
3165 SInt32 priority
, OSIterator
** existing
)
3168 IONotifier
* notify
;
3169 IOOptionBits inState
;
3174 if( type
== gIOPublishNotification
)
3175 inState
= kIOServiceRegisteredState
;
3177 else if( type
== gIOFirstPublishNotification
)
3178 inState
= kIOServiceFirstPublishState
;
3180 else if( (type
== gIOMatchedNotification
)
3181 || (type
== gIOFirstMatchNotification
))
3182 inState
= kIOServiceMatchedState
;
3183 else if( type
== gIOTerminatedNotification
)
3188 notify
= setNotification( type
, matching
, handler
, target
, ref
, priority
);
3191 // get the current set
3192 exist
= (OSIterator
*) getExistingServices( matching
, inState
);
3202 IONotifier
* IOService::installNotification(
3203 const OSSymbol
* type
, OSDictionary
* matching
,
3204 IOServiceNotificationHandler handler
,
3205 void * target
, void * ref
,
3206 SInt32 priority
, OSIterator
** existing
)
3208 IONotifier
* notify
;
3212 notify
= doInstallNotification( type
, matching
, handler
, target
, ref
,
3213 priority
, existing
);
3220 IONotifier
* IOService::addNotification(
3221 const OSSymbol
* type
, OSDictionary
* matching
,
3222 IOServiceNotificationHandler handler
,
3223 void * target
, void * ref
= 0,
3224 SInt32 priority
= 0 )
3226 OSIterator
* existing
;
3227 _IOServiceNotifier
* notify
;
3230 notify
= (_IOServiceNotifier
*) installNotification( type
, matching
,
3231 handler
, target
, ref
, priority
, &existing
);
3233 // send notifications for existing set
3236 notify
->retain(); // in case handler remove()s
3237 while( (next
= (IOService
*) existing
->getNextObject())) {
3239 next
->lockForArbitration();
3240 if( 0 == (next
->__state
[0] & kIOServiceInactiveState
))
3241 next
->invokeNotifer( notify
);
3242 next
->unlockForArbitration();
3245 existing
->release();
3251 struct SyncNotifyVars
{
3252 semaphore_port_t waitHere
;
3256 bool IOService::syncNotificationHandler(
3257 void * /* target */, void * ref
,
3258 IOService
* newService
)
3261 // result may get written more than once before the
3262 // notification is removed!
3263 ((SyncNotifyVars
*) ref
)->result
= newService
;
3264 semaphore_signal( ((SyncNotifyVars
*) ref
)->waitHere
);
3269 IOService
* IOService::waitForService( OSDictionary
* matching
,
3270 mach_timespec_t
* timeout
= 0 )
3272 IONotifier
* notify
= 0;
3273 // priority doesn't help us much since we need a thread wakeup
3274 SInt32 priority
= 0;
3275 SyncNotifyVars state
;
3276 kern_return_t err
= kIOReturnBadArgument
;
3288 state
.result
= (IOService
*) getExistingServices( matching
,
3289 kIOServiceMatchedState
, kIONotifyOnce
);
3293 err
= semaphore_create( kernel_task
, &state
.waitHere
,
3294 SYNC_POLICY_FIFO
, 0 );
3295 if( KERN_SUCCESS
!= err
)
3298 notify
= IOService::setNotification( gIOMatchedNotification
, matching
,
3299 &IOService::syncNotificationHandler
, (void *) 0,
3300 (void *) &state
, priority
);
3308 err
= semaphore_timedwait( state
.waitHere
, *timeout
);
3310 err
= semaphore_wait( state
.waitHere
);
3314 notify
->remove(); // dequeues
3316 matching
->release();
3318 semaphore_destroy( kernel_task
, state
.waitHere
);
3320 return( state
.result
);
3323 void IOService::deliverNotification( const OSSymbol
* type
,
3324 IOOptionBits orNewState
, IOOptionBits andNewState
)
3326 _IOServiceNotifier
* notify
;
3328 OSArray
* willSend
= 0;
3330 lockForArbitration();
3332 if( (0 == (__state
[0] & kIOServiceInactiveState
))
3333 || (type
== gIOTerminatedNotification
)) {
3337 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
3338 gNotifications
->getObject( type
) );
3341 while( (notify
= (_IOServiceNotifier
*) iter
->getNextObject())) {
3343 if( passiveMatch( notify
->matching
)
3344 && (kIOServiceNotifyEnable
& notify
->state
)) {
3346 willSend
= OSArray::withCapacity(8);
3348 willSend
->setObject( notify
);
3354 __state
[0] = (__state
[0] | orNewState
) & andNewState
;
3360 for( unsigned int idx
= 0;
3361 (notify
= (_IOServiceNotifier
*) willSend
->getObject(idx
));
3363 invokeNotifer( notify
);
3365 willSend
->release();
3367 unlockForArbitration();
3370 IOOptionBits
IOService::getState( void ) const
3372 return( __state
[0] );
3376 * Helpers to make matching objects for simple cases
3379 OSDictionary
* IOService::serviceMatching( const OSString
* name
,
3380 OSDictionary
* table
= 0 )
3383 table
= OSDictionary::withCapacity( 2 );
3385 table
->setObject(gIOProviderClassKey
, (OSObject
*)name
);
3390 OSDictionary
* IOService::serviceMatching( const char * name
,
3391 OSDictionary
* table
= 0 )
3393 const OSString
* str
;
3395 str
= OSSymbol::withCString( name
);
3399 table
= serviceMatching( str
, table
);
3404 OSDictionary
* IOService::nameMatching( const OSString
* name
,
3405 OSDictionary
* table
= 0 )
3408 table
= OSDictionary::withCapacity( 2 );
3410 table
->setObject( gIONameMatchKey
, (OSObject
*)name
);
3415 OSDictionary
* IOService::nameMatching( const char * name
,
3416 OSDictionary
* table
= 0 )
3418 const OSString
* str
;
3420 str
= OSSymbol::withCString( name
);
3424 table
= nameMatching( str
, table
);
3429 OSDictionary
* IOService::resourceMatching( const OSString
* str
,
3430 OSDictionary
* table
= 0 )
3432 table
= serviceMatching( gIOResourcesKey
, table
);
3434 table
->setObject( gIOResourceMatchKey
, (OSObject
*) str
);
3439 OSDictionary
* IOService::resourceMatching( const char * name
,
3440 OSDictionary
* table
= 0 )
3442 const OSSymbol
* str
;
3444 str
= OSSymbol::withCString( name
);
3448 table
= resourceMatching( str
, table
);
3455 * _IOServiceNotifier
3458 // wait for all threads, other than the current one,
3459 // to exit the handler
3461 void _IOServiceNotifier::wait()
3463 _IOServiceNotifierInvocation
* next
;
3468 queue_iterate( &handlerInvocations
, next
,
3469 _IOServiceNotifierInvocation
*, link
) {
3470 if( next
->thread
!= current_thread() ) {
3476 state
|= kIOServiceNotifyWaiter
;
3483 void _IOServiceNotifier::free()
3485 assert( queue_empty( &handlerInvocations
));
3489 void _IOServiceNotifier::remove()
3494 whence
->removeObject( (OSObject
*) this );
3498 matching
->release();
3502 state
&= ~kIOServiceNotifyEnable
;
3511 bool _IOServiceNotifier::disable()
3517 ret
= (0 != (kIOServiceNotifyEnable
& state
));
3518 state
&= ~kIOServiceNotifyEnable
;
3527 void _IOServiceNotifier::enable( bool was
)
3531 state
|= kIOServiceNotifyEnable
;
3533 state
&= ~kIOServiceNotifyEnable
;
3541 IOService
* IOResources::resources( void )
3545 inst
= new IOResources
;
3546 if( inst
&& !inst
->init()) {
3554 IOWorkLoop
* IOResources::getWorkLoop() const
3556 // If we are the resource root then bringe over to the
3557 // platform to get its workloop
3558 if (this == (IOResources
*) gIOResources
)
3559 return getPlatform()->getWorkLoop();
3561 return IOService::getWorkLoop();
3564 bool IOResources::matchPropertyTable( OSDictionary
* table
)
3572 prop
= table
->getObject( gIOResourceMatchKey
);
3573 str
= OSDynamicCast( OSString
, prop
);
3575 ok
= (0 != getProperty( str
));
3577 else if( (set
= OSDynamicCast( OSSet
, prop
))) {
3579 iter
= OSCollectionIterator::withCollection( set
);
3581 while( ok
&& (str
= OSDynamicCast( OSString
, iter
->getNextObject()) ))
3582 ok
= (0 != getProperty( str
));
3591 IOReturn
IOResources::setProperties( OSObject
* properties
)
3594 const OSSymbol
* key
;
3595 OSDictionary
* dict
;
3596 OSCollectionIterator
* iter
;
3598 err
= IOUserClient::clientHasPrivilege(current_task(), kIOClientPrivilegeAdministrator
);
3599 if ( kIOReturnSuccess
!= err
)
3602 dict
= OSDynamicCast(OSDictionary
, properties
);
3604 return( kIOReturnBadArgument
);
3606 iter
= OSCollectionIterator::withCollection( dict
);
3608 return( kIOReturnBadArgument
);
3610 while( (key
= OSDynamicCast(OSSymbol
, iter
->getNextObject()))) {
3611 publishResource( key
, dict
->getObject(key
) );
3616 return( kIOReturnSuccess
);
3620 * Helpers for matching dictionaries.
3621 * Keys existing in matching are checked in properties.
3622 * Keys may be a string or OSCollection of IOStrings
3625 bool IOService::compareProperty( OSDictionary
* matching
,
3631 value
= matching
->getObject( key
);
3633 ok
= value
->isEqualTo( getProperty( key
));
3641 bool IOService::compareProperty( OSDictionary
* matching
,
3642 const OSString
* key
)
3647 value
= matching
->getObject( key
);
3649 ok
= value
->isEqualTo( getProperty( key
));
3656 bool IOService::compareProperties( OSDictionary
* matching
,
3657 OSCollection
* keys
)
3659 OSCollectionIterator
* iter
;
3660 const OSString
* key
;
3663 if( !matching
|| !keys
)
3666 iter
= OSCollectionIterator::withCollection( keys
);
3669 while( ok
&& (key
= OSDynamicCast( OSString
, iter
->getNextObject())))
3670 ok
= compareProperty( matching
, key
);
3674 keys
->release(); // !! consume a ref !!
3679 /* Helper to add a location matching dict to the table */
3681 OSDictionary
* IOService::addLocation( OSDictionary
* table
)
3683 OSDictionary
* dict
;
3688 dict
= OSDictionary::withCapacity( 1 );
3690 table
->setObject( gIOLocationMatchKey
, dict
);
3698 * Go looking for a provider to match a location dict.
3701 IOService
* IOService::matchLocation( IOService
* /* client */ )
3705 parent
= getProvider();
3708 parent
= parent
->matchLocation( this );
3713 bool IOService::passiveMatch( OSDictionary
* table
, bool changesOK
)
3719 IORegistryEntry
* entry
;
3724 bool matchParent
= false;
3735 str
= OSDynamicCast( OSString
, table
->getObject( gIOProviderClassKey
));
3738 match
= (0 != where
->metaCast( str
));
3743 obj
= table
->getObject( gIONameMatchKey
);
3746 match
= where
->compareNames( obj
, changesOK
? &matched
: 0 );
3749 if( changesOK
&& matched
) {
3750 // leave a hint as to which name matched
3751 table
->setObject( gIONameMatchedKey
, matched
);
3756 str
= OSDynamicCast( OSString
, table
->getObject( gIOLocationMatchKey
));
3759 const OSSymbol
* sym
;
3763 sym
= where
->copyLocation();
3765 match
= sym
->isEqualTo( str
);
3772 obj
= table
->getObject( gIOPropertyMatchKey
);
3775 OSDictionary
* dict
;
3776 OSDictionary
* nextDict
;
3781 dict
= where
->dictionaryWithProperties();
3783 nextDict
= OSDynamicCast( OSDictionary
, obj
);
3787 iter
= OSCollectionIterator::withCollection(
3788 OSDynamicCast(OSCollection
, obj
));
3791 || (iter
&& (0 != (nextDict
= OSDynamicCast(OSDictionary
,
3792 iter
->getNextObject()))))) {
3793 match
= dict
->isEqualTo( nextDict
, nextDict
);
3806 str
= OSDynamicCast( OSString
, table
->getObject( gIOPathMatchKey
));
3809 entry
= IORegistryEntry::fromPath( str
->getCStringNoCopy() );
3810 match
= (where
== entry
);
3817 num
= OSDynamicCast( OSNumber
, table
->getObject( gIOMatchedServiceCountKey
));
3821 IOService
* service
= 0;
3822 UInt32 serviceCount
= 0;
3825 iter
= where
->getClientIterator();
3827 while( (service
= (IOService
*) iter
->getNextObject())) {
3828 if( kIOServiceInactiveState
& service
->__state
[0])
3830 if( 0 == service
->getProperty( gIOMatchCategoryKey
))
3836 match
= (serviceCount
== num
->unsigned32BitValue());
3841 if( done
== table
->getCount()) {
3842 // don't call family if we've done all the entries in the table
3843 matchParent
= false;
3847 // pass in score from property table
3848 score
= IOServiceObjectOrder( table
, (void *) gIOProbeScoreKey
);
3850 // do family specific matching
3851 match
= where
->matchPropertyTable( table
, &score
);
3855 if( kIOLogMatch
& getDebugFlags( table
))
3856 LOG("%s: family specific matching fails\n", where
->getName());
3863 newPri
= OSNumber::withNumber( score
, 32 );
3865 table
->setObject( gIOProbeScoreKey
, newPri
);
3870 if( !(match
= where
->compareProperty( table
, kIOBSDNameKey
)))
3873 matchParent
= false;
3875 obj
= OSDynamicCast( OSDictionary
,
3876 table
->getObject( gIOParentMatchKey
));
3880 table
= (OSDictionary
*) obj
;
3884 table
= OSDynamicCast( OSDictionary
,
3885 table
->getObject( gIOLocationMatchKey
));
3888 where
= where
->getProvider();
3890 where
= where
->matchLocation( where
);
3893 } while( table
&& where
);
3895 } while( matchParent
&& (where
= where
->getProvider()) );
3897 if( kIOLogMatch
& gIOKitDebug
)
3899 LOG("match parent @ %s = %d\n",
3900 where
->getName(), match
);
3906 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
3907 UInt32 type
, OSDictionary
* properties
,
3908 IOUserClient
** handler
)
3910 const OSSymbol
*userClientClass
= 0;
3911 IOUserClient
*client
;
3914 // First try my own properties for a user client class name
3915 temp
= getProperty(gIOUserClientClassKey
);
3917 if (OSDynamicCast(OSSymbol
, temp
))
3918 userClientClass
= (const OSSymbol
*) temp
;
3919 else if (OSDynamicCast(OSString
, temp
)) {
3920 userClientClass
= OSSymbol::withString((OSString
*) temp
);
3921 if (userClientClass
)
3922 setProperty(kIOUserClientClassKey
,
3923 (OSObject
*) userClientClass
);
3927 // Didn't find one so lets just bomb out now without further ado.
3928 if (!userClientClass
)
3929 return kIOReturnUnsupported
;
3931 temp
= OSMetaClass::allocClassWithName(userClientClass
);
3933 return kIOReturnNoMemory
;
3935 if (OSDynamicCast(IOUserClient
, temp
))
3936 client
= (IOUserClient
*) temp
;
3939 return kIOReturnUnsupported
;
3942 if ( !client
->initWithTask(owningTask
, securityID
, type
, properties
) ) {
3944 return kIOReturnBadArgument
;
3947 if ( !client
->attach(this) ) {
3949 return kIOReturnUnsupported
;
3952 if ( !client
->start(this) ) {
3953 client
->detach(this);
3955 return kIOReturnUnsupported
;
3959 return kIOReturnSuccess
;
3962 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
3963 UInt32 type
, IOUserClient
** handler
)
3965 return( newUserClient( owningTask
, securityID
, type
, 0, handler
));
3968 IOReturn
IOService::requestProbe( IOOptionBits options
)
3970 return( kIOReturnUnsupported
);
3974 * Convert an IOReturn to text. Subclasses which add additional
3975 * IOReturn's should override this method and call
3976 * super::stringFromReturn if the desired value is not found.
3979 const char * IOService::stringFromReturn( IOReturn rtn
)
3981 static const IONamedValue IOReturn_values
[] = {
3982 {kIOReturnSuccess
, "success" },
3983 {kIOReturnError
, "general error" },
3984 {kIOReturnNoMemory
, "memory allocation error" },
3985 {kIOReturnNoResources
, "resource shortage" },
3986 {kIOReturnIPCError
, "Mach IPC failure" },
3987 {kIOReturnNoDevice
, "no such device" },
3988 {kIOReturnNotPrivileged
, "privilege violation" },
3989 {kIOReturnBadArgument
, "invalid argument" },
3990 {kIOReturnLockedRead
, "device is read locked" },
3991 {kIOReturnLockedWrite
, "device is write locked" },
3992 {kIOReturnExclusiveAccess
, "device is exclusive access" },
3993 {kIOReturnBadMessageID
, "bad IPC message ID" },
3994 {kIOReturnUnsupported
, "unsupported function" },
3995 {kIOReturnVMError
, "virtual memory error" },
3996 {kIOReturnInternalError
, "internal driver error" },
3997 {kIOReturnIOError
, "I/O error" },
3998 {kIOReturnCannotLock
, "cannot acquire lock" },
3999 {kIOReturnNotOpen
, "device is not open" },
4000 {kIOReturnNotReadable
, "device is not readable" },
4001 {kIOReturnNotWritable
, "device is not writeable" },
4002 {kIOReturnNotAligned
, "alignment error" },
4003 {kIOReturnBadMedia
, "media error" },
4004 {kIOReturnStillOpen
, "device is still open" },
4005 {kIOReturnRLDError
, "rld failure" },
4006 {kIOReturnDMAError
, "DMA failure" },
4007 {kIOReturnBusy
, "device is busy" },
4008 {kIOReturnTimeout
, "I/O timeout" },
4009 {kIOReturnOffline
, "device is offline" },
4010 {kIOReturnNotReady
, "device is not ready" },
4011 {kIOReturnNotAttached
, "device/channel is not attached" },
4012 {kIOReturnNoChannels
, "no DMA channels available" },
4013 {kIOReturnNoSpace
, "no space for data" },
4014 {kIOReturnPortExists
, "device port already exists" },
4015 {kIOReturnCannotWire
, "cannot wire physical memory" },
4016 {kIOReturnNoInterrupt
, "no interrupt attached" },
4017 {kIOReturnNoFrames
, "no DMA frames enqueued" },
4018 {kIOReturnMessageTooLarge
, "message is too large" },
4019 {kIOReturnNotPermitted
, "operation is not permitted" },
4020 {kIOReturnNoPower
, "device is without power" },
4021 {kIOReturnNoMedia
, "media is not present" },
4022 {kIOReturnUnformattedMedia
, "media is not formatted" },
4023 {kIOReturnUnsupportedMode
, "unsupported mode" },
4024 {kIOReturnUnderrun
, "data underrun" },
4025 {kIOReturnOverrun
, "data overrun" },
4026 {kIOReturnDeviceError
, "device error" },
4027 {kIOReturnNoCompletion
, "no completion routine" },
4028 {kIOReturnAborted
, "operation was aborted" },
4029 {kIOReturnNoBandwidth
, "bus bandwidth would be exceeded" },
4030 {kIOReturnNotResponding
, "device is not responding" },
4031 {kIOReturnInvalid
, "unanticipated driver error" },
4035 return IOFindNameForValue(rtn
, IOReturn_values
);
4039 * Convert an IOReturn to an errno.
4041 int IOService::errnoFromReturn( IOReturn rtn
)
4045 case kIOReturnSuccess
:
4047 case kIOReturnNoMemory
:
4049 case kIOReturnNoDevice
:
4051 case kIOReturnVMError
:
4053 case kIOReturnNotPermitted
:
4055 case kIOReturnNotPrivileged
:
4057 case kIOReturnIOError
:
4059 case kIOReturnNotWritable
:
4061 case kIOReturnBadArgument
:
4063 case kIOReturnUnsupported
:
4067 case kIOReturnNoPower
:
4069 case kIOReturnDeviceError
:
4071 case kIOReturnTimeout
:
4073 case kIOReturnMessageTooLarge
:
4075 case kIOReturnNoSpace
:
4077 case kIOReturnCannotLock
:
4081 case kIOReturnBadMessageID
:
4082 case kIOReturnNoCompletion
:
4083 case kIOReturnNotAligned
:
4085 case kIOReturnNotReady
:
4087 case kIOReturnRLDError
:
4089 case kIOReturnPortExists
:
4090 case kIOReturnStillOpen
:
4092 case kIOReturnExclusiveAccess
:
4093 case kIOReturnLockedRead
:
4094 case kIOReturnLockedWrite
:
4095 case kIOReturnNotAttached
:
4096 case kIOReturnNotOpen
:
4097 case kIOReturnNotReadable
:
4099 case kIOReturnCannotWire
:
4100 case kIOReturnNoResources
:
4102 case kIOReturnAborted
:
4103 case kIOReturnOffline
:
4104 case kIOReturnNotResponding
:
4106 case kIOReturnBadMedia
:
4107 case kIOReturnNoMedia
:
4108 case kIOReturnUnformattedMedia
:
4109 return(ENXIO
); // (media error)
4110 case kIOReturnDMAError
:
4111 case kIOReturnOverrun
:
4112 case kIOReturnUnderrun
:
4113 return(EIO
); // (transfer error)
4114 case kIOReturnNoBandwidth
:
4115 case kIOReturnNoChannels
:
4116 case kIOReturnNoFrames
:
4117 case kIOReturnNoInterrupt
:
4118 return(EIO
); // (hardware error)
4119 case kIOReturnError
:
4120 case kIOReturnInternalError
:
4121 case kIOReturnInvalid
:
4122 return(EIO
); // (generic error)
4123 case kIOReturnIPCError
:
4124 return(EIO
); // (ipc error)
4126 return(EIO
); // (all other errors)
4130 IOReturn
IOService::message( UInt32 type
, IOService
* provider
,
4134 * Generic entry point for calls from the provider. A return value of
4135 * kIOReturnSuccess indicates that the message was received, and where
4136 * applicable, that it was successful.
4139 return kIOReturnUnsupported
;
4146 IOItemCount
IOService::getDeviceMemoryCount( void )
4151 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4153 count
= array
->getCount();
4160 IODeviceMemory
* IOService::getDeviceMemoryWithIndex( unsigned int index
)
4163 IODeviceMemory
* range
;
4165 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4167 range
= (IODeviceMemory
*) array
->getObject( index
);
4174 IOMemoryMap
* IOService::mapDeviceMemoryWithIndex( unsigned int index
,
4175 IOOptionBits options
= 0 )
4177 IODeviceMemory
* range
;
4180 range
= getDeviceMemoryWithIndex( index
);
4182 map
= range
->map( options
);
4189 OSArray
* IOService::getDeviceMemory( void )
4191 return( OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
)));
4195 void IOService::setDeviceMemory( OSArray
* array
)
4197 setProperty( gIODeviceMemoryKey
, array
);
4204 IOReturn
IOService::resolveInterrupt(IOService
*nub
, int source
)
4206 IOInterruptController
*interruptController
;
4209 OSSymbol
*interruptControllerName
;
4211 IOInterruptSource
*interruptSources
;
4213 // Get the parents list from the nub.
4214 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptControllersKey
));
4215 if (array
== 0) return kIOReturnNoResources
;
4217 // Allocate space for the IOInterruptSources if needed... then return early.
4218 if (nub
->_interruptSources
== 0) {
4219 numSources
= array
->getCount();
4220 interruptSources
= (IOInterruptSource
*)IOMalloc(numSources
* sizeof(IOInterruptSource
));
4221 if (interruptSources
== 0) return kIOReturnNoMemory
;
4223 bzero(interruptSources
, numSources
* sizeof(IOInterruptSource
));
4225 nub
->_numInterruptSources
= numSources
;
4226 nub
->_interruptSources
= interruptSources
;
4227 return kIOReturnSuccess
;
4230 interruptControllerName
= OSDynamicCast(OSSymbol
,array
->getObject(source
));
4231 if (interruptControllerName
== 0) return kIOReturnNoResources
;
4233 interruptController
= getPlatform()->lookUpInterruptController(interruptControllerName
);
4234 if (interruptController
== 0) return kIOReturnNoResources
;
4236 // Get the interrupt numbers from the nub.
4237 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptSpecifiersKey
));
4238 if (array
== 0) return kIOReturnNoResources
;
4239 data
= OSDynamicCast(OSData
, array
->getObject(source
));
4240 if (data
== 0) return kIOReturnNoResources
;
4242 // Set the interruptController and interruptSource in the nub's table.
4243 interruptSources
= nub
->_interruptSources
;
4244 interruptSources
[source
].interruptController
= interruptController
;
4245 interruptSources
[source
].vectorData
= data
;
4247 return kIOReturnSuccess
;
4250 IOReturn
IOService::lookupInterrupt(int source
, bool resolve
, IOInterruptController
**interruptController
)
4254 /* Make sure the _interruptSources are set */
4255 if (_interruptSources
== 0) {
4256 ret
= resolveInterrupt(this, source
);
4257 if (ret
!= kIOReturnSuccess
) return ret
;
4260 /* Make sure the local source number is valid */
4261 if ((source
< 0) || (source
>= _numInterruptSources
))
4262 return kIOReturnNoInterrupt
;
4264 /* Look up the contoller for the local source */
4265 *interruptController
= _interruptSources
[source
].interruptController
;
4267 if (*interruptController
== NULL
) {
4268 if (!resolve
) return kIOReturnNoInterrupt
;
4270 /* Try to reslove the interrupt */
4271 ret
= resolveInterrupt(this, source
);
4272 if (ret
!= kIOReturnSuccess
) return ret
;
4274 *interruptController
= _interruptSources
[source
].interruptController
;
4277 return kIOReturnSuccess
;
4280 IOReturn
IOService::registerInterrupt(int source
, OSObject
*target
,
4281 IOInterruptAction handler
,
4284 IOInterruptController
*interruptController
;
4287 ret
= lookupInterrupt(source
, true, &interruptController
);
4288 if (ret
!= kIOReturnSuccess
) return ret
;
4290 /* Register the source */
4291 return interruptController
->registerInterrupt(this, source
, target
,
4292 (IOInterruptHandler
)handler
,
4296 IOReturn
IOService::unregisterInterrupt(int source
)
4298 IOInterruptController
*interruptController
;
4301 ret
= lookupInterrupt(source
, false, &interruptController
);
4302 if (ret
!= kIOReturnSuccess
) return ret
;
4304 /* Unregister the source */
4305 return interruptController
->unregisterInterrupt(this, source
);
4308 IOReturn
IOService::getInterruptType(int source
, int *interruptType
)
4310 IOInterruptController
*interruptController
;
4313 ret
= lookupInterrupt(source
, true, &interruptController
);
4314 if (ret
!= kIOReturnSuccess
) return ret
;
4316 /* Return the type */
4317 return interruptController
->getInterruptType(this, source
, interruptType
);
4320 IOReturn
IOService::enableInterrupt(int source
)
4322 IOInterruptController
*interruptController
;
4325 ret
= lookupInterrupt(source
, false, &interruptController
);
4326 if (ret
!= kIOReturnSuccess
) return ret
;
4328 /* Enable the source */
4329 return interruptController
->enableInterrupt(this, source
);
4332 IOReturn
IOService::disableInterrupt(int source
)
4334 IOInterruptController
*interruptController
;
4337 ret
= lookupInterrupt(source
, false, &interruptController
);
4338 if (ret
!= kIOReturnSuccess
) return ret
;
4340 /* Disable the source */
4341 return interruptController
->disableInterrupt(this, source
);
4344 IOReturn
IOService::causeInterrupt(int source
)
4346 IOInterruptController
*interruptController
;
4349 ret
= lookupInterrupt(source
, false, &interruptController
);
4350 if (ret
!= kIOReturnSuccess
) return ret
;
4352 /* Cause an interrupt for the source */
4353 return interruptController
->causeInterrupt(this, source
);
4356 OSMetaClassDefineReservedUsed(IOService
, 0);
4357 OSMetaClassDefineReservedUsed(IOService
, 1);
4358 OSMetaClassDefineReservedUsed(IOService
, 2);
4360 OSMetaClassDefineReservedUnused(IOService
, 3);
4361 OSMetaClassDefineReservedUnused(IOService
, 4);
4362 OSMetaClassDefineReservedUnused(IOService
, 5);
4363 OSMetaClassDefineReservedUnused(IOService
, 6);
4364 OSMetaClassDefineReservedUnused(IOService
, 7);
4365 OSMetaClassDefineReservedUnused(IOService
, 8);
4366 OSMetaClassDefineReservedUnused(IOService
, 9);
4367 OSMetaClassDefineReservedUnused(IOService
, 10);
4368 OSMetaClassDefineReservedUnused(IOService
, 11);
4369 OSMetaClassDefineReservedUnused(IOService
, 12);
4370 OSMetaClassDefineReservedUnused(IOService
, 13);
4371 OSMetaClassDefineReservedUnused(IOService
, 14);
4372 OSMetaClassDefineReservedUnused(IOService
, 15);
4373 OSMetaClassDefineReservedUnused(IOService
, 16);
4374 OSMetaClassDefineReservedUnused(IOService
, 17);
4375 OSMetaClassDefineReservedUnused(IOService
, 18);
4376 OSMetaClassDefineReservedUnused(IOService
, 19);
4377 OSMetaClassDefineReservedUnused(IOService
, 20);
4378 OSMetaClassDefineReservedUnused(IOService
, 21);
4379 OSMetaClassDefineReservedUnused(IOService
, 22);
4380 OSMetaClassDefineReservedUnused(IOService
, 23);
4381 OSMetaClassDefineReservedUnused(IOService
, 24);
4382 OSMetaClassDefineReservedUnused(IOService
, 25);
4383 OSMetaClassDefineReservedUnused(IOService
, 26);
4384 OSMetaClassDefineReservedUnused(IOService
, 27);
4385 OSMetaClassDefineReservedUnused(IOService
, 28);
4386 OSMetaClassDefineReservedUnused(IOService
, 29);
4387 OSMetaClassDefineReservedUnused(IOService
, 30);
4388 OSMetaClassDefineReservedUnused(IOService
, 31);
4389 OSMetaClassDefineReservedUnused(IOService
, 32);
4390 OSMetaClassDefineReservedUnused(IOService
, 33);
4391 OSMetaClassDefineReservedUnused(IOService
, 34);
4392 OSMetaClassDefineReservedUnused(IOService
, 35);
4393 OSMetaClassDefineReservedUnused(IOService
, 36);
4394 OSMetaClassDefineReservedUnused(IOService
, 37);
4395 OSMetaClassDefineReservedUnused(IOService
, 38);
4396 OSMetaClassDefineReservedUnused(IOService
, 39);
4397 OSMetaClassDefineReservedUnused(IOService
, 40);
4398 OSMetaClassDefineReservedUnused(IOService
, 41);
4399 OSMetaClassDefineReservedUnused(IOService
, 42);
4400 OSMetaClassDefineReservedUnused(IOService
, 43);
4401 OSMetaClassDefineReservedUnused(IOService
, 44);
4402 OSMetaClassDefineReservedUnused(IOService
, 45);
4403 OSMetaClassDefineReservedUnused(IOService
, 46);
4404 OSMetaClassDefineReservedUnused(IOService
, 47);
4405 OSMetaClassDefineReservedUnused(IOService
, 48);
4406 OSMetaClassDefineReservedUnused(IOService
, 49);
4407 OSMetaClassDefineReservedUnused(IOService
, 50);
4408 OSMetaClassDefineReservedUnused(IOService
, 51);
4409 OSMetaClassDefineReservedUnused(IOService
, 52);
4410 OSMetaClassDefineReservedUnused(IOService
, 53);
4411 OSMetaClassDefineReservedUnused(IOService
, 54);
4412 OSMetaClassDefineReservedUnused(IOService
, 55);
4413 OSMetaClassDefineReservedUnused(IOService
, 56);
4414 OSMetaClassDefineReservedUnused(IOService
, 57);
4415 OSMetaClassDefineReservedUnused(IOService
, 58);
4416 OSMetaClassDefineReservedUnused(IOService
, 59);
4417 OSMetaClassDefineReservedUnused(IOService
, 60);
4418 OSMetaClassDefineReservedUnused(IOService
, 61);
4419 OSMetaClassDefineReservedUnused(IOService
, 62);
4420 OSMetaClassDefineReservedUnused(IOService
, 63);