]>
git.saurik.com Git - apple/xnu.git/blob - iokit/Kernel/IOWorkLoop.cpp
157bdd976318b0a63c773146f9912a8d6f8da34d
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/IOCommandPool.h>
35 #include <IOKit/IOTimeStamp.h>
36 #include <IOKit/IOKitDebug.h>
37 #include <libkern/OSDebug.h>
38 #include <kern/thread.h>
40 #define super OSObject
42 OSDefineMetaClassAndStructors(IOWorkLoop
, OSObject
);
44 // Block of unused functions intended for future use
46 OSMetaClassDefineReservedUnused(IOWorkLoop
, 0);
47 OSMetaClassDefineReservedUnused(IOWorkLoop
, 1);
48 OSMetaClassDefineReservedUnused(IOWorkLoop
, 2);
50 OSMetaClassDefineReservedUsed(IOWorkLoop
, 0);
51 OSMetaClassDefineReservedUsed(IOWorkLoop
, 1);
52 OSMetaClassDefineReservedUsed(IOWorkLoop
, 2);
54 OSMetaClassDefineReservedUnused(IOWorkLoop
, 3);
55 OSMetaClassDefineReservedUnused(IOWorkLoop
, 4);
56 OSMetaClassDefineReservedUnused(IOWorkLoop
, 5);
57 OSMetaClassDefineReservedUnused(IOWorkLoop
, 6);
58 OSMetaClassDefineReservedUnused(IOWorkLoop
, 7);
60 enum IOWorkLoopState
{ kLoopRestart
= 0x1, kLoopTerminate
= 0x2 };
61 static inline void SETP(void *addr
, unsigned int flag
)
62 { unsigned char *num
= (unsigned char *) addr
; *num
|= flag
; }
63 static inline void CLRP(void *addr
, unsigned int flag
)
64 { unsigned char *num
= (unsigned char *) addr
; *num
&= ~flag
; }
65 static inline bool ISSETP(void *addr
, unsigned int flag
)
66 { unsigned char *num
= (unsigned char *) addr
; return (*num
& flag
) != 0; }
68 #define fFlags loopRestart
70 #define passiveEventChain reserved->passiveEventChain
74 #define IOStatisticsRegisterCounter() \
76 reserved->counter = IOStatistics::registerWorkLoop(this); \
79 #define IOStatisticsUnregisterCounter() \
82 IOStatistics::unregisterWorkLoop(reserved->counter); \
85 #define IOStatisticsOpenGate() \
87 IOStatistics::countWorkLoopOpenGate(reserved->counter); \
88 if (reserved->lockInterval) lockTime(); \
90 #define IOStatisticsCloseGate() \
92 IOStatistics::countWorkLoopCloseGate(reserved->counter); \
93 if (reserved->lockInterval) reserved->lockTime = mach_absolute_time(); \
96 #define IOStatisticsAttachEventSource() \
98 IOStatistics::attachWorkLoopEventSource(reserved->counter, inEvent->reserved->counter); \
101 #define IOStatisticsDetachEventSource() \
103 IOStatistics::detachWorkLoopEventSource(reserved->counter, inEvent->reserved->counter); \
108 #define IOStatisticsRegisterCounter()
109 #define IOStatisticsUnregisterCounter()
110 #define IOStatisticsOpenGate()
111 #define IOStatisticsCloseGate()
112 #define IOStatisticsAttachEventSource()
113 #define IOStatisticsDetachEventSource()
115 #endif /* IOKITSTATS */
117 bool IOWorkLoop::init()
119 // The super init and gateLock allocation MUST be done first.
120 if ( !super::init() )
123 // Allocate our ExpansionData if it hasn't been allocated already.
126 reserved
= IONew(ExpansionData
,1);
130 bzero(reserved
,sizeof(ExpansionData
));
134 OSBacktrace ( reserved
->allocationBacktrace
, sizeof ( reserved
->allocationBacktrace
) / sizeof ( reserved
->allocationBacktrace
[0] ) );
137 if ( gateLock
== NULL
) {
138 if ( !( gateLock
= IORecursiveLockAlloc()) )
142 if ( workToDoLock
== NULL
) {
143 if ( !(workToDoLock
= IOSimpleLockAlloc()) )
145 IOSimpleLockInit(workToDoLock
);
149 IOStatisticsRegisterCounter();
151 if ( controlG
== NULL
) {
152 controlG
= IOCommandGate::commandGate(
154 OSMemberFunctionCast(
155 IOCommandGate::Action
,
157 &IOWorkLoop::_maintRequest
));
161 // Point the controlGate at the workLoop. Usually addEventSource
162 // does this automatically. The problem is in this case addEventSource
163 // uses the control gate and it has to be bootstrapped.
164 controlG
->setWorkLoop(this);
165 if (addEventSource(controlG
) != kIOReturnSuccess
)
169 if ( workThread
== NULL
) {
170 thread_continue_t cptr
= OSMemberFunctionCast(
173 &IOWorkLoop::threadMain
);
174 if (KERN_SUCCESS
!= kernel_thread_start(cptr
, this, &workThread
))
178 (void) thread_set_tag(workThread
, THREAD_TAG_IOWORKLOOP
);
183 IOWorkLoop::workLoop()
185 return IOWorkLoop::workLoopWithOptions(0);
189 IOWorkLoop::workLoopWithOptions(IOOptionBits options
)
191 IOWorkLoop
*me
= new IOWorkLoop
;
194 me
->reserved
= IONew(ExpansionData
,1);
199 bzero(me
->reserved
,sizeof(ExpansionData
));
200 me
->reserved
->options
= options
;
203 if (me
&& !me
->init()) {
211 // Free is called twice:
212 // First when the atomic retainCount transitions from 1 -> 0
213 // Secondly when the work loop itself is commiting hari kari
214 // Hence the each leg of the free must be single threaded.
215 void IOWorkLoop::free()
220 // If we are here then we must be trying to shut down this work loop
221 // in this case disable all of the event source, mark the loop
222 // as terminating and wakeup the work thread itself and return
223 // Note: we hold the gate across the entire operation mainly for the
224 // benefit of our event sources so we can disable them cleanly.
227 disableAllEventSources();
229 is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
230 SETP(&fFlags
, kLoopTerminate
);
231 thread_wakeup_one((void *) &workToDo
);
232 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
236 else /* !workThread */ {
237 IOEventSource
*event
, *next
;
239 for (event
= eventChain
; event
; event
= next
) {
240 next
= event
->getNext();
241 event
->setWorkLoop(0);
247 for (event
= passiveEventChain
; event
; event
= next
) {
248 next
= event
->getNext();
249 event
->setWorkLoop(0);
253 passiveEventChain
= 0;
255 // Either we have a partial initialization to clean up
256 // or the workThread itself is performing hari-kari.
257 // Either way clean up all of our resources and return.
260 controlG
->workLoop
= 0;
266 IOSimpleLockFree(workToDoLock
);
271 IORecursiveLockFree(gateLock
);
275 IOStatisticsUnregisterCounter();
278 IODelete(reserved
, ExpansionData
, 1);
286 IOReturn
IOWorkLoop::addEventSource(IOEventSource
*newEvent
)
289 && !thread_has_thread_name(workThread
)
291 && !OSDynamicCast(IOCommandPool
, newEvent
->owner
)) {
292 thread_set_thread_name(workThread
, newEvent
->owner
->getMetaClass()->getClassName());
295 return controlG
->runCommand((void *) mAddEvent
, (void *) newEvent
);
298 IOReturn
IOWorkLoop::removeEventSource(IOEventSource
*toRemove
)
300 return controlG
->runCommand((void *) mRemoveEvent
, (void *) toRemove
);
303 void IOWorkLoop::enableAllEventSources() const
305 IOEventSource
*event
;
307 for (event
= eventChain
; event
; event
= event
->getNext())
310 for (event
= passiveEventChain
; event
; event
= event
->getNext())
314 void IOWorkLoop::disableAllEventSources() const
316 IOEventSource
*event
;
318 for (event
= eventChain
; event
; event
= event
->getNext())
321 /* NOTE: controlG is in passiveEventChain since it's an IOCommandGate */
322 for (event
= passiveEventChain
; event
; event
= event
->getNext())
323 if (event
!= controlG
) // Don't disable the control gate
327 void IOWorkLoop::enableAllInterrupts() const
329 IOEventSource
*event
;
331 for (event
= eventChain
; event
; event
= event
->getNext())
332 if (OSDynamicCast(IOInterruptEventSource
, event
))
336 void IOWorkLoop::disableAllInterrupts() const
338 IOEventSource
*event
;
340 for (event
= eventChain
; event
; event
= event
->getNext())
341 if (OSDynamicCast(IOInterruptEventSource
, event
))
346 /* virtual */ bool IOWorkLoop::runEventSources()
349 bool traceWL
= (gIOKitTrace
& kIOTraceWorkLoops
) ? true : false;
350 bool traceES
= (gIOKitTrace
& kIOTraceEventSources
) ? true : false;
353 if (ISSETP(&fFlags
, kLoopTerminate
))
357 IOTimeStampStartConstant(IODBG_WORKLOOP(IOWL_WORK
), (uintptr_t) this);
361 CLRP(&fFlags
, kLoopRestart
);
363 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
365 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
366 /* NOTE: only loop over event sources in eventChain. Bypass "passive" event sources for performance */
367 for (IOEventSource
*evnt
= eventChain
; evnt
; evnt
= evnt
->getNext()) {
370 IOTimeStampStartConstant(IODBG_WORKLOOP(IOWL_CLIENT
), (uintptr_t) this, (uintptr_t) evnt
);
372 more
|= evnt
->checkForWork();
375 IOTimeStampEndConstant(IODBG_WORKLOOP(IOWL_CLIENT
), (uintptr_t) this, (uintptr_t) evnt
);
377 if (ISSETP(&fFlags
, kLoopTerminate
))
379 else if (fFlags
& kLoopRestart
) {
389 IOTimeStampEndConstant(IODBG_WORKLOOP(IOWL_WORK
), (uintptr_t) this);
396 /* virtual */ void IOWorkLoop::threadMain()
400 if ( !runEventSources() )
403 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
404 if ( !ISSETP(&fFlags
, kLoopTerminate
) && !workToDo
) {
405 assert_wait((void *) &workToDo
, false);
406 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
407 thread_continue_t cptr
= NULL
;
408 if (!reserved
|| !(kPreciousStack
& reserved
->options
))
409 cptr
= OSMemberFunctionCast(
410 thread_continue_t
, this, &IOWorkLoop::threadMain
);
411 thread_block_parameter(cptr
, this);
416 // At this point we either have work to do or we need
417 // to commit suicide. But no matter
418 // Clear the simple lock and retore the interrupt state
419 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
423 thread_t thread
= workThread
;
424 workThread
= 0; // Say we don't have a loop and free ourselves
427 thread_deallocate(thread
);
428 (void) thread_terminate(thread
);
431 IOThread
IOWorkLoop::getThread() const
436 bool IOWorkLoop::onThread() const
438 return (IOThreadSelf() == workThread
);
441 bool IOWorkLoop::inGate() const
443 return IORecursiveLockHaveLock(gateLock
);
446 // Internal APIs used by event sources to control the thread
447 void IOWorkLoop::signalWorkAvailable()
450 IOInterruptState is
= IOSimpleLockLockDisableInterrupt(workToDoLock
);
452 thread_wakeup_one((void *) &workToDo
);
453 IOSimpleLockUnlockEnableInterrupt(workToDoLock
, is
);
457 void IOWorkLoop::openGate()
459 IOStatisticsOpenGate();
460 IORecursiveLockUnlock(gateLock
);
463 void IOWorkLoop::closeGate()
465 IORecursiveLockLock(gateLock
);
466 IOStatisticsCloseGate();
469 bool IOWorkLoop::tryCloseGate()
471 bool res
= (IORecursiveLockTryLock(gateLock
) != 0);
473 IOStatisticsCloseGate();
478 int IOWorkLoop::sleepGate(void *event
, UInt32 interuptibleType
)
481 IOStatisticsOpenGate();
482 res
= IORecursiveLockSleep(gateLock
, event
, interuptibleType
);
483 IOStatisticsCloseGate();
487 int IOWorkLoop::sleepGate(void *event
, AbsoluteTime deadline
, UInt32 interuptibleType
)
490 IOStatisticsOpenGate();
491 res
= IORecursiveLockSleepDeadline(gateLock
, event
, deadline
, interuptibleType
);
492 IOStatisticsCloseGate();
496 void IOWorkLoop::wakeupGate(void *event
, bool oneThread
)
498 IORecursiveLockWakeup(gateLock
, event
, oneThread
);
501 IOReturn
IOWorkLoop::runAction(Action inAction
, OSObject
*target
,
502 void *arg0
, void *arg1
,
503 void *arg2
, void *arg3
)
507 // closeGate is recursive so don't worry if we already hold the lock.
509 res
= (*inAction
)(target
, arg0
, arg1
, arg2
, arg3
);
515 IOReturn
IOWorkLoop::_maintRequest(void *inC
, void *inD
, void *, void *)
517 maintCommandEnum command
= (maintCommandEnum
) (uintptr_t) inC
;
518 IOEventSource
*inEvent
= (IOEventSource
*) inD
;
519 IOReturn res
= kIOReturnSuccess
;
524 if (!inEvent
->getWorkLoop()) {
525 SETP(&fFlags
, kLoopRestart
);
528 inEvent
->setWorkLoop(this);
531 /* Check if this is a passive or active event source being added */
532 if (eventSourcePerformsWork(inEvent
)) {
535 eventChain
= inEvent
;
537 IOEventSource
*event
, *next
;
539 for (event
= eventChain
; (next
= event
->getNext()); event
= next
)
541 event
->setNext(inEvent
);
548 if (!passiveEventChain
)
549 passiveEventChain
= inEvent
;
551 IOEventSource
*event
, *next
;
553 for (event
= passiveEventChain
; (next
= event
->getNext()); event
= next
)
555 event
->setNext(inEvent
);
560 IOStatisticsAttachEventSource();
565 if (inEvent
->getWorkLoop()) {
566 IOStatisticsDetachEventSource();
568 if (eventSourcePerformsWork(inEvent
)) {
569 if (eventChain
== inEvent
)
570 eventChain
= inEvent
->getNext();
572 IOEventSource
*event
, *next
= 0;
575 if (event
) while ((next
= event
->getNext()) && (next
!= inEvent
))
579 res
= kIOReturnBadArgument
;
582 event
->setNext(inEvent
->getNext());
586 if (passiveEventChain
== inEvent
)
587 passiveEventChain
= inEvent
->getNext();
589 IOEventSource
*event
, *next
= 0;
591 event
= passiveEventChain
;
592 if (event
) while ((next
= event
->getNext()) && (next
!= inEvent
))
596 res
= kIOReturnBadArgument
;
599 event
->setNext(inEvent
->getNext());
603 inEvent
->setWorkLoop(0);
606 SETP(&fFlags
, kLoopRestart
);
611 return kIOReturnUnsupported
;
618 IOWorkLoop::eventSourcePerformsWork(IOEventSource
*inEventSource
)
623 * The idea here is to see if the subclass of IOEventSource has overridden checkForWork().
624 * The assumption is that if you override checkForWork(), you need to be
625 * active and not passive.
627 * We picked a known quantity controlG that does not override
628 * IOEventSource::checkForWork(), namely the IOCommandGate associated with
629 * the workloop to which this event source is getting attached.
631 * We do a pointer comparison on the offset in the vtable for inNewEvent against
632 * the offset in the vtable for inReferenceEvent. This works because
633 * IOCommandGate's slot for checkForWork() has the address of
634 * IOEventSource::checkForWork() in it.
636 * Think of OSMemberFunctionCast yielding the value at the vtable offset for
637 * checkForWork() here. We're just testing to see if it's the same or not.
644 ptr1
= OSMemberFunctionCast(void*, inEventSource
, &IOEventSource::checkForWork
);
645 ptr2
= OSMemberFunctionCast(void*, controlG
, &IOEventSource::checkForWork
);
655 IOWorkLoop::lockTime(void)
658 time
= mach_absolute_time() - reserved
->lockTime
;
659 if (time
> reserved
->lockInterval
)
661 absolutetime_to_nanoseconds(time
, &time
);
662 if (kTimeLockPanics
& reserved
->options
) panic("IOWorkLoop %p lock time %qd us", this, time
/ 1000ULL);
663 else OSReportWithBacktrace("IOWorkLoop %p lock time %qd us", this, time
/ 1000ULL);
668 IOWorkLoop::setMaximumLockTime(uint64_t interval
, uint32_t options
)
670 IORecursiveLockLock(gateLock
);
671 reserved
->lockInterval
= interval
;
672 reserved
->options
= (reserved
->options
& ~kTimeLockPanics
) | (options
& kTimeLockPanics
);
673 IORecursiveLockUnlock(gateLock
);