]>
git.saurik.com Git - apple/xnu.git/blob - iokit/Kernel/IOWorkLoop.cpp
2 * Copyright (c) 1998-2010 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 #include <pexpert/pexpert.h>
30 #include <IOKit/IOWorkLoop.h>
31 #include <IOKit/IOEventSource.h>
32 #include <IOKit/IOInterruptEventSource.h>
33 #include <IOKit/IOCommandGate.h>
34 #include <IOKit/IOTimeStamp.h>
35 #include <IOKit/IOKitDebug.h>
36 #include <libkern/OSDebug.h>
38 #define super OSObject
40 OSDefineMetaClassAndStructors(IOWorkLoop
, OSObject
);
42 // Block of unused functions intended for future use
44 OSMetaClassDefineReservedUnused(IOWorkLoop
, 0);
45 OSMetaClassDefineReservedUnused(IOWorkLoop
, 1);
46 OSMetaClassDefineReservedUnused(IOWorkLoop
, 2);
48 OSMetaClassDefineReservedUsed(IOWorkLoop
, 0);
49 OSMetaClassDefineReservedUsed(IOWorkLoop
, 1);
50 OSMetaClassDefineReservedUsed(IOWorkLoop
, 2);
52 OSMetaClassDefineReservedUnused(IOWorkLoop
, 3);
53 OSMetaClassDefineReservedUnused(IOWorkLoop
, 4);
54 OSMetaClassDefineReservedUnused(IOWorkLoop
, 5);
55 OSMetaClassDefineReservedUnused(IOWorkLoop
, 6);
56 OSMetaClassDefineReservedUnused(IOWorkLoop
, 7);
58 enum IOWorkLoopState
{ kLoopRestart
= 0x1, kLoopTerminate
= 0x2 };
59 static inline void SETP(void *addr
, unsigned int flag
)
60 { unsigned char *num
= (unsigned char *) addr
; *num
|= flag
; }
61 static inline void CLRP(void *addr
, unsigned int flag
)
62 { unsigned char *num
= (unsigned char *) addr
; *num
&= ~flag
; }
63 static inline bool ISSETP(void *addr
, unsigned int flag
)
64 { unsigned char *num
= (unsigned char *) addr
; return (*num
& flag
) != 0; }
66 #define fFlags loopRestart
68 #define passiveEventChain reserved->passiveEventChain
72 #define IOStatisticsRegisterCounter() \
74 reserved->counter = IOStatistics::registerWorkLoop(this); \
77 #define IOStatisticsUnregisterCounter() \
80 IOStatistics::unregisterWorkLoop(reserved->counter); \
83 #define IOStatisticsOpenGate() \
85 IOStatistics::countWorkLoopOpenGate(reserved->counter); \
88 #define IOStatisticsCloseGate() \
90 IOStatistics::countWorkLoopCloseGate(reserved->counter); \
93 #define IOStatisticsAttachEventSource() \
95 IOStatistics::attachWorkLoopEventSource(reserved->counter, inEvent->reserved->counter); \
98 #define IOStatisticsDetachEventSource() \
100 IOStatistics::detachWorkLoopEventSource(reserved->counter, inEvent->reserved->counter); \
105 #define IOStatisticsRegisterCounter()
106 #define IOStatisticsUnregisterCounter()
107 #define IOStatisticsOpenGate()
108 #define IOStatisticsCloseGate()
109 #define IOStatisticsAttachEventSource()
110 #define IOStatisticsDetachEventSource()
112 #endif /* IOKITSTATS */
114 bool IOWorkLoop::init()
116 // The super init and gateLock allocation MUST be done first.
117 if ( !super::init() )
120 // Allocate our ExpansionData if it hasn't been allocated already.
123 reserved
= IONew(ExpansionData
,1);
127 bzero(reserved
,sizeof(ExpansionData
));
131 OSBacktrace ( reserved
->allocationBacktrace
, sizeof ( reserved
->allocationBacktrace
) / sizeof ( reserved
->allocationBacktrace
[0] ) );
134 if ( gateLock
== NULL
) {
135 if ( !( gateLock
= IORecursiveLockAlloc()) )
139 if ( workToDoLock
== NULL
) {
140 if ( !(workToDoLock
= IOSimpleLockAlloc()) )
142 IOSimpleLockInit(workToDoLock
);
147 reserved
= IONew(ExpansionData
, 1);
148 reserved
->options
= 0;
151 IOStatisticsRegisterCounter();
153 if ( controlG
== NULL
) {
154 controlG
= IOCommandGate::commandGate(
156 OSMemberFunctionCast(
157 IOCommandGate::Action
,
159 &IOWorkLoop::_maintRequest
));
163 // Point the controlGate at the workLoop. Usually addEventSource
164 // does this automatically. The problem is in this case addEventSource
165 // uses the control gate and it has to be bootstrapped.
166 controlG
->setWorkLoop(this);
167 if (addEventSource(controlG
) != kIOReturnSuccess
)
171 if ( workThread
== NULL
) {
172 thread_continue_t cptr
= OSMemberFunctionCast(
175 &IOWorkLoop::threadMain
);
176 if (KERN_SUCCESS
!= kernel_thread_start(cptr
, this, &workThread
))
184 IOWorkLoop::workLoop()
186 return IOWorkLoop::workLoopWithOptions(0);
190 IOWorkLoop::workLoopWithOptions(IOOptionBits options
)
192 IOWorkLoop
*me
= new IOWorkLoop
;
195 me
->reserved
= IONew(ExpansionData
,1);
200 bzero(me
->reserved
,sizeof(ExpansionData
));
201 me
->reserved
->options
= options
;
204 if (me
&& !me
->init()) {
212 // Free is called twice:
213 // First when the atomic retainCount transitions from 1 -> 0
214 // Secondly when the work loop itself is commiting hari kari
215 // Hence the each leg of the free must be single threaded.
216 void IOWorkLoop::free()
221 // If we are here then we must be trying to shut down this work loop
222 // in this case disable all of the event source, mark the loop
223 // as terminating and wakeup the work thread itself and return
224 // Note: we hold the gate across the entire operation mainly for the
225 // benefit of our event sources so we can disable them cleanly.
228 disableAllEventSources();
230 is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
231 SETP(&fFlags
, kLoopTerminate
);
232 thread_wakeup_one((void *) &workToDo
);
233 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
237 else /* !workThread */ {
238 IOEventSource
*event
, *next
;
240 for (event
= eventChain
; event
; event
= next
) {
241 next
= event
->getNext();
242 event
->setWorkLoop(0);
248 for (event
= passiveEventChain
; event
; event
= next
) {
249 next
= event
->getNext();
250 event
->setWorkLoop(0);
254 passiveEventChain
= 0;
256 // Either we have a partial initialization to clean up
257 // or the workThread itself is performing hari-kari.
258 // Either way clean up all of our resources and return.
266 IOSimpleLockFree(workToDoLock
);
271 IORecursiveLockFree(gateLock
);
275 IOStatisticsUnregisterCounter();
278 IODelete(reserved
, ExpansionData
, 1);
286 IOReturn
IOWorkLoop::addEventSource(IOEventSource
*newEvent
)
288 return controlG
->runCommand((void *) mAddEvent
, (void *) newEvent
);
291 IOReturn
IOWorkLoop::removeEventSource(IOEventSource
*toRemove
)
293 return controlG
->runCommand((void *) mRemoveEvent
, (void *) toRemove
);
296 void IOWorkLoop::enableAllEventSources() const
298 IOEventSource
*event
;
300 for (event
= eventChain
; event
; event
= event
->getNext())
303 for (event
= passiveEventChain
; event
; event
= event
->getNext())
307 void IOWorkLoop::disableAllEventSources() const
309 IOEventSource
*event
;
311 for (event
= eventChain
; event
; event
= event
->getNext())
314 /* NOTE: controlG is in passiveEventChain since it's an IOCommandGate */
315 for (event
= passiveEventChain
; event
; event
= event
->getNext())
316 if (event
!= controlG
) // Don't disable the control gate
320 void IOWorkLoop::enableAllInterrupts() const
322 IOEventSource
*event
;
324 for (event
= eventChain
; event
; event
= event
->getNext())
325 if (OSDynamicCast(IOInterruptEventSource
, event
))
329 void IOWorkLoop::disableAllInterrupts() const
331 IOEventSource
*event
;
333 for (event
= eventChain
; event
; event
= event
->getNext())
334 if (OSDynamicCast(IOInterruptEventSource
, event
))
339 /* virtual */ bool IOWorkLoop::runEventSources()
342 bool traceWL
= (gIOKitTrace
& kIOTraceWorkLoops
) ? true : false;
343 bool traceES
= (gIOKitTrace
& kIOTraceEventSources
) ? true : false;
346 if (ISSETP(&fFlags
, kLoopTerminate
))
350 IOTimeStampStartConstant(IODBG_WORKLOOP(IOWL_WORK
), (uintptr_t) this);
354 CLRP(&fFlags
, kLoopRestart
);
356 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
358 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
359 /* NOTE: only loop over event sources in eventChain. Bypass "passive" event sources for performance */
360 for (IOEventSource
*evnt
= eventChain
; evnt
; evnt
= evnt
->getNext()) {
363 IOTimeStampStartConstant(IODBG_WORKLOOP(IOWL_CLIENT
), (uintptr_t) this, (uintptr_t) evnt
);
365 more
|= evnt
->checkForWork();
368 IOTimeStampEndConstant(IODBG_WORKLOOP(IOWL_CLIENT
), (uintptr_t) this, (uintptr_t) evnt
);
370 if (ISSETP(&fFlags
, kLoopTerminate
))
372 else if (fFlags
& kLoopRestart
) {
382 IOTimeStampEndConstant(IODBG_WORKLOOP(IOWL_WORK
), (uintptr_t) this);
389 /* virtual */ void IOWorkLoop::threadMain()
393 if ( !runEventSources() )
396 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
397 if ( !ISSETP(&fFlags
, kLoopTerminate
) && !workToDo
) {
398 assert_wait((void *) &workToDo
, false);
399 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
400 thread_continue_t cptr
= NULL
;
401 if (!reserved
|| !(kPreciousStack
& reserved
->options
))
402 cptr
= OSMemberFunctionCast(
403 thread_continue_t
, this, &IOWorkLoop::threadMain
);
404 thread_block_parameter(cptr
, this);
409 // At this point we either have work to do or we need
410 // to commit suicide. But no matter
411 // Clear the simple lock and retore the interrupt state
412 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
416 thread_t thread
= workThread
;
417 workThread
= 0; // Say we don't have a loop and free ourselves
420 thread_deallocate(thread
);
421 (void) thread_terminate(thread
);
424 IOThread
IOWorkLoop::getThread() const
429 bool IOWorkLoop::onThread() const
431 return (IOThreadSelf() == workThread
);
434 bool IOWorkLoop::inGate() const
436 return IORecursiveLockHaveLock(gateLock
);
439 // Internal APIs used by event sources to control the thread
440 void IOWorkLoop::signalWorkAvailable()
443 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
445 thread_wakeup_one((void *) &workToDo
);
446 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
450 void IOWorkLoop::openGate()
452 IOStatisticsOpenGate();
453 IORecursiveLockUnlock(gateLock
);
456 void IOWorkLoop::closeGate()
458 IORecursiveLockLock(gateLock
);
459 IOStatisticsCloseGate();
462 bool IOWorkLoop::tryCloseGate()
464 bool res
= (IORecursiveLockTryLock(gateLock
) != 0);
466 IOStatisticsCloseGate();
471 int IOWorkLoop::sleepGate(void *event
, UInt32 interuptibleType
)
474 IOStatisticsOpenGate();
475 res
= IORecursiveLockSleep(gateLock
, event
, interuptibleType
);
476 IOStatisticsCloseGate();
480 int IOWorkLoop::sleepGate(void *event
, AbsoluteTime deadline
, UInt32 interuptibleType
)
483 IOStatisticsOpenGate();
484 res
= IORecursiveLockSleepDeadline(gateLock
, event
, deadline
, interuptibleType
);
485 IOStatisticsCloseGate();
489 void IOWorkLoop::wakeupGate(void *event
, bool oneThread
)
491 IORecursiveLockWakeup(gateLock
, event
, oneThread
);
494 IOReturn
IOWorkLoop::runAction(Action inAction
, OSObject
*target
,
495 void *arg0
, void *arg1
,
496 void *arg2
, void *arg3
)
500 // closeGate is recursive so don't worry if we already hold the lock.
502 res
= (*inAction
)(target
, arg0
, arg1
, arg2
, arg3
);
508 IOReturn
IOWorkLoop::_maintRequest(void *inC
, void *inD
, void *, void *)
510 maintCommandEnum command
= (maintCommandEnum
) (uintptr_t) inC
;
511 IOEventSource
*inEvent
= (IOEventSource
*) inD
;
512 IOReturn res
= kIOReturnSuccess
;
517 if (!inEvent
->getWorkLoop()) {
518 SETP(&fFlags
, kLoopRestart
);
521 inEvent
->setWorkLoop(this);
524 /* Check if this is a passive or active event source being added */
525 if (eventSourcePerformsWork(inEvent
)) {
528 eventChain
= inEvent
;
530 IOEventSource
*event
, *next
;
532 for (event
= eventChain
; (next
= event
->getNext()); event
= next
)
534 event
->setNext(inEvent
);
541 if (!passiveEventChain
)
542 passiveEventChain
= inEvent
;
544 IOEventSource
*event
, *next
;
546 for (event
= passiveEventChain
; (next
= event
->getNext()); event
= next
)
548 event
->setNext(inEvent
);
553 IOStatisticsAttachEventSource();
558 if (inEvent
->getWorkLoop()) {
559 IOStatisticsDetachEventSource();
561 if (eventSourcePerformsWork(inEvent
)) {
562 if (eventChain
== inEvent
)
563 eventChain
= inEvent
->getNext();
565 IOEventSource
*event
, *next
;
568 while ((next
= event
->getNext()) && next
!= inEvent
)
572 res
= kIOReturnBadArgument
;
575 event
->setNext(inEvent
->getNext());
579 if (passiveEventChain
== inEvent
)
580 passiveEventChain
= inEvent
->getNext();
582 IOEventSource
*event
, *next
;
584 event
= passiveEventChain
;
585 while ((next
= event
->getNext()) && next
!= inEvent
)
589 res
= kIOReturnBadArgument
;
592 event
->setNext(inEvent
->getNext());
596 inEvent
->setWorkLoop(0);
599 SETP(&fFlags
, kLoopRestart
);
604 return kIOReturnUnsupported
;
611 IOWorkLoop::eventSourcePerformsWork(IOEventSource
*inEventSource
)
616 * The idea here is to see if the subclass of IOEventSource has overridden checkForWork().
617 * The assumption is that if you override checkForWork(), you need to be
618 * active and not passive.
620 * We picked a known quantity controlG that does not override
621 * IOEventSource::checkForWork(), namely the IOCommandGate associated with
622 * the workloop to which this event source is getting attached.
624 * We do a pointer comparison on the offset in the vtable for inNewEvent against
625 * the offset in the vtable for inReferenceEvent. This works because
626 * IOCommandGate's slot for checkForWork() has the address of
627 * IOEventSource::checkForWork() in it.
629 * Think of OSMemberFunctionCast yielding the value at the vtable offset for
630 * checkForWork() here. We're just testing to see if it's the same or not.
637 ptr1
= OSMemberFunctionCast(void*, inEventSource
, &IOEventSource::checkForWork
);
638 ptr2
= OSMemberFunctionCast(void*, controlG
, &IOEventSource::checkForWork
);