]>
git.saurik.com Git - apple/xnu.git/blob - iokit/Kernel/IOWorkLoop.cpp
0789f66bb4baf299359bf97ef220eaa319e61492
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>
37 #include <kern/thread.h>
39 #define super OSObject
41 OSDefineMetaClassAndStructors(IOWorkLoop
, OSObject
);
43 // Block of unused functions intended for future use
45 OSMetaClassDefineReservedUnused(IOWorkLoop
, 0);
46 OSMetaClassDefineReservedUnused(IOWorkLoop
, 1);
47 OSMetaClassDefineReservedUnused(IOWorkLoop
, 2);
49 OSMetaClassDefineReservedUsed(IOWorkLoop
, 0);
50 OSMetaClassDefineReservedUsed(IOWorkLoop
, 1);
51 OSMetaClassDefineReservedUsed(IOWorkLoop
, 2);
53 OSMetaClassDefineReservedUnused(IOWorkLoop
, 3);
54 OSMetaClassDefineReservedUnused(IOWorkLoop
, 4);
55 OSMetaClassDefineReservedUnused(IOWorkLoop
, 5);
56 OSMetaClassDefineReservedUnused(IOWorkLoop
, 6);
57 OSMetaClassDefineReservedUnused(IOWorkLoop
, 7);
59 enum IOWorkLoopState
{ kLoopRestart
= 0x1, kLoopTerminate
= 0x2 };
60 static inline void SETP(void *addr
, unsigned int flag
)
61 { unsigned char *num
= (unsigned char *) addr
; *num
|= flag
; }
62 static inline void CLRP(void *addr
, unsigned int flag
)
63 { unsigned char *num
= (unsigned char *) addr
; *num
&= ~flag
; }
64 static inline bool ISSETP(void *addr
, unsigned int flag
)
65 { unsigned char *num
= (unsigned char *) addr
; return (*num
& flag
) != 0; }
67 #define fFlags loopRestart
69 #define passiveEventChain reserved->passiveEventChain
73 #define IOStatisticsRegisterCounter() \
75 reserved->counter = IOStatistics::registerWorkLoop(this); \
78 #define IOStatisticsUnregisterCounter() \
81 IOStatistics::unregisterWorkLoop(reserved->counter); \
84 #define IOStatisticsOpenGate() \
86 IOStatistics::countWorkLoopOpenGate(reserved->counter); \
89 #define IOStatisticsCloseGate() \
91 IOStatistics::countWorkLoopCloseGate(reserved->counter); \
94 #define IOStatisticsAttachEventSource() \
96 IOStatistics::attachWorkLoopEventSource(reserved->counter, inEvent->reserved->counter); \
99 #define IOStatisticsDetachEventSource() \
101 IOStatistics::detachWorkLoopEventSource(reserved->counter, inEvent->reserved->counter); \
106 #define IOStatisticsRegisterCounter()
107 #define IOStatisticsUnregisterCounter()
108 #define IOStatisticsOpenGate()
109 #define IOStatisticsCloseGate()
110 #define IOStatisticsAttachEventSource()
111 #define IOStatisticsDetachEventSource()
113 #endif /* IOKITSTATS */
115 bool IOWorkLoop::init()
117 // The super init and gateLock allocation MUST be done first.
118 if ( !super::init() )
121 // Allocate our ExpansionData if it hasn't been allocated already.
124 reserved
= IONew(ExpansionData
,1);
128 bzero(reserved
,sizeof(ExpansionData
));
132 OSBacktrace ( reserved
->allocationBacktrace
, sizeof ( reserved
->allocationBacktrace
) / sizeof ( reserved
->allocationBacktrace
[0] ) );
135 if ( gateLock
== NULL
) {
136 if ( !( gateLock
= IORecursiveLockAlloc()) )
140 if ( workToDoLock
== NULL
) {
141 if ( !(workToDoLock
= IOSimpleLockAlloc()) )
143 IOSimpleLockInit(workToDoLock
);
147 IOStatisticsRegisterCounter();
149 if ( controlG
== NULL
) {
150 controlG
= IOCommandGate::commandGate(
152 OSMemberFunctionCast(
153 IOCommandGate::Action
,
155 &IOWorkLoop::_maintRequest
));
159 // Point the controlGate at the workLoop. Usually addEventSource
160 // does this automatically. The problem is in this case addEventSource
161 // uses the control gate and it has to be bootstrapped.
162 controlG
->setWorkLoop(this);
163 if (addEventSource(controlG
) != kIOReturnSuccess
)
167 if ( workThread
== NULL
) {
168 thread_continue_t cptr
= OSMemberFunctionCast(
171 &IOWorkLoop::threadMain
);
172 if (KERN_SUCCESS
!= kernel_thread_start(cptr
, this, &workThread
))
176 (void) thread_set_tag(workThread
, THREAD_TAG_IOWORKLOOP
);
181 IOWorkLoop::workLoop()
183 return IOWorkLoop::workLoopWithOptions(0);
187 IOWorkLoop::workLoopWithOptions(IOOptionBits options
)
189 IOWorkLoop
*me
= new IOWorkLoop
;
192 me
->reserved
= IONew(ExpansionData
,1);
197 bzero(me
->reserved
,sizeof(ExpansionData
));
198 me
->reserved
->options
= options
;
201 if (me
&& !me
->init()) {
209 // Free is called twice:
210 // First when the atomic retainCount transitions from 1 -> 0
211 // Secondly when the work loop itself is commiting hari kari
212 // Hence the each leg of the free must be single threaded.
213 void IOWorkLoop::free()
218 // If we are here then we must be trying to shut down this work loop
219 // in this case disable all of the event source, mark the loop
220 // as terminating and wakeup the work thread itself and return
221 // Note: we hold the gate across the entire operation mainly for the
222 // benefit of our event sources so we can disable them cleanly.
225 disableAllEventSources();
227 is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
228 SETP(&fFlags
, kLoopTerminate
);
229 thread_wakeup_one((void *) &workToDo
);
230 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
234 else /* !workThread */ {
235 IOEventSource
*event
, *next
;
237 for (event
= eventChain
; event
; event
= next
) {
238 next
= event
->getNext();
239 event
->setWorkLoop(0);
245 for (event
= passiveEventChain
; event
; event
= next
) {
246 next
= event
->getNext();
247 event
->setWorkLoop(0);
251 passiveEventChain
= 0;
253 // Either we have a partial initialization to clean up
254 // or the workThread itself is performing hari-kari.
255 // Either way clean up all of our resources and return.
263 IOSimpleLockFree(workToDoLock
);
268 IORecursiveLockFree(gateLock
);
272 IOStatisticsUnregisterCounter();
275 IODelete(reserved
, ExpansionData
, 1);
283 IOReturn
IOWorkLoop::addEventSource(IOEventSource
*newEvent
)
285 return controlG
->runCommand((void *) mAddEvent
, (void *) newEvent
);
288 IOReturn
IOWorkLoop::removeEventSource(IOEventSource
*toRemove
)
290 return controlG
->runCommand((void *) mRemoveEvent
, (void *) toRemove
);
293 void IOWorkLoop::enableAllEventSources() const
295 IOEventSource
*event
;
297 for (event
= eventChain
; event
; event
= event
->getNext())
300 for (event
= passiveEventChain
; event
; event
= event
->getNext())
304 void IOWorkLoop::disableAllEventSources() const
306 IOEventSource
*event
;
308 for (event
= eventChain
; event
; event
= event
->getNext())
311 /* NOTE: controlG is in passiveEventChain since it's an IOCommandGate */
312 for (event
= passiveEventChain
; event
; event
= event
->getNext())
313 if (event
!= controlG
) // Don't disable the control gate
317 void IOWorkLoop::enableAllInterrupts() const
319 IOEventSource
*event
;
321 for (event
= eventChain
; event
; event
= event
->getNext())
322 if (OSDynamicCast(IOInterruptEventSource
, event
))
326 void IOWorkLoop::disableAllInterrupts() const
328 IOEventSource
*event
;
330 for (event
= eventChain
; event
; event
= event
->getNext())
331 if (OSDynamicCast(IOInterruptEventSource
, event
))
336 /* virtual */ bool IOWorkLoop::runEventSources()
339 bool traceWL
= (gIOKitTrace
& kIOTraceWorkLoops
) ? true : false;
340 bool traceES
= (gIOKitTrace
& kIOTraceEventSources
) ? true : false;
343 if (ISSETP(&fFlags
, kLoopTerminate
))
347 IOTimeStampStartConstant(IODBG_WORKLOOP(IOWL_WORK
), (uintptr_t) this);
351 CLRP(&fFlags
, kLoopRestart
);
353 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
355 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
356 /* NOTE: only loop over event sources in eventChain. Bypass "passive" event sources for performance */
357 for (IOEventSource
*evnt
= eventChain
; evnt
; evnt
= evnt
->getNext()) {
360 IOTimeStampStartConstant(IODBG_WORKLOOP(IOWL_CLIENT
), (uintptr_t) this, (uintptr_t) evnt
);
362 more
|= evnt
->checkForWork();
365 IOTimeStampEndConstant(IODBG_WORKLOOP(IOWL_CLIENT
), (uintptr_t) this, (uintptr_t) evnt
);
367 if (ISSETP(&fFlags
, kLoopTerminate
))
369 else if (fFlags
& kLoopRestart
) {
379 IOTimeStampEndConstant(IODBG_WORKLOOP(IOWL_WORK
), (uintptr_t) this);
386 /* virtual */ void IOWorkLoop::threadMain()
390 if ( !runEventSources() )
393 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
394 if ( !ISSETP(&fFlags
, kLoopTerminate
) && !workToDo
) {
395 assert_wait((void *) &workToDo
, false);
396 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
397 thread_continue_t cptr
= NULL
;
398 if (!reserved
|| !(kPreciousStack
& reserved
->options
))
399 cptr
= OSMemberFunctionCast(
400 thread_continue_t
, this, &IOWorkLoop::threadMain
);
401 thread_block_parameter(cptr
, this);
406 // At this point we either have work to do or we need
407 // to commit suicide. But no matter
408 // Clear the simple lock and retore the interrupt state
409 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
413 thread_t thread
= workThread
;
414 workThread
= 0; // Say we don't have a loop and free ourselves
417 thread_deallocate(thread
);
418 (void) thread_terminate(thread
);
421 IOThread
IOWorkLoop::getThread() const
426 bool IOWorkLoop::onThread() const
428 return (IOThreadSelf() == workThread
);
431 bool IOWorkLoop::inGate() const
433 return IORecursiveLockHaveLock(gateLock
);
436 // Internal APIs used by event sources to control the thread
437 void IOWorkLoop::signalWorkAvailable()
440 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
442 thread_wakeup_one((void *) &workToDo
);
443 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
447 void IOWorkLoop::openGate()
449 IOStatisticsOpenGate();
450 IORecursiveLockUnlock(gateLock
);
453 void IOWorkLoop::closeGate()
455 IORecursiveLockLock(gateLock
);
456 IOStatisticsCloseGate();
459 bool IOWorkLoop::tryCloseGate()
461 bool res
= (IORecursiveLockTryLock(gateLock
) != 0);
463 IOStatisticsCloseGate();
468 int IOWorkLoop::sleepGate(void *event
, UInt32 interuptibleType
)
471 IOStatisticsOpenGate();
472 res
= IORecursiveLockSleep(gateLock
, event
, interuptibleType
);
473 IOStatisticsCloseGate();
477 int IOWorkLoop::sleepGate(void *event
, AbsoluteTime deadline
, UInt32 interuptibleType
)
480 IOStatisticsOpenGate();
481 res
= IORecursiveLockSleepDeadline(gateLock
, event
, deadline
, interuptibleType
);
482 IOStatisticsCloseGate();
486 void IOWorkLoop::wakeupGate(void *event
, bool oneThread
)
488 IORecursiveLockWakeup(gateLock
, event
, oneThread
);
491 IOReturn
IOWorkLoop::runAction(Action inAction
, OSObject
*target
,
492 void *arg0
, void *arg1
,
493 void *arg2
, void *arg3
)
497 // closeGate is recursive so don't worry if we already hold the lock.
499 res
= (*inAction
)(target
, arg0
, arg1
, arg2
, arg3
);
505 IOReturn
IOWorkLoop::_maintRequest(void *inC
, void *inD
, void *, void *)
507 maintCommandEnum command
= (maintCommandEnum
) (uintptr_t) inC
;
508 IOEventSource
*inEvent
= (IOEventSource
*) inD
;
509 IOReturn res
= kIOReturnSuccess
;
514 if (!inEvent
->getWorkLoop()) {
515 SETP(&fFlags
, kLoopRestart
);
518 inEvent
->setWorkLoop(this);
521 /* Check if this is a passive or active event source being added */
522 if (eventSourcePerformsWork(inEvent
)) {
525 eventChain
= inEvent
;
527 IOEventSource
*event
, *next
;
529 for (event
= eventChain
; (next
= event
->getNext()); event
= next
)
531 event
->setNext(inEvent
);
538 if (!passiveEventChain
)
539 passiveEventChain
= inEvent
;
541 IOEventSource
*event
, *next
;
543 for (event
= passiveEventChain
; (next
= event
->getNext()); event
= next
)
545 event
->setNext(inEvent
);
550 IOStatisticsAttachEventSource();
555 if (inEvent
->getWorkLoop()) {
556 IOStatisticsDetachEventSource();
558 if (eventSourcePerformsWork(inEvent
)) {
559 if (eventChain
== inEvent
)
560 eventChain
= inEvent
->getNext();
562 IOEventSource
*event
, *next
;
565 while ((next
= event
->getNext()) && next
!= inEvent
)
569 res
= kIOReturnBadArgument
;
572 event
->setNext(inEvent
->getNext());
576 if (passiveEventChain
== inEvent
)
577 passiveEventChain
= inEvent
->getNext();
579 IOEventSource
*event
, *next
;
581 event
= passiveEventChain
;
582 while ((next
= event
->getNext()) && next
!= inEvent
)
586 res
= kIOReturnBadArgument
;
589 event
->setNext(inEvent
->getNext());
593 inEvent
->setWorkLoop(0);
596 SETP(&fFlags
, kLoopRestart
);
601 return kIOReturnUnsupported
;
608 IOWorkLoop::eventSourcePerformsWork(IOEventSource
*inEventSource
)
613 * The idea here is to see if the subclass of IOEventSource has overridden checkForWork().
614 * The assumption is that if you override checkForWork(), you need to be
615 * active and not passive.
617 * We picked a known quantity controlG that does not override
618 * IOEventSource::checkForWork(), namely the IOCommandGate associated with
619 * the workloop to which this event source is getting attached.
621 * We do a pointer comparison on the offset in the vtable for inNewEvent against
622 * the offset in the vtable for inReferenceEvent. This works because
623 * IOCommandGate's slot for checkForWork() has the address of
624 * IOEventSource::checkForWork() in it.
626 * Think of OSMemberFunctionCast yielding the value at the vtable offset for
627 * checkForWork() here. We're just testing to see if it's the same or not.
634 ptr1
= OSMemberFunctionCast(void*, inEventSource
, &IOEventSource::checkForWork
);
635 ptr2
= OSMemberFunctionCast(void*, controlG
, &IOEventSource::checkForWork
);