2 * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
23 #include <IOKit/system.h>
25 #include <IOKit/IOService.h>
26 #include <libkern/c++/OSContainers.h>
27 #include <libkern/c++/OSUnserialize.h>
28 #include <IOKit/IOCatalogue.h>
29 #include <IOKit/IOCommand.h>
30 #include <IOKit/IODeviceMemory.h>
31 #include <IOKit/IOInterrupts.h>
32 #include <IOKit/IOInterruptController.h>
33 #include <IOKit/IOPlatformExpert.h>
34 #include <IOKit/IOMessage.h>
35 #include <IOKit/IOLib.h>
36 #include <IOKit/IOKitKeysPrivate.h>
37 #include <IOKit/IOBSD.h>
38 #include <IOKit/IOUserClient.h>
39 #include <IOKit/IOWorkLoop.h>
40 #include <mach/sync_policy.h>
41 #include <IOKit/assert.h>
42 #include <sys/errno.h>
47 #include "IOServicePrivate.h"
49 // take lockForArbitration before LOCKNOTIFY
51 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
53 #define super IORegistryEntry
55 OSDefineMetaClassAndStructors(IOService
, IORegistryEntry
)
57 OSDefineMetaClassAndStructors(_IOServiceNotifier
, IONotifier
)
59 OSDefineMetaClassAndStructors(_IOServiceInterestNotifier
, IONotifier
)
61 OSDefineMetaClassAndStructors(_IOConfigThread
, OSObject
)
63 OSDefineMetaClassAndStructors(_IOServiceJob
, OSObject
)
65 OSDefineMetaClassAndStructors(IOResources
, IOService
)
67 OSDefineMetaClassAndStructors(_IOOpenServiceIterator
, OSIterator
)
69 OSDefineMetaClassAndAbstractStructors(IONotifier
, OSObject
)
71 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
73 static IOPlatformExpert
* gIOPlatform
;
74 static class IOPMrootDomain
* gIOPMRootDomain
;
75 const IORegistryPlane
* gIOServicePlane
;
76 const IORegistryPlane
* gIOPowerPlane
;
77 const OSSymbol
* gIODeviceMemoryKey
;
78 const OSSymbol
* gIOInterruptControllersKey
;
79 const OSSymbol
* gIOInterruptSpecifiersKey
;
81 const OSSymbol
* gIOResourcesKey
;
82 const OSSymbol
* gIOResourceMatchKey
;
83 const OSSymbol
* gIOProviderClassKey
;
84 const OSSymbol
* gIONameMatchKey
;
85 const OSSymbol
* gIONameMatchedKey
;
86 const OSSymbol
* gIOPropertyMatchKey
;
87 const OSSymbol
* gIOLocationMatchKey
;
88 const OSSymbol
* gIOParentMatchKey
;
89 const OSSymbol
* gIOPathMatchKey
;
90 const OSSymbol
* gIOMatchCategoryKey
;
91 const OSSymbol
* gIODefaultMatchCategoryKey
;
92 const OSSymbol
* gIOMatchedServiceCountKey
;
94 const OSSymbol
* gIOUserClientClassKey
;
95 const OSSymbol
* gIOKitDebugKey
;
97 const OSSymbol
* gIOCommandPoolSizeKey
;
99 const OSSymbol
* gIOConsoleUsersKey
;
100 const OSSymbol
* gIOConsoleSessionUIDKey
;
101 const OSSymbol
* gIOConsoleUsersSeedKey
;
103 static int gIOResourceGenerationCount
;
105 const OSSymbol
* gIOServiceKey
;
106 const OSSymbol
* gIOPublishNotification
;
107 const OSSymbol
* gIOFirstPublishNotification
;
108 const OSSymbol
* gIOMatchedNotification
;
109 const OSSymbol
* gIOFirstMatchNotification
;
110 const OSSymbol
* gIOTerminatedNotification
;
112 const OSSymbol
* gIOGeneralInterest
;
113 const OSSymbol
* gIOBusyInterest
;
114 const OSSymbol
* gIOAppPowerStateInterest
;
115 const OSSymbol
* gIOPriorityPowerStateInterest
;
117 static OSDictionary
* gNotifications
;
118 static IORecursiveLock
* gNotificationLock
;
120 static IOService
* gIOResources
;
121 static IOService
* gIOServiceRoot
;
123 static OSOrderedSet
* gJobs
;
124 static semaphore_port_t gJobsSemaphore
;
125 static IOLock
* gJobsLock
;
126 static int gOutstandingJobs
;
127 static int gNumConfigThreads
;
128 static int gNumWaitingThreads
;
129 static IOLock
* gIOServiceBusyLock
;
131 static thread_t gIOTerminateThread
;
132 static UInt32 gIOTerminateWork
;
133 static OSArray
* gIOTerminatePhase2List
;
134 static OSArray
* gIOStopList
;
135 static OSArray
* gIOStopProviderList
;
136 static OSArray
* gIOFinalizeList
;
138 static SInt32 gIOConsoleUsersSeed
;
139 static OSData
* gIOConsoleUsersSeedValue
;
141 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
143 #define LOCKREADNOTIFY() \
144 IORecursiveLockLock( gNotificationLock )
145 #define LOCKWRITENOTIFY() \
146 IORecursiveLockLock( gNotificationLock )
147 #define LOCKWRITE2READNOTIFY()
148 #define UNLOCKNOTIFY() \
149 IORecursiveLockUnlock( gNotificationLock )
150 #define SLEEPNOTIFY(event) \
151 IORecursiveLockSleep( gNotificationLock, (void *)(event), THREAD_UNINT )
152 #define WAKEUPNOTIFY(event) \
153 IORecursiveLockWakeup( gNotificationLock, (void *)(event), /* wake one */ false )
155 #define randomDelay() \
156 int del = read_processor_clock(); \
157 del = (((int)IOThreadSelf()) ^ del ^ (del >> 10)) & 0x3ff; \
160 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
162 #define queue_element(entry, element, type, field) do { \
163 vm_address_t __ele = (vm_address_t) (entry); \
164 __ele -= -4 + ((size_t)(&((type) 4)->field)); \
165 (element) = (type) __ele; \
168 #define iterqueue(que, elt) \
169 for (queue_entry_t elt = queue_first(que); \
170 !queue_end(que, elt); \
171 elt = queue_next(elt))
173 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
175 struct ArbitrationLockQueueElement
{
184 static queue_head_t gArbitrationLockQueueActive
;
185 static queue_head_t gArbitrationLockQueueWaiting
;
186 static queue_head_t gArbitrationLockQueueFree
;
187 static IOLock
* gArbitrationLockQueueLock
;
189 bool IOService::isInactive( void ) const
190 { return( 0 != (kIOServiceInactiveState
& getState())); }
192 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
194 void IOService::initialize( void )
198 gIOServicePlane
= IORegistryEntry::makePlane( kIOServicePlane
);
199 gIOPowerPlane
= IORegistryEntry::makePlane( kIOPowerPlane
);
201 gIOProviderClassKey
= OSSymbol::withCStringNoCopy( kIOProviderClassKey
);
202 gIONameMatchKey
= OSSymbol::withCStringNoCopy( kIONameMatchKey
);
203 gIONameMatchedKey
= OSSymbol::withCStringNoCopy( kIONameMatchedKey
);
204 gIOPropertyMatchKey
= OSSymbol::withCStringNoCopy( kIOPropertyMatchKey
);
205 gIOPathMatchKey
= OSSymbol::withCStringNoCopy( kIOPathMatchKey
);
206 gIOLocationMatchKey
= OSSymbol::withCStringNoCopy( kIOLocationMatchKey
);
207 gIOParentMatchKey
= OSSymbol::withCStringNoCopy( kIOParentMatchKey
);
209 gIOMatchCategoryKey
= OSSymbol::withCStringNoCopy( kIOMatchCategoryKey
);
210 gIODefaultMatchCategoryKey
= OSSymbol::withCStringNoCopy(
211 kIODefaultMatchCategoryKey
);
212 gIOMatchedServiceCountKey
= OSSymbol::withCStringNoCopy(
213 kIOMatchedServiceCountKey
);
215 gIOUserClientClassKey
= OSSymbol::withCStringNoCopy( kIOUserClientClassKey
);
217 gIOResourcesKey
= OSSymbol::withCStringNoCopy( kIOResourcesClass
);
218 gIOResourceMatchKey
= OSSymbol::withCStringNoCopy( kIOResourceMatchKey
);
220 gIODeviceMemoryKey
= OSSymbol::withCStringNoCopy( "IODeviceMemory" );
221 gIOInterruptControllersKey
222 = OSSymbol::withCStringNoCopy("IOInterruptControllers");
223 gIOInterruptSpecifiersKey
224 = OSSymbol::withCStringNoCopy("IOInterruptSpecifiers");
226 gIOKitDebugKey
= OSSymbol::withCStringNoCopy( kIOKitDebugKey
);
228 gIOCommandPoolSizeKey
= OSSymbol::withCStringNoCopy( kIOCommandPoolSizeKey
);
230 gIOGeneralInterest
= OSSymbol::withCStringNoCopy( kIOGeneralInterest
);
231 gIOBusyInterest
= OSSymbol::withCStringNoCopy( kIOBusyInterest
);
232 gIOAppPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOAppPowerStateInterest
);
233 gIOPriorityPowerStateInterest
= OSSymbol::withCStringNoCopy( kIOPriorityPowerStateInterest
);
235 gNotifications
= OSDictionary::withCapacity( 1 );
236 gIOPublishNotification
= OSSymbol::withCStringNoCopy(
237 kIOPublishNotification
);
238 gIOFirstPublishNotification
= OSSymbol::withCStringNoCopy(
239 kIOFirstPublishNotification
);
240 gIOMatchedNotification
= OSSymbol::withCStringNoCopy(
241 kIOMatchedNotification
);
242 gIOFirstMatchNotification
= OSSymbol::withCStringNoCopy(
243 kIOFirstMatchNotification
);
244 gIOTerminatedNotification
= OSSymbol::withCStringNoCopy(
245 kIOTerminatedNotification
);
246 gIOServiceKey
= OSSymbol::withCStringNoCopy( kIOServiceClass
);
248 gIOConsoleUsersKey
= OSSymbol::withCStringNoCopy( kIOConsoleUsersKey
);
249 gIOConsoleSessionUIDKey
= OSSymbol::withCStringNoCopy( kIOConsoleSessionUIDKey
);
250 gIOConsoleUsersSeedKey
= OSSymbol::withCStringNoCopy( kIOConsoleUsersSeedKey
);
251 gIOConsoleUsersSeedValue
= OSData::withBytesNoCopy(&gIOConsoleUsersSeed
, sizeof(gIOConsoleUsersSeed
));
253 gNotificationLock
= IORecursiveLockAlloc();
255 assert( gIOServicePlane
&& gIODeviceMemoryKey
256 && gIOInterruptControllersKey
&& gIOInterruptSpecifiersKey
257 && gIOResourcesKey
&& gNotifications
&& gNotificationLock
258 && gIOProviderClassKey
&& gIONameMatchKey
&& gIONameMatchedKey
259 && gIOMatchCategoryKey
&& gIODefaultMatchCategoryKey
260 && gIOPublishNotification
&& gIOMatchedNotification
261 && gIOTerminatedNotification
&& gIOServiceKey
262 && gIOConsoleUsersKey
&& gIOConsoleSessionUIDKey
263 && gIOConsoleUsersSeedKey
&& gIOConsoleUsersSeedValue
);
265 gJobsLock
= IOLockAlloc();
266 gJobs
= OSOrderedSet::withCapacity( 10 );
268 gIOServiceBusyLock
= IOLockAlloc();
270 err
= semaphore_create(kernel_task
, &gJobsSemaphore
, SYNC_POLICY_FIFO
, 0);
272 assert( gIOServiceBusyLock
&& gJobs
&& gJobsLock
&& (err
== KERN_SUCCESS
) );
274 gIOResources
= IOResources::resources();
275 assert( gIOResources
);
277 gArbitrationLockQueueLock
= IOLockAlloc();
278 queue_init(&gArbitrationLockQueueActive
);
279 queue_init(&gArbitrationLockQueueWaiting
);
280 queue_init(&gArbitrationLockQueueFree
);
282 assert( gArbitrationLockQueueLock
);
284 gIOTerminatePhase2List
= OSArray::withCapacity( 2 );
285 gIOStopList
= OSArray::withCapacity( 16 );
286 gIOStopProviderList
= OSArray::withCapacity( 16 );
287 gIOFinalizeList
= OSArray::withCapacity( 16 );
288 assert( gIOTerminatePhase2List
&& gIOStopList
&& gIOStopProviderList
&& gIOFinalizeList
);
291 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
294 static UInt64
getDebugFlags( OSDictionary
* props
)
296 OSNumber
* debugProp
;
299 debugProp
= OSDynamicCast( OSNumber
,
300 props
->getObject( gIOKitDebugKey
));
302 debugFlags
= debugProp
->unsigned64BitValue();
304 debugFlags
= gIOKitDebug
;
306 return( debugFlags
);
310 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
312 // Probe a matched service and return an instance to be started.
313 // The default score is from the property table, & may be altered
314 // during probe to change the start order.
316 IOService
* IOService::probe( IOService
* provider
,
322 bool IOService::start( IOService
* provider
)
327 void IOService::stop( IOService
* provider
)
331 void IOService::free( void )
333 if( getPropertyTable())
334 unregisterAllInterest();
340 * Attach in service plane
342 bool IOService::attach( IOService
* provider
)
348 if( gIOKitDebug
& kIOLogAttach
)
349 LOG( "%s::attach(%s)\n", getName(),
350 provider
->getName());
352 provider
->lockForArbitration();
353 if( provider
->__state
[0] & kIOServiceInactiveState
)
356 ok
= attachToParent( provider
, gIOServicePlane
);
357 provider
->unlockForArbitration();
360 gIOServiceRoot
= this;
361 ok
= attachToParent( getRegistryRoot(), gIOServicePlane
);
367 IOService
* IOService::getServiceRoot( void )
369 return( gIOServiceRoot
);
372 void IOService::detach( IOService
* provider
)
374 IOService
* newProvider
= 0;
378 if( gIOKitDebug
& kIOLogAttach
)
379 LOG("%s::detach(%s)\n", getName(), provider
->getName());
381 lockForArbitration();
383 adjParent
= ((busy
= (__state
[1] & kIOServiceBusyStateMask
))
384 && (provider
== getProvider()));
386 detachFromParent( provider
, gIOServicePlane
);
389 newProvider
= getProvider();
390 if( busy
&& (__state
[1] & kIOServiceTermPhase3State
) && (0 == newProvider
))
391 _adjustBusy( -busy
);
394 unlockForArbitration();
397 newProvider
->lockForArbitration();
398 newProvider
->_adjustBusy(1);
399 newProvider
->unlockForArbitration();
402 // check for last client detach from a terminated service
403 if( provider
->lockForArbitration( true )) {
405 provider
->_adjustBusy( -1 );
406 if( (provider
->__state
[1] & kIOServiceTermPhase3State
)
407 && (0 == provider
->getClient())) {
408 provider
->scheduleFinalize();
410 provider
->unlockForArbitration();
415 * Register instance - publish it for matching
418 void IOService::registerService( IOOptionBits options
)
424 enum { kMaxPathLen
= 256 };
425 enum { kMaxChars
= 63 };
427 IORegistryEntry
* parent
= this;
428 IORegistryEntry
* root
= getRegistryRoot();
429 while( parent
&& (parent
!= root
))
430 parent
= parent
->getParentEntry( gIOServicePlane
);
432 if( parent
!= root
) {
433 IOLog("%s: not registry member at registerService()\n", getName());
437 // Allow the Platform Expert to adjust this node.
438 if( gIOPlatform
&& (!gIOPlatform
->platformAdjustService(this)))
441 if( (this != gIOResources
)
442 && (kIOLogRegister
& gIOKitDebug
)) {
444 pathBuf
= (char *) IOMalloc( kMaxPathLen
);
446 IOLog( "Registering: " );
449 if( pathBuf
&& getPath( pathBuf
, &len
, gIOServicePlane
)) {
452 if( len
> kMaxChars
) {
456 if( (skip
= strchr( path
, '/')))
462 IOLog( "%s\n", path
);
465 IOFree( pathBuf
, kMaxPathLen
);
468 startMatching( options
);
471 void IOService::startMatching( IOOptionBits options
)
473 IOService
* provider
;
476 bool needWake
= false;
481 lockForArbitration();
483 sync
= (options
& kIOServiceSynchronous
)
484 || ((provider
= getProvider())
485 && (provider
->__state
[1] & kIOServiceSynchronousState
));
488 needConfig
= (0 == (__state
[1] & (kIOServiceNeedConfigState
| kIOServiceConfigState
)))
489 && (0 == (__state
[0] & kIOServiceInactiveState
));
491 __state
[1] |= kIOServiceNeedConfigState
;
493 // __state[0] &= ~kIOServiceInactiveState;
495 // if( sync) LOG("OSKernelStackRemaining = %08x @ %s\n",
496 // OSKernelStackRemaining(), getName());
499 prevBusy
= _adjustBusy( 1 );
500 needWake
= (0 != (kIOServiceSyncPubState
& __state
[1]));
504 __state
[1] |= kIOServiceSynchronousState
;
506 __state
[1] &= ~kIOServiceSynchronousState
;
508 unlockForArbitration();
513 IOLockLock( gIOServiceBusyLock
);
514 thread_wakeup( (event_t
) this/*&__state[1]*/ );
515 IOLockUnlock( gIOServiceBusyLock
);
517 } else if( !sync
|| (kIOServiceAsynchronous
& options
)) {
519 ok
= (0 != _IOServiceJob::startJob( this, kMatchNubJob
, options
));
523 if( (__state
[1] & kIOServiceNeedConfigState
))
524 doServiceMatch( options
);
526 lockForArbitration();
527 IOLockLock( gIOServiceBusyLock
);
529 waitAgain
= (prevBusy
< (__state
[1] & kIOServiceBusyStateMask
));
531 __state
[1] |= kIOServiceSyncPubState
| kIOServiceBusyWaiterState
;
533 __state
[1] &= ~kIOServiceSyncPubState
;
535 unlockForArbitration();
538 assert_wait( (event_t
) this/*&__state[1]*/, THREAD_UNINT
);
540 IOLockUnlock( gIOServiceBusyLock
);
542 thread_block(THREAD_CONTINUE_NULL
);
544 } while( waitAgain
);
548 IOReturn
IOService::catalogNewDrivers( OSOrderedSet
* newTables
)
550 OSDictionary
* table
;
560 while( (table
= (OSDictionary
*) newTables
->getFirstObject())) {
563 set
= (OSSet
*) getExistingServices( table
,
564 kIOServiceRegisteredState
,
565 kIOServiceExistingSet
);
570 count
+= set
->getCount();
573 allSet
->merge((const OSSet
*) set
);
581 if( getDebugFlags( table
) & kIOLogMatch
)
582 LOG("Matching service count = %ld\n", count
);
584 newTables
->removeObject(table
);
588 while( (service
= (IOService
*) allSet
->getAnyObject())) {
589 service
->startMatching(kIOServiceAsynchronous
);
590 allSet
->removeObject(service
);
595 newTables
->release();
597 return( kIOReturnSuccess
);
600 _IOServiceJob
* _IOServiceJob::startJob( IOService
* nub
, int type
,
601 IOOptionBits options
)
605 job
= new _IOServiceJob
;
606 if( job
&& !job
->init()) {
614 job
->options
= options
;
615 nub
->retain(); // thread will release()
623 * Called on a registered service to see if it matches
627 bool IOService::matchPropertyTable( OSDictionary
* table
, SInt32
* score
)
629 return( matchPropertyTable(table
) );
632 bool IOService::matchPropertyTable( OSDictionary
* table
)
638 * Called on a matched service to allocate resources
639 * before first driver is attached.
642 IOReturn
IOService::getResources( void )
644 return( kIOReturnSuccess
);
648 * Client/provider accessors
651 IOService
* IOService::getProvider( void ) const
653 IOService
* self
= (IOService
*) this;
658 generation
= getGenerationCount();
659 if( __providerGeneration
== generation
)
662 parent
= (IOService
*) getParentEntry( gIOServicePlane
);
663 if( parent
== IORegistryEntry::getRegistryRoot())
664 /* root is not an IOService */
667 self
->__provider
= parent
;
668 // save the count before getParentEntry()
669 self
->__providerGeneration
= generation
;
674 IOWorkLoop
* IOService::getWorkLoop() const
676 IOService
*provider
= getProvider();
679 return provider
->getWorkLoop();
684 OSIterator
* IOService::getProviderIterator( void ) const
686 return( getParentIterator( gIOServicePlane
));
689 IOService
* IOService::getClient( void ) const
691 return( (IOService
*) getChildEntry( gIOServicePlane
));
694 OSIterator
* IOService::getClientIterator( void ) const
696 return( getChildIterator( gIOServicePlane
));
699 OSIterator
* _IOOpenServiceIterator::iterator( OSIterator
* _iter
,
700 const IOService
* client
,
701 const IOService
* provider
)
703 _IOOpenServiceIterator
* inst
;
708 inst
= new _IOOpenServiceIterator
;
710 if( inst
&& !inst
->init()) {
716 inst
->client
= client
;
717 inst
->provider
= provider
;
723 void _IOOpenServiceIterator::free()
727 last
->unlockForArbitration();
731 OSObject
* _IOOpenServiceIterator::getNextObject()
736 last
->unlockForArbitration();
738 while( (next
= (IOService
*) iter
->getNextObject())) {
740 next
->lockForArbitration();
741 if( (client
&& (next
->isOpen( client
)))
742 || (provider
&& (provider
->isOpen( next
))) )
744 next
->unlockForArbitration();
752 bool _IOOpenServiceIterator::isValid()
754 return( iter
->isValid() );
757 void _IOOpenServiceIterator::reset()
760 last
->unlockForArbitration();
766 OSIterator
* IOService::getOpenProviderIterator( void ) const
768 return( _IOOpenServiceIterator::iterator( getProviderIterator(), this, 0 ));
771 OSIterator
* IOService::getOpenClientIterator( void ) const
773 return( _IOOpenServiceIterator::iterator( getClientIterator(), 0, this ));
777 IOReturn
IOService::callPlatformFunction( const OSSymbol
* functionName
,
778 bool waitForFunction
,
779 void *param1
, void *param2
,
780 void *param3
, void *param4
)
782 IOReturn result
= kIOReturnUnsupported
;
783 IOService
*provider
= getProvider();
786 result
= provider
->callPlatformFunction(functionName
, waitForFunction
,
787 param1
, param2
, param3
, param4
);
793 IOReturn
IOService::callPlatformFunction( const char * functionName
,
794 bool waitForFunction
,
795 void *param1
, void *param2
,
796 void *param3
, void *param4
)
798 IOReturn result
= kIOReturnNoMemory
;
799 const OSSymbol
*functionSymbol
= OSSymbol::withCString(functionName
);
801 if (functionSymbol
!= 0) {
802 result
= callPlatformFunction(functionSymbol
, waitForFunction
,
803 param1
, param2
, param3
, param4
);
804 functionSymbol
->release();
812 * Accessors for global services
815 IOPlatformExpert
* IOService::getPlatform( void )
817 return( gIOPlatform
);
820 class IOPMrootDomain
* IOService::getPMRootDomain( void )
822 return( gIOPMRootDomain
);
825 IOService
* IOService::getResourceService( void )
827 return( gIOResources
);
830 void IOService::setPlatform( IOPlatformExpert
* platform
)
832 gIOPlatform
= platform
;
833 gIOResources
->attachToParent( gIOServiceRoot
, gIOServicePlane
);
836 void IOService::setPMRootDomain( class IOPMrootDomain
* rootDomain
)
838 gIOPMRootDomain
= rootDomain
;
839 publishResource("IOKit");
846 bool IOService::lockForArbitration( bool isSuccessRequired
)
850 ArbitrationLockQueueElement
* element
;
851 ArbitrationLockQueueElement
* active
;
852 ArbitrationLockQueueElement
* waiting
;
854 enum { kPutOnFreeQueue
, kPutOnActiveQueue
, kPutOnWaitingQueue
} action
;
856 // lock global access
857 IOTakeLock( gArbitrationLockQueueLock
);
859 // obtain an unused queue element
860 if( !queue_empty( &gArbitrationLockQueueFree
)) {
861 queue_remove_first( &gArbitrationLockQueueFree
,
863 ArbitrationLockQueueElement
*,
866 element
= IONew( ArbitrationLockQueueElement
, 1 );
870 // prepare the queue element
871 element
->thread
= IOThreadSelf();
872 element
->service
= this;
874 element
->required
= isSuccessRequired
;
875 element
->aborted
= false;
877 // determine whether this object is already locked (ie. on active queue)
879 queue_iterate( &gArbitrationLockQueueActive
,
881 ArbitrationLockQueueElement
*,
884 if( active
->service
== element
->service
) {
890 if( found
) { // this object is already locked
892 // determine whether it is the same or a different thread trying to lock
893 if( active
->thread
!= element
->thread
) { // it is a different thread
895 ArbitrationLockQueueElement
* victim
= 0;
897 // before placing this new thread on the waiting queue, we look for
898 // a deadlock cycle...
901 // determine whether the active thread holding the object we
902 // want is waiting for another object to be unlocked
904 queue_iterate( &gArbitrationLockQueueWaiting
,
906 ArbitrationLockQueueElement
*,
909 if( waiting
->thread
== active
->thread
) {
910 assert( false == waiting
->aborted
);
916 if( found
) { // yes, active thread waiting for another object
918 // this may be a candidate for rejection if the required
919 // flag is not set, should we detect a deadlock later on
920 if( false == waiting
->required
)
923 // find the thread that is holding this other object, that
924 // is blocking the active thread from proceeding (fun :-)
926 queue_iterate( &gArbitrationLockQueueActive
,
927 active
, // (reuse active queue element)
928 ArbitrationLockQueueElement
*,
931 if( active
->service
== waiting
->service
) {
937 // someone must be holding it or it wouldn't be waiting
940 if( active
->thread
== element
->thread
) {
942 // doh, it's waiting for the thread that originated
943 // this whole lock (ie. current thread) -> deadlock
944 if( false == element
->required
) { // willing to fail?
946 // the originating thread doesn't have the required
947 // flag, so it can fail
948 success
= false; // (fail originating lock request)
949 break; // (out of while)
951 } else { // originating thread is not willing to fail
953 // see if we came across a waiting thread that did
954 // not have the 'required' flag set: we'll fail it
957 // we do have a willing victim, fail it's lock
958 victim
->aborted
= true;
960 // take the victim off the waiting queue
961 queue_remove( &gArbitrationLockQueueWaiting
,
963 ArbitrationLockQueueElement
*,
967 IOLockWakeup( gArbitrationLockQueueLock
,
969 /* one thread */ true );
971 // allow this thread to proceed (ie. wait)
972 success
= true; // (put request on wait queue)
973 break; // (out of while)
976 // all the waiting threads we came across in
977 // finding this loop had the 'required' flag
978 // set, so we've got a deadlock we can't avoid
979 panic("I/O Kit: Unrecoverable deadlock.");
983 // repeat while loop, redefining active thread to be the
984 // thread holding "this other object" (see above), and
985 // looking for threads waiting on it; note the active
986 // variable points to "this other object" already... so
987 // there nothing to do in this else clause.
989 } else { // no, active thread is not waiting for another object
991 success
= true; // (put request on wait queue)
992 break; // (out of while)
996 if( success
) { // put the request on the waiting queue?
997 kern_return_t wait_result
;
999 // place this thread on the waiting queue and put it to sleep;
1000 // we place it at the tail of the queue...
1001 queue_enter( &gArbitrationLockQueueWaiting
,
1003 ArbitrationLockQueueElement
*,
1006 // declare that this thread will wait for a given event
1007 restart_sleep
: wait_result
= assert_wait( element
,
1008 element
->required
? THREAD_UNINT
1009 : THREAD_INTERRUPTIBLE
);
1011 // unlock global access
1012 IOUnlock( gArbitrationLockQueueLock
);
1014 // put thread to sleep, waiting for our event to fire...
1015 if (wait_result
== THREAD_WAITING
)
1016 wait_result
= thread_block(THREAD_CONTINUE_NULL
);
1019 // ...and we've been woken up; we might be in one of two states:
1020 // (a) we've been aborted and our queue element is not on
1021 // any of the three queues, but is floating around
1022 // (b) we're allowed to proceed with the lock and we have
1023 // already been moved from the waiting queue to the
1025 // ...plus a 3rd state, should the thread have been interrupted:
1026 // (c) we're still on the waiting queue
1028 // determine whether we were interrupted out of our sleep
1029 if( THREAD_INTERRUPTED
== wait_result
) {
1031 // re-lock global access
1032 IOTakeLock( gArbitrationLockQueueLock
);
1034 // determine whether we're still on the waiting queue
1036 queue_iterate( &gArbitrationLockQueueWaiting
,
1037 waiting
, // (reuse waiting queue element)
1038 ArbitrationLockQueueElement
*,
1041 if( waiting
== element
) {
1047 if( found
) { // yes, we're still on the waiting queue
1049 // determine whether we're willing to fail
1050 if( false == element
->required
) {
1052 // mark us as aborted
1053 element
->aborted
= true;
1055 // take us off the waiting queue
1056 queue_remove( &gArbitrationLockQueueWaiting
,
1058 ArbitrationLockQueueElement
*,
1060 } else { // we are not willing to fail
1062 // ignore interruption, go back to sleep
1067 // unlock global access
1068 IOUnlock( gArbitrationLockQueueLock
);
1070 // proceed as though this were a normal wake up
1071 wait_result
= THREAD_AWAKENED
;
1074 assert( THREAD_AWAKENED
== wait_result
);
1076 // determine whether we've been aborted while we were asleep
1077 if( element
->aborted
) {
1078 assert( false == element
->required
);
1080 // re-lock global access
1081 IOTakeLock( gArbitrationLockQueueLock
);
1083 action
= kPutOnFreeQueue
;
1085 } else { // we weren't aborted, so we must be ready to go :-)
1087 // we've already been moved from waiting to active queue
1091 } else { // the lock request is to be failed
1093 // return unused queue element to queue
1094 action
= kPutOnFreeQueue
;
1096 } else { // it is the same thread, recursive access is allowed
1098 // add one level of recursion
1101 // return unused queue element to queue
1102 action
= kPutOnFreeQueue
;
1105 } else { // this object is not already locked, so let this thread through
1106 action
= kPutOnActiveQueue
;
1110 // put the new element on a queue
1111 if( kPutOnActiveQueue
== action
) {
1112 queue_enter( &gArbitrationLockQueueActive
,
1114 ArbitrationLockQueueElement
*,
1116 } else if( kPutOnFreeQueue
== action
) {
1117 queue_enter( &gArbitrationLockQueueFree
,
1119 ArbitrationLockQueueElement
*,
1122 assert( 0 ); // kPutOnWaitingQueue never occurs, handled specially above
1125 // unlock global access
1126 IOUnlock( gArbitrationLockQueueLock
);
1131 void IOService::unlockForArbitration( void )
1134 ArbitrationLockQueueElement
* element
;
1136 // lock global access
1137 IOTakeLock( gArbitrationLockQueueLock
);
1139 // find the lock element for this object (ie. on active queue)
1141 queue_iterate( &gArbitrationLockQueueActive
,
1143 ArbitrationLockQueueElement
*,
1146 if( element
->service
== this ) {
1154 // determine whether the lock has been taken recursively
1155 if( element
->count
> 1 ) {
1156 // undo one level of recursion
1161 // remove it from the active queue
1162 queue_remove( &gArbitrationLockQueueActive
,
1164 ArbitrationLockQueueElement
*,
1167 // put it on the free queue
1168 queue_enter( &gArbitrationLockQueueFree
,
1170 ArbitrationLockQueueElement
*,
1173 // determine whether a thread is waiting for object (head to tail scan)
1175 queue_iterate( &gArbitrationLockQueueWaiting
,
1177 ArbitrationLockQueueElement
*,
1180 if( element
->service
== this ) {
1186 if ( found
) { // we found an interested thread on waiting queue
1188 // remove it from the waiting queue
1189 queue_remove( &gArbitrationLockQueueWaiting
,
1191 ArbitrationLockQueueElement
*,
1194 // put it on the active queue
1195 queue_enter( &gArbitrationLockQueueActive
,
1197 ArbitrationLockQueueElement
*,
1200 // wake the waiting thread
1201 IOLockWakeup( gArbitrationLockQueueLock
,
1203 /* one thread */ true );
1207 // unlock global access
1208 IOUnlock( gArbitrationLockQueueLock
);
1211 void IOService::applyToProviders( IOServiceApplierFunction applier
,
1214 applyToParents( (IORegistryEntryApplierFunction
) applier
,
1215 context
, gIOServicePlane
);
1218 void IOService::applyToClients( IOServiceApplierFunction applier
,
1221 applyToChildren( (IORegistryEntryApplierFunction
) applier
,
1222 context
, gIOServicePlane
);
1231 // send a message to a client or interested party of this service
1232 IOReturn
IOService::messageClient( UInt32 type
, OSObject
* client
,
1233 void * argument
, vm_size_t argSize
)
1236 IOService
* service
;
1237 _IOServiceInterestNotifier
* notify
;
1239 if( (service
= OSDynamicCast( IOService
, client
)))
1240 ret
= service
->message( type
, this, argument
);
1242 else if( (notify
= OSDynamicCast( _IOServiceInterestNotifier
, client
))) {
1244 _IOServiceNotifierInvocation invocation
;
1247 invocation
.thread
= current_thread();
1250 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
1253 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
1254 _IOServiceNotifierInvocation
*, link
);
1260 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
,
1261 type
, this, argument
, argSize
);
1264 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
1265 _IOServiceNotifierInvocation
*, link
);
1266 if( kIOServiceNotifyWaiter
& notify
->state
) {
1267 notify
->state
&= ~kIOServiceNotifyWaiter
;
1268 WAKEUPNOTIFY( notify
);
1273 ret
= kIOReturnSuccess
;
1276 ret
= kIOReturnBadArgument
;
1281 void IOService::applyToInterested( const OSSymbol
* typeOfInterest
,
1282 OSObjectApplierFunction applier
,
1285 OSArray
* copyArray
= 0;
1287 applyToClients( (IOServiceApplierFunction
) applier
, context
);
1291 IOCommand
*notifyList
=
1292 OSDynamicCast( IOCommand
, getProperty( typeOfInterest
));
1295 copyArray
= OSArray::withCapacity(1);
1297 // iterate over queue, entry is set to each element in the list
1298 iterqueue(¬ifyList
->fCommandChain
, entry
) {
1299 _IOServiceInterestNotifier
* notify
;
1301 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1302 copyArray
->setObject(notify
);
1311 for( index
= 0; (next
= copyArray
->getObject( index
)); index
++)
1312 (*applier
)(next
, context
);
1313 copyArray
->release();
1317 struct MessageClientsContext
{
1318 IOService
* service
;
1325 static void messageClientsApplier( OSObject
* object
, void * ctx
)
1328 MessageClientsContext
* context
= (MessageClientsContext
*) ctx
;
1330 ret
= context
->service
->messageClient( context
->type
,
1331 object
, context
->argument
, context
->argSize
);
1332 if( kIOReturnSuccess
!= ret
)
1336 // send a message to all clients
1337 IOReturn
IOService::messageClients( UInt32 type
,
1338 void * argument
, vm_size_t argSize
)
1340 MessageClientsContext context
;
1342 context
.service
= this;
1343 context
.type
= type
;
1344 context
.argument
= argument
;
1345 context
.argSize
= argSize
;
1346 context
.ret
= kIOReturnSuccess
;
1348 applyToInterested( gIOGeneralInterest
,
1349 &messageClientsApplier
, &context
);
1351 return( context
.ret
);
1354 IOReturn
IOService::acknowledgeNotification( IONotificationRef notification
,
1355 IOOptionBits response
)
1357 return( kIOReturnUnsupported
);
1360 IONotifier
* IOService::registerInterest( const OSSymbol
* typeOfInterest
,
1361 IOServiceInterestHandler handler
, void * target
, void * ref
)
1363 _IOServiceInterestNotifier
* notify
= 0;
1365 if( (typeOfInterest
!= gIOGeneralInterest
)
1366 && (typeOfInterest
!= gIOBusyInterest
)
1367 && (typeOfInterest
!= gIOAppPowerStateInterest
)
1368 && (typeOfInterest
!= gIOPriorityPowerStateInterest
))
1371 lockForArbitration();
1372 if( 0 == (__state
[0] & kIOServiceInactiveState
)) {
1374 notify
= new _IOServiceInterestNotifier
;
1375 if( notify
&& !notify
->init()) {
1381 notify
->handler
= handler
;
1382 notify
->target
= target
;
1384 notify
->state
= kIOServiceNotifyEnable
;
1385 queue_init( ¬ify
->handlerInvocations
);
1391 // Get the head of the notifier linked list
1392 IOCommand
*notifyList
= (IOCommand
*) getProperty( typeOfInterest
);
1393 if (!notifyList
|| !OSDynamicCast(IOCommand
, notifyList
)) {
1394 notifyList
= OSTypeAlloc(IOCommand
);
1397 setProperty( typeOfInterest
, notifyList
);
1398 notifyList
->release();
1403 enqueue(¬ifyList
->fCommandChain
, ¬ify
->chain
);
1404 notify
->retain(); // ref'ed while in list
1410 unlockForArbitration();
1415 static void cleanInterestList( OSObject
* head
)
1417 IOCommand
*notifyHead
= OSDynamicCast(IOCommand
, head
);
1422 while ( queue_entry_t entry
= dequeue(¬ifyHead
->fCommandChain
) ) {
1423 queue_next(entry
) = queue_prev(entry
) = 0;
1425 _IOServiceInterestNotifier
* notify
;
1427 queue_element(entry
, notify
, _IOServiceInterestNotifier
*, chain
);
1433 void IOService::unregisterAllInterest( void )
1435 cleanInterestList( getProperty( gIOGeneralInterest
));
1436 cleanInterestList( getProperty( gIOBusyInterest
));
1437 cleanInterestList( getProperty( gIOAppPowerStateInterest
));
1438 cleanInterestList( getProperty( gIOPriorityPowerStateInterest
));
1442 * _IOServiceInterestNotifier
1445 // wait for all threads, other than the current one,
1446 // to exit the handler
1448 void _IOServiceInterestNotifier::wait()
1450 _IOServiceNotifierInvocation
* next
;
1455 queue_iterate( &handlerInvocations
, next
,
1456 _IOServiceNotifierInvocation
*, link
) {
1457 if( next
->thread
!= current_thread() ) {
1463 state
|= kIOServiceNotifyWaiter
;
1470 void _IOServiceInterestNotifier::free()
1472 assert( queue_empty( &handlerInvocations
));
1476 void _IOServiceInterestNotifier::remove()
1480 if( queue_next( &chain
)) {
1481 remqueue( 0, &chain
);
1482 queue_next( &chain
) = queue_prev( &chain
) = 0;
1486 state
&= ~kIOServiceNotifyEnable
;
1495 bool _IOServiceInterestNotifier::disable()
1501 ret
= (0 != (kIOServiceNotifyEnable
& state
));
1502 state
&= ~kIOServiceNotifyEnable
;
1511 void _IOServiceInterestNotifier::enable( bool was
)
1515 state
|= kIOServiceNotifyEnable
;
1517 state
&= ~kIOServiceNotifyEnable
;
1521 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1527 #define tailQ(o) setObject(o)
1528 #define headQ(o) setObject(0, o)
1529 #define TLOG(fmt, args...) { if(kIOLogYield & gIOKitDebug) IOLog(fmt, ## args); }
1531 inline void _workLoopAction( IOWorkLoop::Action action
,
1532 IOService
* service
,
1533 void * p0
= 0, void * p1
= 0,
1534 void * p2
= 0, void * p3
= 0 )
1538 if( (wl
= service
->getWorkLoop())) {
1540 wl
->runAction( action
, service
, p0
, p1
, p2
, p3
);
1543 (*action
)( service
, p0
, p1
, p2
, p3
);
1546 bool IOService::requestTerminate( IOService
* provider
, IOOptionBits options
)
1550 // if its our only provider
1551 ok
= isParent( provider
, gIOServicePlane
, true);
1555 provider
->terminateClient( this, options
| kIOServiceRecursing
);
1556 ok
= (0 != (__state
[1] & kIOServiceRecursing
));
1563 bool IOService::terminatePhase1( IOOptionBits options
)
1568 OSArray
* makeInactive
;
1571 bool startPhase2
= false;
1573 TLOG("%s::terminatePhase1(%08lx)\n", getName(), options
);
1576 if( options
& kIOServiceRecursing
) {
1577 __state
[1] |= kIOServiceRecursing
;
1582 makeInactive
= OSArray::withCapacity( 16 );
1591 didInactive
= victim
->lockForArbitration( true );
1593 didInactive
= (0 == (victim
->__state
[0] & kIOServiceInactiveState
));
1595 victim
->__state
[0] |= kIOServiceInactiveState
;
1596 victim
->__state
[0] &= ~(kIOServiceRegisteredState
| kIOServiceMatchedState
1597 | kIOServiceFirstPublishState
| kIOServiceFirstMatchState
);
1598 victim
->_adjustBusy( 1 );
1600 victim
->unlockForArbitration();
1603 startPhase2
= didInactive
;
1606 victim
->deliverNotification( gIOTerminatedNotification
, 0, 0xffffffff );
1607 IOUserClient::destroyUserReferences( victim
);
1609 iter
= victim
->getClientIterator();
1611 while( (client
= (IOService
*) iter
->getNextObject())) {
1612 TLOG("%s::requestTerminate(%s, %08lx)\n",
1613 client
->getName(), victim
->getName(), options
);
1614 ok
= client
->requestTerminate( victim
, options
);
1615 TLOG("%s::requestTerminate(%s, ok = %d)\n",
1616 client
->getName(), victim
->getName(), ok
);
1618 makeInactive
->setObject( client
);
1624 victim
= (IOService
*) makeInactive
->getObject(0);
1627 makeInactive
->removeObject(0);
1631 makeInactive
->release();
1634 scheduleTerminatePhase2( options
);
1639 void IOService::scheduleTerminatePhase2( IOOptionBits options
)
1641 AbsoluteTime deadline
;
1642 int waitResult
= THREAD_AWAKENED
;
1643 bool wait
, haveDeadline
= false;
1645 options
|= kIOServiceRequired
;
1649 IOLockLock( gJobsLock
);
1651 if( (options
& kIOServiceSynchronous
)
1652 && (current_thread() != gIOTerminateThread
)) {
1655 wait
= (gIOTerminateThread
!= 0);
1657 // wait to become the terminate thread
1658 IOLockSleep( gJobsLock
, &gIOTerminateThread
, THREAD_UNINT
);
1662 gIOTerminateThread
= current_thread();
1663 gIOTerminatePhase2List
->setObject( this );
1667 while( gIOTerminateWork
)
1668 terminateWorker( options
);
1669 wait
= (0 != (__state
[1] & kIOServiceBusyStateMask
));
1671 // wait for the victim to go non-busy
1672 if( !haveDeadline
) {
1673 clock_interval_to_deadline( 15, kSecondScale
, &deadline
);
1674 haveDeadline
= true;
1676 waitResult
= IOLockSleepDeadline( gJobsLock
, &gIOTerminateWork
,
1677 deadline
, THREAD_UNINT
);
1678 if( waitResult
== THREAD_TIMED_OUT
) {
1679 TLOG("%s::terminate(kIOServiceSynchronous) timeout", getName());
1682 } while(gIOTerminateWork
|| (wait
&& (waitResult
!= THREAD_TIMED_OUT
)));
1684 gIOTerminateThread
= 0;
1685 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1688 // ! kIOServiceSynchronous
1690 gIOTerminatePhase2List
->setObject( this );
1691 if( 0 == gIOTerminateWork
++) {
1692 if( !gIOTerminateThread
)
1693 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) options
);
1695 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1699 IOLockUnlock( gJobsLock
);
1704 void IOService::terminateThread( void * arg
)
1706 IOLockLock( gJobsLock
);
1708 while (gIOTerminateWork
)
1709 terminateWorker( (IOOptionBits
) arg
);
1711 gIOTerminateThread
= 0;
1712 IOLockWakeup( gJobsLock
, (event_t
) &gIOTerminateThread
, /* one-thread */ false);
1714 IOLockUnlock( gJobsLock
);
1717 void IOService::scheduleStop( IOService
* provider
)
1719 TLOG("%s::scheduleStop(%s)\n", getName(), provider
->getName());
1721 IOLockLock( gJobsLock
);
1722 gIOStopList
->tailQ( this );
1723 gIOStopProviderList
->tailQ( provider
);
1725 if( 0 == gIOTerminateWork
++) {
1726 if( !gIOTerminateThread
)
1727 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) 0 );
1729 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1732 IOLockUnlock( gJobsLock
);
1735 void IOService::scheduleFinalize( void )
1737 TLOG("%s::scheduleFinalize\n", getName());
1739 IOLockLock( gJobsLock
);
1740 gIOFinalizeList
->tailQ( this );
1742 if( 0 == gIOTerminateWork
++) {
1743 if( !gIOTerminateThread
)
1744 gIOTerminateThread
= IOCreateThread( &terminateThread
, (void *) 0 );
1746 IOLockWakeup(gJobsLock
, (event_t
) &gIOTerminateWork
, /* one-thread */ false );
1749 IOLockUnlock( gJobsLock
);
1752 bool IOService::willTerminate( IOService
* provider
, IOOptionBits options
)
1757 bool IOService::didTerminate( IOService
* provider
, IOOptionBits options
, bool * defer
)
1759 if( false == *defer
) {
1761 if( lockForArbitration( true )) {
1762 if( false == provider
->handleIsOpen( this ))
1763 scheduleStop( provider
);
1766 message( kIOMessageServiceIsRequestingClose
, provider
, (void *) options
);
1767 if( false == provider
->handleIsOpen( this ))
1768 scheduleStop( provider
);
1771 unlockForArbitration();
1778 void IOService::actionWillTerminate( IOService
* victim
, IOOptionBits options
,
1779 OSArray
* doPhase2List
)
1785 iter
= victim
->getClientIterator();
1787 while( (client
= (IOService
*) iter
->getNextObject())) {
1788 TLOG("%s::willTerminate(%s, %08lx)\n",
1789 client
->getName(), victim
->getName(), options
);
1790 ok
= client
->willTerminate( victim
, options
);
1791 doPhase2List
->tailQ( client
);
1797 void IOService::actionDidTerminate( IOService
* victim
, IOOptionBits options
)
1803 victim
->messageClients( kIOMessageServiceIsTerminated
, (void *) options
);
1805 iter
= victim
->getClientIterator();
1807 while( (client
= (IOService
*) iter
->getNextObject())) {
1808 TLOG("%s::didTerminate(%s, %08lx)\n",
1809 client
->getName(), victim
->getName(), options
);
1810 client
->didTerminate( victim
, options
, &defer
);
1811 TLOG("%s::didTerminate(%s, defer %d)\n",
1812 client
->getName(), victim
->getName(), defer
);
1818 void IOService::actionFinalize( IOService
* victim
, IOOptionBits options
)
1820 TLOG("%s::finalize(%08lx)\n", victim
->getName(), options
);
1821 victim
->finalize( options
);
1824 void IOService::actionStop( IOService
* provider
, IOService
* client
)
1826 TLOG("%s::stop(%s)\n", client
->getName(), provider
->getName());
1827 client
->stop( provider
);
1828 if( provider
->isOpen( client
))
1829 provider
->close( client
);
1830 TLOG("%s::detach(%s)\n", client
->getName(), provider
->getName());
1831 client
->detach( provider
);
1834 void IOService::terminateWorker( IOOptionBits options
)
1836 OSArray
* doPhase2List
;
1837 OSArray
* didPhase2List
;
1842 IOService
* provider
;
1848 options
|= kIOServiceRequired
;
1850 doPhase2List
= OSArray::withCapacity( 16 );
1851 didPhase2List
= OSArray::withCapacity( 16 );
1852 freeList
= OSSet::withCapacity( 16 );
1853 if( (0 == doPhase2List
) || (0 == didPhase2List
) || (0 == freeList
))
1857 workDone
= gIOTerminateWork
;
1859 while( (victim
= (IOService
*) gIOTerminatePhase2List
->getObject(0) )) {
1862 gIOTerminatePhase2List
->removeObject(0);
1863 IOLockUnlock( gJobsLock
);
1867 doPhase2
= victim
->lockForArbitration( true );
1869 doPhase2
= (0 != (kIOServiceInactiveState
& victim
->__state
[0]));
1871 doPhase2
= (0 == (victim
->__state
[1] & kIOServiceTermPhase2State
))
1872 && (0 == (victim
->__state
[1] & kIOServiceConfigState
));
1874 victim
->__state
[1] |= kIOServiceTermPhase2State
;
1876 victim
->unlockForArbitration();
1879 if( 0 == victim
->getClient()) {
1880 // no clients - will go to finalize
1881 IOLockLock( gJobsLock
);
1882 gIOFinalizeList
->tailQ( victim
);
1883 IOLockUnlock( gJobsLock
);
1885 _workLoopAction( (IOWorkLoop::Action
) &actionWillTerminate
,
1886 victim
, (void *) options
, (void *) doPhase2List
);
1888 didPhase2List
->headQ( victim
);
1891 victim
= (IOService
*) doPhase2List
->getObject(0);
1894 doPhase2List
->removeObject(0);
1898 while( (victim
= (IOService
*) didPhase2List
->getObject(0)) ) {
1900 if( victim
->lockForArbitration( true )) {
1901 victim
->__state
[1] |= kIOServiceTermPhase3State
;
1902 victim
->unlockForArbitration();
1904 _workLoopAction( (IOWorkLoop::Action
) &actionDidTerminate
,
1905 victim
, (void *) options
);
1906 didPhase2List
->removeObject(0);
1908 IOLockLock( gJobsLock
);
1915 while( (victim
= (IOService
*) gIOFinalizeList
->getObject(0))) {
1917 IOLockUnlock( gJobsLock
);
1918 _workLoopAction( (IOWorkLoop::Action
) &actionFinalize
,
1919 victim
, (void *) options
);
1920 IOLockLock( gJobsLock
);
1922 freeList
->setObject( victim
);
1923 // safe if finalize list is append only
1924 gIOFinalizeList
->removeObject(0);
1928 (!doPhase3
) && (client
= (IOService
*) gIOStopList
->getObject(idx
)); ) {
1930 provider
= (IOService
*) gIOStopProviderList
->getObject(idx
);
1933 if( !provider
->isChild( client
, gIOServicePlane
)) {
1934 // may be multiply queued - nop it
1935 TLOG("%s::nop stop(%s)\n", client
->getName(), provider
->getName());
1937 // not ready for stop if it has clients, skip it
1938 if( (client
->__state
[1] & kIOServiceTermPhase3State
) && client
->getClient()) {
1939 TLOG("%s::defer stop(%s)\n", client
->getName(), provider
->getName());
1944 IOLockUnlock( gJobsLock
);
1945 _workLoopAction( (IOWorkLoop::Action
) &actionStop
,
1946 provider
, (void *) client
);
1947 IOLockLock( gJobsLock
);
1948 // check the finalize list now
1952 freeList
->setObject( client
);
1953 freeList
->setObject( provider
);
1955 // safe if stop list is append only
1956 gIOStopList
->removeObject( idx
);
1957 gIOStopProviderList
->removeObject( idx
);
1961 } while( doPhase3
);
1963 gIOTerminateWork
-= workDone
;
1964 moreToDo
= (gIOTerminateWork
!= 0);
1967 TLOG("iokit terminate done, %d stops remain\n", gIOStopList
->getCount());
1970 } while( moreToDo
);
1972 IOLockUnlock( gJobsLock
);
1974 freeList
->release();
1975 doPhase2List
->release();
1976 didPhase2List
->release();
1978 IOLockLock( gJobsLock
);
1981 bool IOService::finalize( IOOptionBits options
)
1984 IOService
* provider
;
1986 iter
= getProviderIterator();
1990 while( (provider
= (IOService
*) iter
->getNextObject())) {
1993 if( 0 == (__state
[1] & kIOServiceTermPhase3State
)) {
1994 /* we come down here on programmatic terminate */
1996 if( provider
->isOpen( this ))
1997 provider
->close( this );
2001 if( provider
->lockForArbitration( true )) {
2002 if( 0 == (provider
->__state
[1] & kIOServiceTermPhase3State
))
2003 scheduleStop( provider
);
2004 provider
->unlockForArbitration();
2021 void IOService::doServiceTerminate( IOOptionBits options
)
2025 // a method in case someone needs to override it
2026 bool IOService::terminateClient( IOService
* client
, IOOptionBits options
)
2030 if( client
->isParent( this, gIOServicePlane
, true))
2031 // we are the clients only provider
2032 ok
= client
->terminate( options
);
2039 bool IOService::terminate( IOOptionBits options
)
2041 options
|= kIOServiceTerminate
;
2043 return( terminatePhase1( options
));
2046 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2052 struct ServiceOpenMessageContext
2054 IOService
* service
;
2056 IOService
* excludeClient
;
2057 IOOptionBits options
;
2060 static void serviceOpenMessageApplier( OSObject
* object
, void * ctx
)
2062 ServiceOpenMessageContext
* context
= (ServiceOpenMessageContext
*) ctx
;
2064 if( object
!= context
->excludeClient
)
2065 context
->service
->messageClient( context
->type
, object
, (void *) context
->options
);
2068 bool IOService::open( IOService
* forClient
,
2069 IOOptionBits options
,
2073 ServiceOpenMessageContext context
;
2075 context
.service
= this;
2076 context
.type
= kIOMessageServiceIsAttemptingOpen
;
2077 context
.excludeClient
= forClient
;
2078 context
.options
= options
;
2080 applyToInterested( gIOGeneralInterest
,
2081 &serviceOpenMessageApplier
, &context
);
2083 if( false == lockForArbitration(false) )
2086 ok
= (0 == (__state
[0] & kIOServiceInactiveState
));
2088 ok
= handleOpen( forClient
, options
, arg
);
2090 unlockForArbitration();
2095 void IOService::close( IOService
* forClient
,
2096 IOOptionBits options
)
2101 lockForArbitration();
2103 wasClosed
= handleIsOpen( forClient
);
2105 handleClose( forClient
, options
);
2106 last
= (__state
[1] & kIOServiceTermPhase3State
);
2109 unlockForArbitration();
2112 forClient
->scheduleStop( this );
2114 else if( wasClosed
) {
2116 ServiceOpenMessageContext context
;
2118 context
.service
= this;
2119 context
.type
= kIOMessageServiceWasClosed
;
2120 context
.excludeClient
= forClient
;
2121 context
.options
= options
;
2123 applyToInterested( gIOGeneralInterest
,
2124 &serviceOpenMessageApplier
, &context
);
2128 bool IOService::isOpen( const IOService
* forClient
) const
2130 IOService
* self
= (IOService
*) this;
2133 self
->lockForArbitration();
2135 ok
= handleIsOpen( forClient
);
2137 self
->unlockForArbitration();
2142 bool IOService::handleOpen( IOService
* forClient
,
2143 IOOptionBits options
,
2148 ok
= (0 == __owner
);
2150 __owner
= forClient
;
2152 else if( options
& kIOServiceSeize
) {
2153 ok
= (kIOReturnSuccess
== messageClient( kIOMessageServiceIsRequestingClose
,
2154 __owner
, (void *) options
));
2155 if( ok
&& (0 == __owner
))
2156 __owner
= forClient
;
2163 void IOService::handleClose( IOService
* forClient
,
2164 IOOptionBits options
)
2166 if( __owner
== forClient
)
2170 bool IOService::handleIsOpen( const IOService
* forClient
) const
2173 return( __owner
== forClient
);
2175 return( __owner
!= forClient
);
2179 * Probing & starting
2181 static SInt32
IONotifyOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2183 const _IOServiceNotifier
* obj1
= (const _IOServiceNotifier
*) inObj1
;
2184 const _IOServiceNotifier
* obj2
= (const _IOServiceNotifier
*) inObj2
;
2192 val1
= obj1
->priority
;
2195 val2
= obj2
->priority
;
2197 return ( val1
- val2
);
2200 static SInt32
IOServiceObjectOrder( const OSObject
* entry
, void * ref
)
2202 OSDictionary
* dict
;
2203 IOService
* service
;
2204 _IOServiceNotifier
* notify
;
2205 OSSymbol
* key
= (OSSymbol
*) ref
;
2208 if( (notify
= OSDynamicCast( _IOServiceNotifier
, entry
)))
2209 return( notify
->priority
);
2211 else if( (service
= OSDynamicCast( IOService
, entry
)))
2212 offset
= OSDynamicCast(OSNumber
, service
->getProperty( key
));
2213 else if( (dict
= OSDynamicCast( OSDictionary
, entry
)))
2214 offset
= OSDynamicCast(OSNumber
, dict
->getObject( key
));
2221 return( (SInt32
) offset
->unsigned32BitValue());
2223 return( kIODefaultProbeScore
);
2226 SInt32
IOServiceOrdering( const OSMetaClassBase
* inObj1
, const OSMetaClassBase
* inObj2
, void * ref
)
2228 const OSObject
* obj1
= (const OSObject
*) inObj1
;
2229 const OSObject
* obj2
= (const OSObject
*) inObj2
;
2237 val1
= IOServiceObjectOrder( obj1
, ref
);
2240 val2
= IOServiceObjectOrder( obj2
, ref
);
2242 return ( val1
- val2
);
2245 IOService
* IOService::getClientWithCategory( const OSSymbol
* category
)
2247 IOService
* service
= 0;
2249 const OSSymbol
* nextCat
;
2251 iter
= getClientIterator();
2253 while( (service
= (IOService
*) iter
->getNextObject())) {
2254 if( kIOServiceInactiveState
& service
->__state
[0])
2256 nextCat
= (const OSSymbol
*) OSDynamicCast( OSSymbol
,
2257 service
->getProperty( gIOMatchCategoryKey
));
2258 if( category
== nextCat
)
2266 bool IOService::invokeNotifer( _IOServiceNotifier
* notify
)
2268 _IOServiceNotifierInvocation invocation
;
2272 invocation
.thread
= current_thread();
2275 willNotify
= (0 != (kIOServiceNotifyEnable
& notify
->state
));
2278 queue_enter( ¬ify
->handlerInvocations
, &invocation
,
2279 _IOServiceNotifierInvocation
*, link
);
2285 ret
= (*notify
->handler
)( notify
->target
, notify
->ref
, this );
2288 queue_remove( ¬ify
->handlerInvocations
, &invocation
,
2289 _IOServiceNotifierInvocation
*, link
);
2290 if( kIOServiceNotifyWaiter
& notify
->state
) {
2291 notify
->state
&= ~kIOServiceNotifyWaiter
;
2292 WAKEUPNOTIFY( notify
);
2301 * Alloc and probe matching classes,
2302 * called on the provider instance
2305 void IOService::probeCandidates( OSOrderedSet
* matches
)
2307 OSDictionary
* match
= 0;
2310 IOService
* newInst
;
2311 OSDictionary
* props
;
2314 OSOrderedSet
* familyMatches
= 0;
2315 OSOrderedSet
* startList
;
2316 OSDictionary
* startDict
= 0;
2317 const OSSymbol
* category
;
2319 _IOServiceNotifier
* notify
;
2320 OSObject
* nextMatch
= 0;
2322 bool needReloc
= false;
2328 while( !needReloc
&& (nextMatch
= matches
->getFirstObject())) {
2330 nextMatch
->retain();
2331 matches
->removeObject(nextMatch
);
2333 if( (notify
= OSDynamicCast( _IOServiceNotifier
, nextMatch
))) {
2335 lockForArbitration();
2336 if( 0 == (__state
[0] & kIOServiceInactiveState
))
2337 invokeNotifer( notify
);
2338 unlockForArbitration();
2339 nextMatch
->release();
2343 } else if( !(match
= OSDynamicCast( OSDictionary
, nextMatch
))) {
2344 nextMatch
->release();
2351 debugFlags
= getDebugFlags( match
);
2355 category
= OSDynamicCast( OSSymbol
,
2356 match
->getObject( gIOMatchCategoryKey
));
2358 category
= gIODefaultMatchCategoryKey
;
2360 if( getClientWithCategory( category
)) {
2362 if( debugFlags
& kIOLogMatch
)
2363 LOG("%s: match category %s exists\n", getName(),
2364 category
->getCStringNoCopy());
2366 nextMatch
->release();
2371 // create a copy now in case its modified during matching
2372 props
= OSDictionary::withDictionary( match
, match
->getCount());
2375 props
->setCapacityIncrement(1);
2377 // check the nub matches
2378 if( false == passiveMatch( props
, true ))
2381 // Check to see if driver reloc has been loaded.
2382 needReloc
= (false == gIOCatalogue
->isModuleLoaded( match
));
2385 if( debugFlags
& kIOLogCatalogue
)
2386 LOG("%s: stalling for module\n", getName());
2388 // If reloc hasn't been loaded, exit;
2389 // reprobing will occur after reloc has been loaded.
2393 // reorder on family matchPropertyTable score.
2394 if( 0 == familyMatches
)
2395 familyMatches
= OSOrderedSet::withCapacity( 1,
2396 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2398 familyMatches
->setObject( props
);
2403 nextMatch
->release();
2412 if( familyMatches
) {
2415 && (props
= (OSDictionary
*) familyMatches
->getFirstObject())) {
2418 familyMatches
->removeObject( props
);
2423 debugFlags
= getDebugFlags( props
);
2426 symbol
= OSDynamicCast( OSSymbol
,
2427 props
->getObject( gIOClassKey
));
2431 // alloc the driver instance
2432 inst
= (IOService
*) OSMetaClass::allocClassWithName( symbol
);
2435 IOLog("Couldn't alloc class \"%s\"\n",
2436 symbol
->getCStringNoCopy());
2440 // init driver instance
2441 if( !(inst
->init( props
))) {
2443 if( debugFlags
& kIOLogStart
)
2444 IOLog("%s::init fails\n", symbol
->getCStringNoCopy());
2448 if( __state
[1] & kIOServiceSynchronousState
)
2449 inst
->__state
[1] |= kIOServiceSynchronousState
;
2451 // give the driver the default match category if not specified
2452 category
= OSDynamicCast( OSSymbol
,
2453 props
->getObject( gIOMatchCategoryKey
));
2455 category
= gIODefaultMatchCategoryKey
;
2456 inst
->setProperty( gIOMatchCategoryKey
, (OSObject
*) category
);
2458 // attach driver instance
2459 if( !(inst
->attach( this )))
2462 // pass in score from property table
2463 score
= familyMatches
->orderObject( props
);
2465 // & probe the new driver instance
2467 if( debugFlags
& kIOLogProbe
)
2468 LOG("%s::probe(%s)\n",
2469 inst
->getMetaClass()->getClassName(), getName());
2472 newInst
= inst
->probe( this, &score
);
2473 inst
->detach( this );
2476 if( debugFlags
& kIOLogProbe
)
2477 IOLog("%s::probe fails\n", symbol
->getCStringNoCopy());
2483 newPri
= OSNumber::withNumber( score
, 32 );
2485 newInst
->setProperty( gIOProbeScoreKey
, newPri
);
2489 // add to start list for the match category
2491 startDict
= OSDictionary::withCapacity( 1 );
2492 assert( startDict
);
2493 startList
= (OSOrderedSet
*)
2494 startDict
->getObject( category
);
2495 if( 0 == startList
) {
2496 startList
= OSOrderedSet::withCapacity( 1,
2497 IOServiceOrdering
, (void *) gIOProbeScoreKey
);
2498 if( startDict
&& startList
) {
2499 startDict
->setObject( category
, startList
);
2500 startList
->release();
2503 assert( startList
);
2505 startList
->setObject( newInst
);
2513 familyMatches
->release();
2517 // start the best (until success) of each category
2519 iter
= OSCollectionIterator::withCollection( startDict
);
2521 while( (category
= (const OSSymbol
*) iter
->getNextObject())) {
2523 startList
= (OSOrderedSet
*) startDict
->getObject( category
);
2524 assert( startList
);
2529 while( true // (!started)
2530 && (inst
= (IOService
*)startList
->getFirstObject())) {
2533 startList
->removeObject(inst
);
2536 debugFlags
= getDebugFlags( inst
->getPropertyTable() );
2538 if( debugFlags
& kIOLogStart
) {
2540 LOG( "match category exists, skipping " );
2541 LOG( "%s::start(%s) <%d>\n", inst
->getName(),
2542 getName(), inst
->getRetainCount());
2545 if( false == started
)
2546 started
= startCandidate( inst
);
2548 if( (debugFlags
& kIOLogStart
) && (false == started
))
2549 LOG( "%s::start(%s) <%d> failed\n", inst
->getName(), getName(),
2550 inst
->getRetainCount());
2559 // adjust the busy count by -1 if matching is stalled for a module,
2560 // or +1 if a previously stalled matching is complete.
2561 lockForArbitration();
2564 adjBusy
= (__state
[1] & kIOServiceModuleStallState
) ? 0 : 1;
2566 __state
[1] |= kIOServiceModuleStallState
;
2568 } else if( __state
[1] & kIOServiceModuleStallState
) {
2569 __state
[1] &= ~kIOServiceModuleStallState
;
2573 _adjustBusy( adjBusy
);
2574 unlockForArbitration();
2577 startDict
->release();
2581 * Start a previously attached & probed instance,
2582 * called on exporting object instance
2585 bool IOService::startCandidate( IOService
* service
)
2589 ok
= service
->attach( this );
2593 if (this != gIOResources
)
2595 // stall for any nub resources
2597 // stall for any driver resources
2598 service
->checkResources();
2601 AbsoluteTime startTime
;
2602 AbsoluteTime endTime
;
2605 if (kIOLogStart
& gIOKitDebug
)
2606 clock_get_uptime(&startTime
);
2608 ok
= service
->start(this);
2610 if (kIOLogStart
& gIOKitDebug
)
2612 clock_get_uptime(&endTime
);
2614 if (CMP_ABSOLUTETIME(&endTime
, &startTime
) > 0)
2616 SUB_ABSOLUTETIME(&endTime
, &startTime
);
2617 absolutetime_to_nanoseconds(endTime
, &nano
);
2618 if (nano
> 500000000ULL)
2619 IOLog("%s::start took %ld ms\n", service
->getName(), (UInt32
)(nano
/ 1000000ULL));
2623 service
->detach( this );
2628 IOService
* IOService::resources( void )
2630 return( gIOResources
);
2633 void IOService::publishResource( const char * key
, OSObject
* value
)
2635 const OSSymbol
* sym
;
2637 if( (sym
= OSSymbol::withCString( key
))) {
2638 publishResource( sym
, value
);
2643 void IOService::publishResource( const OSSymbol
* key
, OSObject
* value
)
2646 value
= (OSObject
*) gIOServiceKey
;
2648 gIOResources
->setProperty( key
, value
);
2650 if( IORecursiveLockHaveLock( gNotificationLock
))
2653 gIOResourceGenerationCount
++;
2654 gIOResources
->registerService();
2657 bool IOService::addNeededResource( const char * key
)
2659 OSObject
* resourcesProp
;
2664 resourcesProp
= getProperty( gIOResourceMatchKey
);
2666 newKey
= OSString::withCString( key
);
2667 if( (0 == resourcesProp
) || (0 == newKey
))
2670 set
= OSDynamicCast( OSSet
, resourcesProp
);
2672 set
= OSSet::withCapacity( 1 );
2674 set
->setObject( resourcesProp
);
2679 set
->setObject( newKey
);
2681 ret
= setProperty( gIOResourceMatchKey
, set
);
2687 bool IOService::checkResource( OSObject
* matching
)
2690 OSDictionary
* table
;
2692 if( (str
= OSDynamicCast( OSString
, matching
))) {
2693 if( gIOResources
->getProperty( str
))
2698 table
= resourceMatching( str
);
2699 else if( (table
= OSDynamicCast( OSDictionary
, matching
)))
2702 IOLog("%s: Can't match using: %s\n", getName(),
2703 matching
->getMetaClass()->getClassName());
2704 /* false would stall forever */
2708 if( gIOKitDebug
& kIOLogConfig
)
2709 LOG("config(%x): stalling %s\n", (int) IOThreadSelf(), getName());
2711 waitForService( table
);
2713 if( gIOKitDebug
& kIOLogConfig
)
2714 LOG("config(%x): waking\n", (int) IOThreadSelf() );
2719 bool IOService::checkResources( void )
2721 OSObject
* resourcesProp
;
2726 resourcesProp
= getProperty( gIOResourceMatchKey
);
2727 if( 0 == resourcesProp
)
2730 if( (set
= OSDynamicCast( OSSet
, resourcesProp
))) {
2732 iter
= OSCollectionIterator::withCollection( set
);
2734 while( ok
&& (resourcesProp
= iter
->getNextObject()) )
2735 ok
= checkResource( resourcesProp
);
2740 ok
= checkResource( resourcesProp
);
2746 void _IOConfigThread::configThread( void )
2748 _IOConfigThread
* inst
;
2751 if( !(inst
= new _IOConfigThread
))
2755 if( !(IOCreateThread((IOThreadFunc
) &_IOConfigThread::main
, inst
)))
2768 void _IOConfigThread::free( void )
2773 void IOService::doServiceMatch( IOOptionBits options
)
2775 _IOServiceNotifier
* notify
;
2777 OSOrderedSet
* matches
;
2778 SInt32 catalogGeneration
;
2779 bool keepGuessing
= true;
2780 bool reRegistered
= true;
2782 // job->nub->deliverNotification( gIOPublishNotification,
2783 // kIOServiceRegisteredState, 0xffffffff );
2785 while( keepGuessing
) {
2787 matches
= gIOCatalogue
->findDrivers( this, &catalogGeneration
);
2788 // the matches list should always be created by findDrivers()
2791 lockForArbitration();
2792 if( 0 == (__state
[0] & kIOServiceFirstPublishState
))
2793 deliverNotification( gIOFirstPublishNotification
,
2794 kIOServiceFirstPublishState
, 0xffffffff );
2796 __state
[1] &= ~kIOServiceNeedConfigState
;
2797 __state
[1] |= kIOServiceConfigState
;
2798 __state
[0] |= kIOServiceRegisteredState
;
2800 if( reRegistered
&& (0 == (__state
[0] & kIOServiceInactiveState
))) {
2802 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
2803 gNotifications
->getObject( gIOPublishNotification
) );
2805 while((notify
= (_IOServiceNotifier
*)
2806 iter
->getNextObject())) {
2808 if( passiveMatch( notify
->matching
)
2809 && (kIOServiceNotifyEnable
& notify
->state
))
2810 matches
->setObject( notify
);
2817 unlockForArbitration();
2819 if( matches
->getCount() && (kIOReturnSuccess
== getResources()))
2820 probeCandidates( matches
);
2825 lockForArbitration();
2826 reRegistered
= (0 != (__state
[1] & kIOServiceNeedConfigState
));
2828 (reRegistered
|| (catalogGeneration
!=
2829 gIOCatalogue
->getGenerationCount()))
2830 && (0 == (__state
[0] & kIOServiceInactiveState
));
2833 unlockForArbitration();
2836 if( (0 == (__state
[0] & kIOServiceInactiveState
))
2837 && (0 == (__state
[1] & kIOServiceModuleStallState
)) ) {
2838 deliverNotification( gIOMatchedNotification
,
2839 kIOServiceMatchedState
, 0xffffffff );
2840 if( 0 == (__state
[0] & kIOServiceFirstMatchState
))
2841 deliverNotification( gIOFirstMatchNotification
,
2842 kIOServiceFirstMatchState
, 0xffffffff );
2845 __state
[1] &= ~kIOServiceConfigState
;
2846 if( __state
[0] & kIOServiceInactiveState
)
2847 scheduleTerminatePhase2();
2850 unlockForArbitration();
2853 UInt32
IOService::_adjustBusy( SInt32 delta
)
2858 bool wasQuiet
, nowQuiet
, needWake
;
2861 result
= __state
[1] & kIOServiceBusyStateMask
;
2865 next
->lockForArbitration();
2866 count
= next
->__state
[1] & kIOServiceBusyStateMask
;
2867 assert( count
< kIOServiceBusyMax
);
2868 wasQuiet
= (0 == count
);
2869 assert( (!wasQuiet
) || (delta
> 0));
2870 next
->__state
[1] += delta
;
2871 nowQuiet
= (0 == (next
->__state
[1] & kIOServiceBusyStateMask
));
2872 needWake
= (0 != (kIOServiceBusyWaiterState
& next
->__state
[1]));
2875 next
->__state
[1] &= ~kIOServiceBusyWaiterState
;
2876 IOLockLock( gIOServiceBusyLock
);
2877 thread_wakeup( (event_t
) next
);
2878 IOLockUnlock( gIOServiceBusyLock
);
2881 next
->unlockForArbitration();
2883 if( (wasQuiet
|| nowQuiet
) ) {
2886 OSObject
* interested
;
2888 array
= OSDynamicCast( OSArray
, next
->getProperty( gIOBusyInterest
));
2892 (interested
= array
->getObject( index
));
2894 next
->messageClient(kIOMessageServiceBusyStateChange
,
2895 interested
, (void *) wasQuiet
/* busy now */);
2900 if( nowQuiet
&& (next
== gIOServiceRoot
))
2901 OSMetaClass::considerUnloads();
2904 delta
= nowQuiet
? -1 : +1;
2906 } while( (wasQuiet
|| nowQuiet
) && (next
= next
->getProvider()));
2911 void IOService::adjustBusy( SInt32 delta
)
2913 lockForArbitration();
2914 _adjustBusy( delta
);
2915 unlockForArbitration();
2918 UInt32
IOService::getBusyState( void )
2920 return( __state
[1] & kIOServiceBusyStateMask
);
2923 IOReturn
IOService::waitForState( UInt32 mask
, UInt32 value
,
2924 mach_timespec_t
* timeout
)
2927 int waitResult
= THREAD_AWAKENED
;
2928 bool computeDeadline
= true;
2929 AbsoluteTime abstime
;
2932 lockForArbitration();
2933 IOLockLock( gIOServiceBusyLock
);
2934 wait
= (value
!= (__state
[1] & mask
));
2936 __state
[1] |= kIOServiceBusyWaiterState
;
2937 unlockForArbitration();
2939 if( computeDeadline
) {
2940 AbsoluteTime nsinterval
;
2941 clock_interval_to_absolutetime_interval(
2942 timeout
->tv_sec
, kSecondScale
, &abstime
);
2943 clock_interval_to_absolutetime_interval(
2944 timeout
->tv_nsec
, kNanosecondScale
, &nsinterval
);
2945 ADD_ABSOLUTETIME( &abstime
, &nsinterval
);
2946 clock_absolutetime_interval_to_deadline(
2947 abstime
, &abstime
);
2948 computeDeadline
= false;
2951 assert_wait_deadline((event_t
)this, THREAD_UNINT
, __OSAbsoluteTime(abstime
));
2954 assert_wait((event_t
)this, THREAD_UNINT
);
2956 unlockForArbitration();
2957 IOLockUnlock( gIOServiceBusyLock
);
2959 waitResult
= thread_block(THREAD_CONTINUE_NULL
);
2961 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
2963 if( waitResult
== THREAD_TIMED_OUT
)
2964 return( kIOReturnTimeout
);
2966 return( kIOReturnSuccess
);
2969 IOReturn
IOService::waitQuiet( mach_timespec_t
* timeout
)
2971 return( waitForState( kIOServiceBusyStateMask
, 0, timeout
));
2974 bool IOService::serializeProperties( OSSerialize
* s
) const
2977 ((IOService
*)this)->setProperty( ((IOService
*)this)->__state
,
2978 sizeof( __state
), "__state");
2980 return( super::serializeProperties(s
) );
2984 void _IOConfigThread::main( _IOConfigThread
* self
)
2986 _IOServiceJob
* job
;
2994 semaphore_wait( gJobsSemaphore
);
2996 IOTakeLock( gJobsLock
);
2997 job
= (_IOServiceJob
*) gJobs
->getFirstObject();
2999 gJobs
->removeObject(job
);
3002 // gNumConfigThreads--; // we're out of service
3003 gNumWaitingThreads
--; // we're out of service
3005 IOUnlock( gJobsLock
);
3011 if( gIOKitDebug
& kIOLogConfig
)
3012 LOG("config(%x): starting on %s, %d\n",
3013 (int) IOThreadSelf(), job
->nub
->getName(), job
->type
);
3015 switch( job
->type
) {
3018 nub
->doServiceMatch( job
->options
);
3022 LOG("config(%x): strange type (%d)\n",
3023 (int) IOThreadSelf(), job
->type
);
3030 IOTakeLock( gJobsLock
);
3031 alive
= (gOutstandingJobs
> gNumWaitingThreads
);
3033 gNumWaitingThreads
++; // back in service
3034 // gNumConfigThreads++;
3036 if( 0 == --gNumConfigThreads
) {
3037 // IOLog("MATCH IDLE\n");
3038 IOLockWakeup( gJobsLock
, (event_t
) &gNumConfigThreads
, /* one-thread */ false );
3041 IOUnlock( gJobsLock
);
3046 if( gIOKitDebug
& kIOLogConfig
)
3047 LOG("config(%x): terminating\n", (int) IOThreadSelf() );
3052 IOReturn
IOService::waitMatchIdle( UInt32 msToWait
)
3055 int waitResult
= THREAD_AWAKENED
;
3056 bool computeDeadline
= true;
3057 AbsoluteTime abstime
;
3059 IOLockLock( gJobsLock
);
3061 wait
= (0 != gNumConfigThreads
);
3064 if( computeDeadline
) {
3065 clock_interval_to_absolutetime_interval(
3066 msToWait
, kMillisecondScale
, &abstime
);
3067 clock_absolutetime_interval_to_deadline(
3068 abstime
, &abstime
);
3069 computeDeadline
= false;
3071 waitResult
= IOLockSleepDeadline( gJobsLock
, &gNumConfigThreads
,
3072 abstime
, THREAD_UNINT
);
3074 waitResult
= IOLockSleep( gJobsLock
, &gNumConfigThreads
,
3078 } while( wait
&& (waitResult
!= THREAD_TIMED_OUT
));
3079 IOLockUnlock( gJobsLock
);
3081 if( waitResult
== THREAD_TIMED_OUT
)
3082 return( kIOReturnTimeout
);
3084 return( kIOReturnSuccess
);
3087 void _IOServiceJob::pingConfig( _IOServiceJob
* job
)
3094 IOTakeLock( gJobsLock
);
3097 gJobs
->setLastObject( job
);
3099 count
= gNumWaitingThreads
;
3100 // if( gNumConfigThreads) count++;// assume we're called from a config thread
3102 create
= ( (gOutstandingJobs
> count
)
3103 && (gNumConfigThreads
< kMaxConfigThreads
) );
3105 gNumConfigThreads
++;
3106 gNumWaitingThreads
++;
3109 IOUnlock( gJobsLock
);
3114 if( gIOKitDebug
& kIOLogConfig
)
3115 LOG("config(%d): creating\n", gNumConfigThreads
- 1);
3116 _IOConfigThread::configThread();
3119 semaphore_signal( gJobsSemaphore
);
3122 // internal - call with gNotificationLock
3123 OSObject
* IOService::getExistingServices( OSDictionary
* matching
,
3124 IOOptionBits inState
, IOOptionBits options
)
3126 OSObject
* current
= 0;
3128 IOService
* service
;
3135 && (obj
= matching
->getObject(gIOProviderClassKey
))
3137 && gIOResourcesKey
->isEqualTo(obj
)
3138 && (service
= gIOResources
))
3140 if( (inState
== (service
->__state
[0] & inState
))
3141 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3142 && service
->passiveMatch( matching
))
3144 if( options
& kIONotifyOnce
)
3147 current
= OSSet::withObjects(
3148 (const OSObject
**) &service
, 1, 1 );
3153 iter
= IORegistryIterator::iterateOver( gIOServicePlane
,
3154 kIORegistryIterateRecursively
);
3158 while( (service
= (IOService
*) iter
->getNextObject())) {
3159 if( (inState
== (service
->__state
[0] & inState
))
3160 && (0 == (service
->__state
[0] & kIOServiceInactiveState
))
3161 && service
->passiveMatch( matching
)) {
3163 if( options
& kIONotifyOnce
) {
3168 ((OSSet
*)current
)->setObject( service
);
3170 current
= OSSet::withObjects(
3171 (const OSObject
**) &service
, 1, 1 );
3174 } while( !service
&& !iter
->isValid());
3179 if( current
&& (0 == (options
& (kIONotifyOnce
| kIOServiceExistingSet
)))) {
3180 iter
= OSCollectionIterator::withCollection( (OSSet
*)current
);
3189 OSIterator
* IOService::getMatchingServices( OSDictionary
* matching
)
3193 // is a lock even needed?
3196 iter
= (OSIterator
*) getExistingServices( matching
,
3197 kIOServiceMatchedState
);
3205 // internal - call with gNotificationLock
3206 IONotifier
* IOService::setNotification(
3207 const OSSymbol
* type
, OSDictionary
* matching
,
3208 IOServiceNotificationHandler handler
, void * target
, void * ref
,
3211 _IOServiceNotifier
* notify
= 0;
3217 notify
= new _IOServiceNotifier
;
3218 if( notify
&& !notify
->init()) {
3224 notify
->matching
= matching
;
3225 notify
->handler
= handler
;
3226 notify
->target
= target
;
3228 notify
->priority
= priority
;
3229 notify
->state
= kIOServiceNotifyEnable
;
3230 queue_init( ¬ify
->handlerInvocations
);
3234 if( 0 == (set
= (OSOrderedSet
*) gNotifications
->getObject( type
))) {
3235 set
= OSOrderedSet::withCapacity( 1,
3236 IONotifyOrdering
, 0 );
3238 gNotifications
->setObject( type
, set
);
3242 notify
->whence
= set
;
3244 set
->setObject( notify
);
3250 // internal - call with gNotificationLock
3251 IONotifier
* IOService::doInstallNotification(
3252 const OSSymbol
* type
, OSDictionary
* matching
,
3253 IOServiceNotificationHandler handler
,
3254 void * target
, void * ref
,
3255 SInt32 priority
, OSIterator
** existing
)
3258 IONotifier
* notify
;
3259 IOOptionBits inState
;
3264 if( type
== gIOPublishNotification
)
3265 inState
= kIOServiceRegisteredState
;
3267 else if( type
== gIOFirstPublishNotification
)
3268 inState
= kIOServiceFirstPublishState
;
3270 else if( (type
== gIOMatchedNotification
)
3271 || (type
== gIOFirstMatchNotification
))
3272 inState
= kIOServiceMatchedState
;
3273 else if( type
== gIOTerminatedNotification
)
3278 notify
= setNotification( type
, matching
, handler
, target
, ref
, priority
);
3281 // get the current set
3282 exist
= (OSIterator
*) getExistingServices( matching
, inState
);
3292 IONotifier
* IOService::installNotification(
3293 const OSSymbol
* type
, OSDictionary
* matching
,
3294 IOServiceNotificationHandler handler
,
3295 void * target
, void * ref
,
3296 SInt32 priority
, OSIterator
** existing
)
3298 IONotifier
* notify
;
3302 notify
= doInstallNotification( type
, matching
, handler
, target
, ref
,
3303 priority
, existing
);
3310 IONotifier
* IOService::addNotification(
3311 const OSSymbol
* type
, OSDictionary
* matching
,
3312 IOServiceNotificationHandler handler
,
3313 void * target
, void * ref
,
3316 OSIterator
* existing
;
3317 _IOServiceNotifier
* notify
;
3320 notify
= (_IOServiceNotifier
*) installNotification( type
, matching
,
3321 handler
, target
, ref
, priority
, &existing
);
3323 // send notifications for existing set
3326 notify
->retain(); // in case handler remove()s
3327 while( (next
= (IOService
*) existing
->getNextObject())) {
3329 next
->lockForArbitration();
3330 if( 0 == (next
->__state
[0] & kIOServiceInactiveState
))
3331 next
->invokeNotifer( notify
);
3332 next
->unlockForArbitration();
3335 existing
->release();
3341 struct SyncNotifyVars
{
3342 semaphore_port_t waitHere
;
3346 bool IOService::syncNotificationHandler(
3347 void * /* target */, void * ref
,
3348 IOService
* newService
)
3351 // result may get written more than once before the
3352 // notification is removed!
3353 ((SyncNotifyVars
*) ref
)->result
= newService
;
3354 semaphore_signal( ((SyncNotifyVars
*) ref
)->waitHere
);
3359 IOService
* IOService::waitForService( OSDictionary
* matching
,
3360 mach_timespec_t
* timeout
)
3362 IONotifier
* notify
= 0;
3363 // priority doesn't help us much since we need a thread wakeup
3364 SInt32 priority
= 0;
3365 SyncNotifyVars state
;
3366 kern_return_t err
= kIOReturnBadArgument
;
3378 state
.result
= (IOService
*) getExistingServices( matching
,
3379 kIOServiceMatchedState
, kIONotifyOnce
);
3383 err
= semaphore_create( kernel_task
, &state
.waitHere
,
3384 SYNC_POLICY_FIFO
, 0 );
3385 if( KERN_SUCCESS
!= err
)
3388 notify
= IOService::setNotification( gIOMatchedNotification
, matching
,
3389 &IOService::syncNotificationHandler
, (void *) 0,
3390 (void *) &state
, priority
);
3398 err
= semaphore_timedwait( state
.waitHere
, *timeout
);
3400 err
= semaphore_wait( state
.waitHere
);
3404 notify
->remove(); // dequeues
3406 matching
->release();
3408 semaphore_destroy( kernel_task
, state
.waitHere
);
3410 return( state
.result
);
3413 void IOService::deliverNotification( const OSSymbol
* type
,
3414 IOOptionBits orNewState
, IOOptionBits andNewState
)
3416 _IOServiceNotifier
* notify
;
3418 OSArray
* willSend
= 0;
3420 lockForArbitration();
3422 if( (0 == (__state
[0] & kIOServiceInactiveState
))
3423 || (type
== gIOTerminatedNotification
)) {
3427 iter
= OSCollectionIterator::withCollection( (OSOrderedSet
*)
3428 gNotifications
->getObject( type
) );
3431 while( (notify
= (_IOServiceNotifier
*) iter
->getNextObject())) {
3433 if( passiveMatch( notify
->matching
)
3434 && (kIOServiceNotifyEnable
& notify
->state
)) {
3436 willSend
= OSArray::withCapacity(8);
3438 willSend
->setObject( notify
);
3444 __state
[0] = (__state
[0] | orNewState
) & andNewState
;
3450 for( unsigned int idx
= 0;
3451 (notify
= (_IOServiceNotifier
*) willSend
->getObject(idx
));
3453 invokeNotifer( notify
);
3455 willSend
->release();
3457 unlockForArbitration();
3460 IOOptionBits
IOService::getState( void ) const
3462 return( __state
[0] );
3466 * Helpers to make matching objects for simple cases
3469 OSDictionary
* IOService::serviceMatching( const OSString
* name
,
3470 OSDictionary
* table
)
3473 table
= OSDictionary::withCapacity( 2 );
3475 table
->setObject(gIOProviderClassKey
, (OSObject
*)name
);
3480 OSDictionary
* IOService::serviceMatching( const char * name
,
3481 OSDictionary
* table
)
3483 const OSString
* str
;
3485 str
= OSSymbol::withCString( name
);
3489 table
= serviceMatching( str
, table
);
3494 OSDictionary
* IOService::nameMatching( const OSString
* name
,
3495 OSDictionary
* table
)
3498 table
= OSDictionary::withCapacity( 2 );
3500 table
->setObject( gIONameMatchKey
, (OSObject
*)name
);
3505 OSDictionary
* IOService::nameMatching( const char * name
,
3506 OSDictionary
* table
)
3508 const OSString
* str
;
3510 str
= OSSymbol::withCString( name
);
3514 table
= nameMatching( str
, table
);
3519 OSDictionary
* IOService::resourceMatching( const OSString
* str
,
3520 OSDictionary
* table
)
3522 table
= serviceMatching( gIOResourcesKey
, table
);
3524 table
->setObject( gIOResourceMatchKey
, (OSObject
*) str
);
3529 OSDictionary
* IOService::resourceMatching( const char * name
,
3530 OSDictionary
* table
)
3532 const OSSymbol
* str
;
3534 str
= OSSymbol::withCString( name
);
3538 table
= resourceMatching( str
, table
);
3545 * _IOServiceNotifier
3548 // wait for all threads, other than the current one,
3549 // to exit the handler
3551 void _IOServiceNotifier::wait()
3553 _IOServiceNotifierInvocation
* next
;
3558 queue_iterate( &handlerInvocations
, next
,
3559 _IOServiceNotifierInvocation
*, link
) {
3560 if( next
->thread
!= current_thread() ) {
3566 state
|= kIOServiceNotifyWaiter
;
3573 void _IOServiceNotifier::free()
3575 assert( queue_empty( &handlerInvocations
));
3579 void _IOServiceNotifier::remove()
3584 whence
->removeObject( (OSObject
*) this );
3588 matching
->release();
3592 state
&= ~kIOServiceNotifyEnable
;
3601 bool _IOServiceNotifier::disable()
3607 ret
= (0 != (kIOServiceNotifyEnable
& state
));
3608 state
&= ~kIOServiceNotifyEnable
;
3617 void _IOServiceNotifier::enable( bool was
)
3621 state
|= kIOServiceNotifyEnable
;
3623 state
&= ~kIOServiceNotifyEnable
;
3631 IOService
* IOResources::resources( void )
3635 inst
= new IOResources
;
3636 if( inst
&& !inst
->init()) {
3644 IOWorkLoop
* IOResources::getWorkLoop() const
3646 // If we are the resource root then bringe over to the
3647 // platform to get its workloop
3648 if (this == (IOResources
*) gIOResources
)
3649 return getPlatform()->getWorkLoop();
3651 return IOService::getWorkLoop();
3654 bool IOResources::matchPropertyTable( OSDictionary
* table
)
3662 prop
= table
->getObject( gIOResourceMatchKey
);
3663 str
= OSDynamicCast( OSString
, prop
);
3665 ok
= (0 != getProperty( str
));
3667 else if( (set
= OSDynamicCast( OSSet
, prop
))) {
3669 iter
= OSCollectionIterator::withCollection( set
);
3671 while( ok
&& (str
= OSDynamicCast( OSString
, iter
->getNextObject()) ))
3672 ok
= (0 != getProperty( str
));
3681 IOReturn
IOResources::setProperties( OSObject
* properties
)
3684 const OSSymbol
* key
;
3685 OSDictionary
* dict
;
3686 OSCollectionIterator
* iter
;
3688 err
= IOUserClient::clientHasPrivilege(current_task(), kIOClientPrivilegeAdministrator
);
3689 if ( kIOReturnSuccess
!= err
)
3692 dict
= OSDynamicCast(OSDictionary
, properties
);
3694 return( kIOReturnBadArgument
);
3696 iter
= OSCollectionIterator::withCollection( dict
);
3698 return( kIOReturnBadArgument
);
3700 while( (key
= OSDynamicCast(OSSymbol
, iter
->getNextObject()))) {
3702 if (gIOConsoleUsersKey
== key
)
3704 IORegistryEntry::getRegistryRoot()->setProperty(key
, dict
->getObject(key
));
3705 OSIncrementAtomic( &gIOConsoleUsersSeed
);
3706 publishResource( gIOConsoleUsersSeedKey
, gIOConsoleUsersSeedValue
);
3710 publishResource( key
, dict
->getObject(key
) );
3715 return( kIOReturnSuccess
);
3719 * Helpers for matching dictionaries.
3720 * Keys existing in matching are checked in properties.
3721 * Keys may be a string or OSCollection of IOStrings
3724 bool IOService::compareProperty( OSDictionary
* matching
,
3730 value
= matching
->getObject( key
);
3732 ok
= value
->isEqualTo( getProperty( key
));
3740 bool IOService::compareProperty( OSDictionary
* matching
,
3741 const OSString
* key
)
3746 value
= matching
->getObject( key
);
3748 ok
= value
->isEqualTo( getProperty( key
));
3755 bool IOService::compareProperties( OSDictionary
* matching
,
3756 OSCollection
* keys
)
3758 OSCollectionIterator
* iter
;
3759 const OSString
* key
;
3762 if( !matching
|| !keys
)
3765 iter
= OSCollectionIterator::withCollection( keys
);
3768 while( ok
&& (key
= OSDynamicCast( OSString
, iter
->getNextObject())))
3769 ok
= compareProperty( matching
, key
);
3773 keys
->release(); // !! consume a ref !!
3778 /* Helper to add a location matching dict to the table */
3780 OSDictionary
* IOService::addLocation( OSDictionary
* table
)
3782 OSDictionary
* dict
;
3787 dict
= OSDictionary::withCapacity( 1 );
3789 table
->setObject( gIOLocationMatchKey
, dict
);
3797 * Go looking for a provider to match a location dict.
3800 IOService
* IOService::matchLocation( IOService
* /* client */ )
3804 parent
= getProvider();
3807 parent
= parent
->matchLocation( this );
3812 bool IOService::passiveMatch( OSDictionary
* table
, bool changesOK
)
3818 IORegistryEntry
* entry
;
3823 bool matchParent
= false;
3834 str
= OSDynamicCast( OSString
, table
->getObject( gIOProviderClassKey
));
3837 match
= (0 != where
->metaCast( str
));
3842 obj
= table
->getObject( gIONameMatchKey
);
3845 match
= where
->compareNames( obj
, changesOK
? &matched
: 0 );
3848 if( changesOK
&& matched
) {
3849 // leave a hint as to which name matched
3850 table
->setObject( gIONameMatchedKey
, matched
);
3855 str
= OSDynamicCast( OSString
, table
->getObject( gIOLocationMatchKey
));
3858 const OSSymbol
* sym
;
3862 sym
= where
->copyLocation();
3864 match
= sym
->isEqualTo( str
);
3871 obj
= table
->getObject( gIOPropertyMatchKey
);
3874 OSDictionary
* dict
;
3875 OSDictionary
* nextDict
;
3880 dict
= where
->dictionaryWithProperties();
3882 nextDict
= OSDynamicCast( OSDictionary
, obj
);
3886 iter
= OSCollectionIterator::withCollection(
3887 OSDynamicCast(OSCollection
, obj
));
3890 || (iter
&& (0 != (nextDict
= OSDynamicCast(OSDictionary
,
3891 iter
->getNextObject()))))) {
3892 match
= dict
->isEqualTo( nextDict
, nextDict
);
3905 str
= OSDynamicCast( OSString
, table
->getObject( gIOPathMatchKey
));
3908 entry
= IORegistryEntry::fromPath( str
->getCStringNoCopy() );
3909 match
= (where
== entry
);
3916 num
= OSDynamicCast( OSNumber
, table
->getObject( gIOMatchedServiceCountKey
));
3920 IOService
* service
= 0;
3921 UInt32 serviceCount
= 0;
3924 iter
= where
->getClientIterator();
3926 while( (service
= (IOService
*) iter
->getNextObject())) {
3927 if( kIOServiceInactiveState
& service
->__state
[0])
3929 if( 0 == service
->getProperty( gIOMatchCategoryKey
))
3935 match
= (serviceCount
== num
->unsigned32BitValue());
3940 if( done
== table
->getCount()) {
3941 // don't call family if we've done all the entries in the table
3942 matchParent
= false;
3946 // pass in score from property table
3947 score
= IOServiceObjectOrder( table
, (void *) gIOProbeScoreKey
);
3949 // do family specific matching
3950 match
= where
->matchPropertyTable( table
, &score
);
3954 if( kIOLogMatch
& getDebugFlags( table
))
3955 LOG("%s: family specific matching fails\n", where
->getName());
3962 newPri
= OSNumber::withNumber( score
, 32 );
3964 table
->setObject( gIOProbeScoreKey
, newPri
);
3969 if( !(match
= where
->compareProperty( table
, kIOBSDNameKey
)))
3972 matchParent
= false;
3974 obj
= OSDynamicCast( OSDictionary
,
3975 table
->getObject( gIOParentMatchKey
));
3979 table
= (OSDictionary
*) obj
;
3983 table
= OSDynamicCast( OSDictionary
,
3984 table
->getObject( gIOLocationMatchKey
));
3987 where
= where
->getProvider();
3989 where
= where
->matchLocation( where
);
3992 } while( table
&& where
);
3994 } while( matchParent
&& (where
= where
->getProvider()) );
3996 if( kIOLogMatch
& gIOKitDebug
)
3998 LOG("match parent @ %s = %d\n",
3999 where
->getName(), match
);
4005 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
4006 UInt32 type
, OSDictionary
* properties
,
4007 IOUserClient
** handler
)
4009 const OSSymbol
*userClientClass
= 0;
4010 IOUserClient
*client
;
4013 // First try my own properties for a user client class name
4014 temp
= getProperty(gIOUserClientClassKey
);
4016 if (OSDynamicCast(OSSymbol
, temp
))
4017 userClientClass
= (const OSSymbol
*) temp
;
4018 else if (OSDynamicCast(OSString
, temp
)) {
4019 userClientClass
= OSSymbol::withString((OSString
*) temp
);
4020 if (userClientClass
)
4021 setProperty(kIOUserClientClassKey
,
4022 (OSObject
*) userClientClass
);
4026 // Didn't find one so lets just bomb out now without further ado.
4027 if (!userClientClass
)
4028 return kIOReturnUnsupported
;
4030 temp
= OSMetaClass::allocClassWithName(userClientClass
);
4032 return kIOReturnNoMemory
;
4034 if (OSDynamicCast(IOUserClient
, temp
))
4035 client
= (IOUserClient
*) temp
;
4038 return kIOReturnUnsupported
;
4041 if ( !client
->initWithTask(owningTask
, securityID
, type
, properties
) ) {
4043 return kIOReturnBadArgument
;
4046 if ( !client
->attach(this) ) {
4048 return kIOReturnUnsupported
;
4051 if ( !client
->start(this) ) {
4052 client
->detach(this);
4054 return kIOReturnUnsupported
;
4058 return kIOReturnSuccess
;
4061 IOReturn
IOService::newUserClient( task_t owningTask
, void * securityID
,
4062 UInt32 type
, IOUserClient
** handler
)
4064 return( newUserClient( owningTask
, securityID
, type
, 0, handler
));
4067 IOReturn
IOService::requestProbe( IOOptionBits options
)
4069 return( kIOReturnUnsupported
);
4073 * Convert an IOReturn to text. Subclasses which add additional
4074 * IOReturn's should override this method and call
4075 * super::stringFromReturn if the desired value is not found.
4078 const char * IOService::stringFromReturn( IOReturn rtn
)
4080 static const IONamedValue IOReturn_values
[] = {
4081 {kIOReturnSuccess
, "success" },
4082 {kIOReturnError
, "general error" },
4083 {kIOReturnNoMemory
, "memory allocation error" },
4084 {kIOReturnNoResources
, "resource shortage" },
4085 {kIOReturnIPCError
, "Mach IPC failure" },
4086 {kIOReturnNoDevice
, "no such device" },
4087 {kIOReturnNotPrivileged
, "privilege violation" },
4088 {kIOReturnBadArgument
, "invalid argument" },
4089 {kIOReturnLockedRead
, "device is read locked" },
4090 {kIOReturnLockedWrite
, "device is write locked" },
4091 {kIOReturnExclusiveAccess
, "device is exclusive access" },
4092 {kIOReturnBadMessageID
, "bad IPC message ID" },
4093 {kIOReturnUnsupported
, "unsupported function" },
4094 {kIOReturnVMError
, "virtual memory error" },
4095 {kIOReturnInternalError
, "internal driver error" },
4096 {kIOReturnIOError
, "I/O error" },
4097 {kIOReturnCannotLock
, "cannot acquire lock" },
4098 {kIOReturnNotOpen
, "device is not open" },
4099 {kIOReturnNotReadable
, "device is not readable" },
4100 {kIOReturnNotWritable
, "device is not writeable" },
4101 {kIOReturnNotAligned
, "alignment error" },
4102 {kIOReturnBadMedia
, "media error" },
4103 {kIOReturnStillOpen
, "device is still open" },
4104 {kIOReturnRLDError
, "rld failure" },
4105 {kIOReturnDMAError
, "DMA failure" },
4106 {kIOReturnBusy
, "device is busy" },
4107 {kIOReturnTimeout
, "I/O timeout" },
4108 {kIOReturnOffline
, "device is offline" },
4109 {kIOReturnNotReady
, "device is not ready" },
4110 {kIOReturnNotAttached
, "device/channel is not attached" },
4111 {kIOReturnNoChannels
, "no DMA channels available" },
4112 {kIOReturnNoSpace
, "no space for data" },
4113 {kIOReturnPortExists
, "device port already exists" },
4114 {kIOReturnCannotWire
, "cannot wire physical memory" },
4115 {kIOReturnNoInterrupt
, "no interrupt attached" },
4116 {kIOReturnNoFrames
, "no DMA frames enqueued" },
4117 {kIOReturnMessageTooLarge
, "message is too large" },
4118 {kIOReturnNotPermitted
, "operation is not permitted" },
4119 {kIOReturnNoPower
, "device is without power" },
4120 {kIOReturnNoMedia
, "media is not present" },
4121 {kIOReturnUnformattedMedia
, "media is not formatted" },
4122 {kIOReturnUnsupportedMode
, "unsupported mode" },
4123 {kIOReturnUnderrun
, "data underrun" },
4124 {kIOReturnOverrun
, "data overrun" },
4125 {kIOReturnDeviceError
, "device error" },
4126 {kIOReturnNoCompletion
, "no completion routine" },
4127 {kIOReturnAborted
, "operation was aborted" },
4128 {kIOReturnNoBandwidth
, "bus bandwidth would be exceeded" },
4129 {kIOReturnNotResponding
, "device is not responding" },
4130 {kIOReturnInvalid
, "unanticipated driver error" },
4134 return IOFindNameForValue(rtn
, IOReturn_values
);
4138 * Convert an IOReturn to an errno.
4140 int IOService::errnoFromReturn( IOReturn rtn
)
4144 case kIOReturnSuccess
:
4146 case kIOReturnNoMemory
:
4148 case kIOReturnNoDevice
:
4150 case kIOReturnVMError
:
4152 case kIOReturnNotPermitted
:
4154 case kIOReturnNotPrivileged
:
4156 case kIOReturnIOError
:
4158 case kIOReturnNotWritable
:
4160 case kIOReturnBadArgument
:
4162 case kIOReturnUnsupported
:
4166 case kIOReturnNoPower
:
4168 case kIOReturnDeviceError
:
4170 case kIOReturnTimeout
:
4172 case kIOReturnMessageTooLarge
:
4174 case kIOReturnNoSpace
:
4176 case kIOReturnCannotLock
:
4180 case kIOReturnBadMessageID
:
4181 case kIOReturnNoCompletion
:
4182 case kIOReturnNotAligned
:
4184 case kIOReturnNotReady
:
4186 case kIOReturnRLDError
:
4188 case kIOReturnPortExists
:
4189 case kIOReturnStillOpen
:
4191 case kIOReturnExclusiveAccess
:
4192 case kIOReturnLockedRead
:
4193 case kIOReturnLockedWrite
:
4194 case kIOReturnNotAttached
:
4195 case kIOReturnNotOpen
:
4196 case kIOReturnNotReadable
:
4198 case kIOReturnCannotWire
:
4199 case kIOReturnNoResources
:
4201 case kIOReturnAborted
:
4202 case kIOReturnOffline
:
4203 case kIOReturnNotResponding
:
4205 case kIOReturnBadMedia
:
4206 case kIOReturnNoMedia
:
4207 case kIOReturnUnformattedMedia
:
4208 return(ENXIO
); // (media error)
4209 case kIOReturnDMAError
:
4210 case kIOReturnOverrun
:
4211 case kIOReturnUnderrun
:
4212 return(EIO
); // (transfer error)
4213 case kIOReturnNoBandwidth
:
4214 case kIOReturnNoChannels
:
4215 case kIOReturnNoFrames
:
4216 case kIOReturnNoInterrupt
:
4217 return(EIO
); // (hardware error)
4218 case kIOReturnError
:
4219 case kIOReturnInternalError
:
4220 case kIOReturnInvalid
:
4221 return(EIO
); // (generic error)
4222 case kIOReturnIPCError
:
4223 return(EIO
); // (ipc error)
4225 return(EIO
); // (all other errors)
4229 IOReturn
IOService::message( UInt32 type
, IOService
* provider
,
4233 * Generic entry point for calls from the provider. A return value of
4234 * kIOReturnSuccess indicates that the message was received, and where
4235 * applicable, that it was successful.
4238 return kIOReturnUnsupported
;
4245 IOItemCount
IOService::getDeviceMemoryCount( void )
4250 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4252 count
= array
->getCount();
4259 IODeviceMemory
* IOService::getDeviceMemoryWithIndex( unsigned int index
)
4262 IODeviceMemory
* range
;
4264 array
= OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
));
4266 range
= (IODeviceMemory
*) array
->getObject( index
);
4273 IOMemoryMap
* IOService::mapDeviceMemoryWithIndex( unsigned int index
,
4274 IOOptionBits options
)
4276 IODeviceMemory
* range
;
4279 range
= getDeviceMemoryWithIndex( index
);
4281 map
= range
->map( options
);
4288 OSArray
* IOService::getDeviceMemory( void )
4290 return( OSDynamicCast( OSArray
, getProperty( gIODeviceMemoryKey
)));
4294 void IOService::setDeviceMemory( OSArray
* array
)
4296 setProperty( gIODeviceMemoryKey
, array
);
4303 IOReturn
IOService::resolveInterrupt(IOService
*nub
, int source
)
4305 IOInterruptController
*interruptController
;
4308 OSSymbol
*interruptControllerName
;
4310 IOInterruptSource
*interruptSources
;
4312 // Get the parents list from the nub.
4313 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptControllersKey
));
4314 if (array
== 0) return kIOReturnNoResources
;
4316 // Allocate space for the IOInterruptSources if needed... then return early.
4317 if (nub
->_interruptSources
== 0) {
4318 numSources
= array
->getCount();
4319 interruptSources
= (IOInterruptSource
*)IOMalloc(numSources
* sizeof(IOInterruptSource
));
4320 if (interruptSources
== 0) return kIOReturnNoMemory
;
4322 bzero(interruptSources
, numSources
* sizeof(IOInterruptSource
));
4324 nub
->_numInterruptSources
= numSources
;
4325 nub
->_interruptSources
= interruptSources
;
4326 return kIOReturnSuccess
;
4329 interruptControllerName
= OSDynamicCast(OSSymbol
,array
->getObject(source
));
4330 if (interruptControllerName
== 0) return kIOReturnNoResources
;
4332 interruptController
= getPlatform()->lookUpInterruptController(interruptControllerName
);
4333 if (interruptController
== 0) return kIOReturnNoResources
;
4335 // Get the interrupt numbers from the nub.
4336 array
= OSDynamicCast(OSArray
, nub
->getProperty(gIOInterruptSpecifiersKey
));
4337 if (array
== 0) return kIOReturnNoResources
;
4338 data
= OSDynamicCast(OSData
, array
->getObject(source
));
4339 if (data
== 0) return kIOReturnNoResources
;
4341 // Set the interruptController and interruptSource in the nub's table.
4342 interruptSources
= nub
->_interruptSources
;
4343 interruptSources
[source
].interruptController
= interruptController
;
4344 interruptSources
[source
].vectorData
= data
;
4346 return kIOReturnSuccess
;
4349 IOReturn
IOService::lookupInterrupt(int source
, bool resolve
, IOInterruptController
**interruptController
)
4353 /* Make sure the _interruptSources are set */
4354 if (_interruptSources
== 0) {
4355 ret
= resolveInterrupt(this, source
);
4356 if (ret
!= kIOReturnSuccess
) return ret
;
4359 /* Make sure the local source number is valid */
4360 if ((source
< 0) || (source
>= _numInterruptSources
))
4361 return kIOReturnNoInterrupt
;
4363 /* Look up the contoller for the local source */
4364 *interruptController
= _interruptSources
[source
].interruptController
;
4366 if (*interruptController
== NULL
) {
4367 if (!resolve
) return kIOReturnNoInterrupt
;
4369 /* Try to reslove the interrupt */
4370 ret
= resolveInterrupt(this, source
);
4371 if (ret
!= kIOReturnSuccess
) return ret
;
4373 *interruptController
= _interruptSources
[source
].interruptController
;
4376 return kIOReturnSuccess
;
4379 IOReturn
IOService::registerInterrupt(int source
, OSObject
*target
,
4380 IOInterruptAction handler
,
4383 IOInterruptController
*interruptController
;
4386 ret
= lookupInterrupt(source
, true, &interruptController
);
4387 if (ret
!= kIOReturnSuccess
) return ret
;
4389 /* Register the source */
4390 return interruptController
->registerInterrupt(this, source
, target
,
4391 (IOInterruptHandler
)handler
,
4395 IOReturn
IOService::unregisterInterrupt(int source
)
4397 IOInterruptController
*interruptController
;
4400 ret
= lookupInterrupt(source
, false, &interruptController
);
4401 if (ret
!= kIOReturnSuccess
) return ret
;
4403 /* Unregister the source */
4404 return interruptController
->unregisterInterrupt(this, source
);
4407 IOReturn
IOService::getInterruptType(int source
, int *interruptType
)
4409 IOInterruptController
*interruptController
;
4412 ret
= lookupInterrupt(source
, true, &interruptController
);
4413 if (ret
!= kIOReturnSuccess
) return ret
;
4415 /* Return the type */
4416 return interruptController
->getInterruptType(this, source
, interruptType
);
4419 IOReturn
IOService::enableInterrupt(int source
)
4421 IOInterruptController
*interruptController
;
4424 ret
= lookupInterrupt(source
, false, &interruptController
);
4425 if (ret
!= kIOReturnSuccess
) return ret
;
4427 /* Enable the source */
4428 return interruptController
->enableInterrupt(this, source
);
4431 IOReturn
IOService::disableInterrupt(int source
)
4433 IOInterruptController
*interruptController
;
4436 ret
= lookupInterrupt(source
, false, &interruptController
);
4437 if (ret
!= kIOReturnSuccess
) return ret
;
4439 /* Disable the source */
4440 return interruptController
->disableInterrupt(this, source
);
4443 IOReturn
IOService::causeInterrupt(int source
)
4445 IOInterruptController
*interruptController
;
4448 ret
= lookupInterrupt(source
, false, &interruptController
);
4449 if (ret
!= kIOReturnSuccess
) return ret
;
4451 /* Cause an interrupt for the source */
4452 return interruptController
->causeInterrupt(this, source
);
4455 OSMetaClassDefineReservedUsed(IOService
, 0);
4456 OSMetaClassDefineReservedUsed(IOService
, 1);
4457 OSMetaClassDefineReservedUsed(IOService
, 2);
4458 OSMetaClassDefineReservedUsed(IOService
, 3);
4460 OSMetaClassDefineReservedUnused(IOService
, 4);
4461 OSMetaClassDefineReservedUnused(IOService
, 5);
4462 OSMetaClassDefineReservedUnused(IOService
, 6);
4463 OSMetaClassDefineReservedUnused(IOService
, 7);
4464 OSMetaClassDefineReservedUnused(IOService
, 8);
4465 OSMetaClassDefineReservedUnused(IOService
, 9);
4466 OSMetaClassDefineReservedUnused(IOService
, 10);
4467 OSMetaClassDefineReservedUnused(IOService
, 11);
4468 OSMetaClassDefineReservedUnused(IOService
, 12);
4469 OSMetaClassDefineReservedUnused(IOService
, 13);
4470 OSMetaClassDefineReservedUnused(IOService
, 14);
4471 OSMetaClassDefineReservedUnused(IOService
, 15);
4472 OSMetaClassDefineReservedUnused(IOService
, 16);
4473 OSMetaClassDefineReservedUnused(IOService
, 17);
4474 OSMetaClassDefineReservedUnused(IOService
, 18);
4475 OSMetaClassDefineReservedUnused(IOService
, 19);
4476 OSMetaClassDefineReservedUnused(IOService
, 20);
4477 OSMetaClassDefineReservedUnused(IOService
, 21);
4478 OSMetaClassDefineReservedUnused(IOService
, 22);
4479 OSMetaClassDefineReservedUnused(IOService
, 23);
4480 OSMetaClassDefineReservedUnused(IOService
, 24);
4481 OSMetaClassDefineReservedUnused(IOService
, 25);
4482 OSMetaClassDefineReservedUnused(IOService
, 26);
4483 OSMetaClassDefineReservedUnused(IOService
, 27);
4484 OSMetaClassDefineReservedUnused(IOService
, 28);
4485 OSMetaClassDefineReservedUnused(IOService
, 29);
4486 OSMetaClassDefineReservedUnused(IOService
, 30);
4487 OSMetaClassDefineReservedUnused(IOService
, 31);
4488 OSMetaClassDefineReservedUnused(IOService
, 32);
4489 OSMetaClassDefineReservedUnused(IOService
, 33);
4490 OSMetaClassDefineReservedUnused(IOService
, 34);
4491 OSMetaClassDefineReservedUnused(IOService
, 35);
4492 OSMetaClassDefineReservedUnused(IOService
, 36);
4493 OSMetaClassDefineReservedUnused(IOService
, 37);
4494 OSMetaClassDefineReservedUnused(IOService
, 38);
4495 OSMetaClassDefineReservedUnused(IOService
, 39);
4496 OSMetaClassDefineReservedUnused(IOService
, 40);
4497 OSMetaClassDefineReservedUnused(IOService
, 41);
4498 OSMetaClassDefineReservedUnused(IOService
, 42);
4499 OSMetaClassDefineReservedUnused(IOService
, 43);
4500 OSMetaClassDefineReservedUnused(IOService
, 44);
4501 OSMetaClassDefineReservedUnused(IOService
, 45);
4502 OSMetaClassDefineReservedUnused(IOService
, 46);
4503 OSMetaClassDefineReservedUnused(IOService
, 47);
4504 OSMetaClassDefineReservedUnused(IOService
, 48);
4505 OSMetaClassDefineReservedUnused(IOService
, 49);
4506 OSMetaClassDefineReservedUnused(IOService
, 50);
4507 OSMetaClassDefineReservedUnused(IOService
, 51);
4508 OSMetaClassDefineReservedUnused(IOService
, 52);
4509 OSMetaClassDefineReservedUnused(IOService
, 53);
4510 OSMetaClassDefineReservedUnused(IOService
, 54);
4511 OSMetaClassDefineReservedUnused(IOService
, 55);
4512 OSMetaClassDefineReservedUnused(IOService
, 56);
4513 OSMetaClassDefineReservedUnused(IOService
, 57);
4514 OSMetaClassDefineReservedUnused(IOService
, 58);
4515 OSMetaClassDefineReservedUnused(IOService
, 59);
4516 OSMetaClassDefineReservedUnused(IOService
, 60);
4517 OSMetaClassDefineReservedUnused(IOService
, 61);
4518 OSMetaClassDefineReservedUnused(IOService
, 62);
4519 OSMetaClassDefineReservedUnused(IOService
, 63);