xref: /xnu-11215/iokit/IOKit/IOWorkLoop.h (revision 94d3b452)
1 /*
2  * Copyright (c) 1998-2019 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
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.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
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.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 #ifndef __IOKIT_IOWORKLOOP_H
30 #define __IOKIT_IOWORKLOOP_H
31 
32 #include <libkern/c++/OSObject.h>
33 #include <IOKit/IOReturn.h>
34 #include <IOKit/IOLib.h>
35 #include <IOKit/IOLocks.h>
36 #include <libkern/c++/OSPtr.h>
37 
38 #include <IOKit/system.h>
39 
40 #if IOKITSTATS
41 #include <IOKit/IOStatisticsPrivate.h>
42 #endif
43 
44 class IOEventSource;
45 class IOTimerEventSource;
46 class IOCommandGate;
47 #if CONFIG_EXCLAVES
48 class IOExclaveWorkLoopAperture;
49 #endif /* CONFIG_EXCLAVES */
50 
51 /*! @class IOWorkLoop
52  *   @discussion An IOWorkLoop is a thread of control that is intended to be used to provide single threaded access to hardware.  This class has no knowledge of the nature and type of the events that it marshals and forwards.  When a device driver successfully starts (see IOService::start), it is expected to create the event sources it will need to receive events.  Then a work loop is initialized and the events are added to the work loop for monitoring.  In general this set up will be automated by the family superclass of the specific device.
53  *  <br><br>
54  *       The thread main method walks the event source linked list and messages each one requesting a work check.  At this point each event source is expected to notify its registered owner that the event has occurred.  After each event has been walked and each indicates that another loop isn't required (by setting the 'more' flag to false) the thread will go to sleep on a signaling semaphore.
55  *  <br><br>
56  *       When an event source is registered with a work loop it is informed of the semaphore to use to wake up the loop.
57  */
58 class IOWorkLoop : public OSObject
59 {
60 	OSDeclareDefaultStructors(IOWorkLoop);
61 
62 public:
63 /*!
64  *   @typedef Action
65  *   @discussion Type and arguments of callout C function that is used when
66  *  a runCommand is executed by a client.  Cast to this type when you want a C++
67  *  member function to be used.  Note the arg1 - arg3 parameters are straight pass
68  *  through from the runCommand to the action callout.
69  *   @param target
70  *       Target of the function, can be used as a refcon.  Note if a C++ function
71  *  was specified, this parameter is implicitly the first parameter in the target
72  *  member function's parameter list.
73  *   @param arg0 Argument to action from run operation.
74  *   @param arg1 Argument to action from run operation.
75  *   @param arg2 Argument to action from run operation.
76  *   @param arg3 Argument to action from run operation.
77  */
78 	typedef IOReturn (*Action)(OSObject *target,
79 	    void *arg0, void *arg1,
80 	    void *arg2, void *arg3);
81 
82 #ifdef __BLOCKS__
83 	typedef IOReturn (^ActionBlock)();
84 #endif /* __BLOCKS__ */
85 
86 	enum {
87 		kPreciousStack  = 0x00000001,
88 		kTimeLockPanics = 0x00000002,
89 	};
90 
91 private:
92 /*! @function threadMainContinuation
93  *   @abstract Static function that calls the threadMain function.
94  */
95 	static void threadMainContinuation(IOWorkLoop *self);
96 
97 /*! @function eventSourcePerformsWork
98  *       @abstract Checks if the event source passed in overrides checkForWork() to perform any work.
99  *  IOWorkLoop uses this to determine if the event source should be polled in runEventSources() or not.
100  *       @param inEventSource The event source to check.
101  */
102 	bool eventSourcePerformsWork(IOEventSource *inEventSource);
103 
104 /*! @function releaseEventChain
105  *   @abstract Static function that releases the events in a chain and sets
106  *   their work loops to NULL.
107  */
108 	static void releaseEventChain(LIBKERN_CONSUMED IOEventSource *eventChain);
109 
110 protected:
111 
112 /*! @typedef maintCommandEnum
113  *   @discussion Enumeration of commands that _maintCommand can deal with.
114  *   @constant mAddEvent Used to tag a Remove event source command.
115  *   @constant mRemoveEvent Used to tag a Remove event source command.
116  */
117 	typedef enum { mAddEvent, mRemoveEvent } maintCommandEnum;
118 
119 /*! @var gateLock
120  *   Mutual exclusion lock that is used by close and open Gate functions.
121  *   This is a recursive lock, which allows multiple layers of code to share a single IOWorkLoop without deadlock.  This is common in IOKit since threads of execution tend to follow the service plane in the IORegistry, and multiple objects along the call path may acquire the gate for the same (shared) workloop.
122  */
123 	IORecursiveLock *gateLock;
124 
125 /*! @var eventChain
126  *   Pointer to first event source in linked list.
127  */
128 	IOEventSource *eventChain;
129 
130 /*! @var controlG
131  *   Internal control gate to maintain event system.
132  */
133 	IOCommandGate *controlG;
134 
135 /*! @var workToDoLock
136  *   The spin lock that is used to guard the 'workToDo' variable.
137  */
138 	IOSimpleLock *workToDoLock;
139 
140 /*! @var workThread
141  *   Work loop thread.
142  */
143 	IOThread workThread;
144 
145 /*! @var workToDo
146  *   Used to to indicate that an interrupt has fired and needs to be processed.
147  */
148 	volatile bool workToDo;
149 
150 /*! @var loopRestart
151  *   Set if an event chain has been changed and the system has to be rechecked from start.  (Internal use only)
152  */
153 	bool loopRestart;
154 
155 /*! @struct ExpansionData
156  *   @discussion This structure will be used to expand the capablilties of the IOWorkLoop in the future.
157  */
158 	struct ExpansionData {
159 		IOOptionBits options;
160 		IOEventSource *passiveEventChain;
161 #if IOKITSTATS
162 		struct IOWorkLoopCounter *counter;
163 #else
164 		void *iokitstatsReserved;
165 #endif
166 		uint64_t lockInterval;
167 		uint64_t lockTime;
168 	};
169 
170 /*! @var reserved
171  *   Reserved for future use.  (Internal use only)
172  */
173 	ExpansionData *reserved;
174 
175 /*! @function _maintRequest
176  *   @abstract Synchronous implementation of addEventSource and removeEventSource functions.
177  *   @discussion This function implements the commands as defined in the maintCommandEnum.  It can be subclassed but it isn't an external API in the usual sense.  A subclass implementation of _maintRequest would be called synchronously with respect to the work loop and it should be implemented in the usual way that an ioctl would be.
178  *   @return kIOReturnUnsupported if the command given is not implemented, kIOReturnSuccess otherwise.
179  */
180 	virtual IOReturn _maintRequest(void *command, void *data, void *, void *);
181 
182 /*! @function free
183  *   @discussion Mandatory free of the object independent of the current retain count.  If the work loop is running, this method will not return until the thread has successfully terminated.  Each event source in the chain will be released and the working semaphore will be destroyed.
184  *  <br><br>
185  *       If the client has some outstanding requests on an event they will never be informed of completion.  If an external thread is blocked on any of the event sources they will be awakened with a KERN_INTERUPTED status.
186  */
187 	virtual void free() APPLE_KEXT_OVERRIDE;
188 
189 /*! @function threadMain
190  *   @discussion Work loop threads main function.  This function consists of 3
191  *   loops: the outermost loop is the semaphore clear and wait loop, the middle
192  *   loop terminates when there is no more work, and the inside loop walks the
193  *   event list calling the checkForWork method in each event source.  If an
194  *   event source has more work to do, it can set the more flag and the middle
195  *   loop will repeat.  When no more work is outstanding the outermost will
196  *   sleep until an event is signalled.
197  */
198 	virtual void threadMain();
199 
200 public:
201 
202 /*! @function workLoop
203  *   @abstract Factory member function to construct and intialize a work loop.
204  *   @result Returns a workLoop instance if constructed successfully, 0 otherwise.
205  */
206 	static OSPtr<IOWorkLoop> workLoop();
207 
208 /*! @function workLoopWithOptions(IOOptionBits options)
209  *   @abstract Factory member function to constuct and intialize a work loop.
210  *   @param options Options - kPreciousStack to avoid stack deallocation on paging path.
211  *   @result Returns a workLoop instance if constructed successfully, 0 otherwise.
212  */
213 	static OSPtr<IOWorkLoop> workLoopWithOptions(IOOptionBits options);
214 
215 /*! @function init
216  *   @discussion Initializes an instance of the workloop.  This method creates and initializes the signaling semaphore, the controller gate lock, and spawns the thread that will continue executing.
217  *   @result Returns true if initialized successfully, false otherwise.
218  */
219 	virtual bool init() APPLE_KEXT_OVERRIDE;
220 
221 /*! @function getThread
222  *   @abstract Gets the workThread.
223  *   @result Returns workThread.
224  */
225 	virtual IOThread getThread() const;
226 
227 /*! @function onThread
228  *   @abstract Is the current execution context on the work thread?
229  *   @result Returns true if IOThreadSelf() == workThread.
230  */
231 	virtual bool onThread() const;
232 
233 /*! @function inGate
234  *   @abstract Is the current execution context holding the work-loop's gate?
235  *   @result Returns true if IOThreadSelf() is gate holder.
236  */
237 	virtual bool inGate() const;
238 
239 /*! @function addEventSource
240  *   @discussion Add an event source to be monitored by the work loop.  This function does not return until the work loop has acknowledged the arrival of the new event source.  When a new event has been added the threadMain will always restart its loop and check all outstanding events.  The event source is retained by the work loop.
241  *   @param newEvent Pointer to IOEventSource subclass to add.
242  *   @result Always returns kIOReturnSuccess.
243  */
244 	virtual IOReturn addEventSource(IOEventSource *newEvent);
245 
246 /*! @function removeEventSource
247  *   @discussion Remove an event source from the work loop.  This function does not return until the work loop has acknowledged the removal of the event source.  When an event has been removed the threadMain will always restart its loop and check all outstanding events.  The event source will be released before return.
248  *   @param toRemove Pointer to IOEventSource subclass to remove.
249  *   @result Returns kIOReturnSuccess if successful, kIOReturnBadArgument if toRemove couldn't be found.
250  */
251 	virtual IOReturn removeEventSource(IOEventSource *toRemove);
252 
253 /*! @function enableAllEventSources
254  *   @abstract Calls enable() in all event sources.
255  *   @discussion For all event sources in eventChain, call enable() function.  See IOEventSource::enable().
256  */
257 	virtual void enableAllEventSources() const;
258 
259 /*! @function disableAllEventSources
260  *   @abstract Calls disable() in all event sources.
261  *   @discussion For all event sources in eventChain, call disable() function.  See IOEventSource::disable().
262  */
263 	virtual void disableAllEventSources() const;
264 
265 /*! @function enableAllInterrupts
266  *   @abstract Calls enable() in all interrupt event sources.
267  *   @discussion For all event sources (ES) for which OSDynamicCast(IOInterruptEventSource, ES) is valid, in eventChain call enable() function.  See IOEventSource::enable().
268  */
269 	virtual void enableAllInterrupts() const;
270 
271 /*! @function disableAllInterrupts
272  *   @abstract Calls disable() in all interrupt event sources.
273  *   @discussion For all event sources (ES) for which OSDynamicCast(IOInterruptEventSource, ES) is valid,  in eventChain call disable() function.  See IOEventSource::disable().
274  */
275 	virtual void disableAllInterrupts() const;
276 
277 
278 protected:
279 // Internal APIs used by event sources to control the thread
280 	friend class IOEventSource;
281 	friend class IOTimerEventSource;
282 	friend class IOCommandGate;
283 #if CONFIG_EXCLAVES
284 	friend class IOExclaveWorkLoopAperture;
285 #endif /* CONFIG_EXCLAVES */
286 #if IOKITSTATS
287 	friend class IOStatistics;
288 #endif
289 	virtual void signalWorkAvailable();
290 	virtual void openGate();
291 	virtual void closeGate();
292 	virtual bool tryCloseGate();
293 	virtual int  sleepGate(void *event, UInt32 interuptibleType);
294 	virtual void wakeupGate(void *event, bool oneThread);
295 
296 public:
297 /* methods available in Mac OS X 10.1 or later */
298 
299 /*! @function runAction
300  *   @abstract Single thread a call to an action with the work-loop.
301  *   @discussion Client function that causes the given action to be called in a single threaded manner.  Beware: the work-loop's gate is recursive and runAction can cause direct or indirect re-entrancy.  When executing on a client's thread, runAction will sleep until the work-loop's gate opens for execution of client actions, the action is single threaded against all other work-loop event sources.
302  *   @param action Pointer to function to be executed in work-loop context.
303  *   @param arg0 Parameter for action parameter, defaults to 0.
304  *   @param arg1 Parameter for action parameter, defaults to 0.
305  *   @param arg2 Parameter for action parameter, defaults to 0.
306  *   @param arg3 Parameter for action parameter, defaults to 0.
307  *   @result Returns the value of the Action callout.
308  */
309 	virtual IOReturn runAction(Action action, OSObject *target,
310 	    void *arg0 = NULL, void *arg1 = NULL,
311 	    void *arg2 = NULL, void *arg3 = NULL);
312 
313 #ifdef __BLOCKS__
314 /*! @function runAction
315  *   @abstract Single thread a call to an action with the work-loop.
316  *   @discussion Client function that causes the given action to be called in a single threaded manner.  Beware: the work-loop's gate is recursive and runAction can cause direct or indirect re-entrancy.  When executing on a client's thread, runAction will sleep until the work-loop's gate opens for execution of client actions, the action is single threaded against all other work-loop event sources.
317  *   @param action Block to be executed in work-loop context.
318  *   @result Returns the result of the action block.
319  */
320 	IOReturn runActionBlock(ActionBlock action);
321 #endif /* __BLOCKS__ */
322 
323 /*! @function runEventSources
324  *   @discussion Consists of the inner 2 loops of the threadMain function(qv).
325  *   The outer loop terminates when there is no more work, and the inside loop
326  *   walks the event list calling the checkForWork method in each event source.
327  *   If an event source has more work to do, it can set the more flag and the
328  *   outer loop will repeat.
329  *  <br><br>
330  *   This function can be used to clear a priority inversion between the normal
331  *   workloop thread and multimedia's real time threads.  The problem is that
332  *   the interrupt action routine is often held off by high priority threads.
333  *   So if they want to get their data now they will have to call us and ask if
334  *   any data is available.  The multi-media user client will arrange for this
335  *   function to be called, which causes any pending interrupts to be processed
336  *   and the completion routines called.  By the time the function returns all
337  *   outstanding work will have been completed at the real time threads
338  *   priority.
339  *
340  *   @result Return false if the work loop is shutting down, true otherwise.
341  */
342 	virtual bool runEventSources();
343 
344 /*! @function setMaximumLockTime
345  *   @discussion For diagnostics use in DEVELOPMENT kernels, set a time interval which if the work loop lock is held for this time or greater, IOWorkLoop will panic or log a backtrace.
346  *   @param interval An absolute time interval, eg. created with clock_interval_to_absolutetime_interval().
347  *   @param options Pass IOWorkLoop::kTimeLockPanics to panic when the time is exceeded, otherwise a log will be generated with OSReportWithBacktrace().
348  */
349 	void setMaximumLockTime(uint64_t interval, uint32_t options);
350 
351 protected:
352 // Internal APIs used by event sources to control the thread
353 	virtual int sleepGate(void *event, AbsoluteTime deadline, UInt32 interuptibleType);
354 
355 #if XNU_KERNEL_PRIVATE
356 	void lockTime(void);
357 #endif /* XNU_KERNEL_PRIVATE */
358 
359 protected:
360 #if __LP64__
361 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 0);
362 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 1);
363 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 2);
364 #else
365 	OSMetaClassDeclareReservedUsedX86(IOWorkLoop, 0);
366 	OSMetaClassDeclareReservedUsedX86(IOWorkLoop, 1);
367 	OSMetaClassDeclareReservedUsedX86(IOWorkLoop, 2);
368 #endif
369 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 3);
370 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 4);
371 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 5);
372 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 6);
373 	OSMetaClassDeclareReservedUnused(IOWorkLoop, 7);
374 };
375 
376 #endif /* !__IOKIT_IOWORKLOOP_H */
377