3 * Integrating Win32 asynchronous I/O with the GHC RTS.
13 #include "Capability.h"
14 #include "win32/AsyncIO.h"
15 #include "win32/IOManager.h"
20 * Haskell code issue asynchronous I/O requests via the
21 * async{Read,Write,DoOp}# primops. These cause addIORequest()
22 * to be invoked, which forwards the request to the underlying
23 * asynchronous I/O subsystem. Each request is tagged with a unique
26 * addIORequest() returns this ID, so that when the blocked CH
27 * thread is added onto blocked_queue, its TSO is annotated with
28 * it. Upon completion of an I/O request, the async I/O handling
29 * code makes a back-call to signal its completion; the local
30 * onIOComplete() routine. It adds the IO request ID (along with
31 * its result data) to a queue of completed requests before returning.
33 * The queue of completed IO request is read by the thread operating
34 * the RTS scheduler. It de-queues the CH threads corresponding
35 * to the request IDs, making them runnable again.
39 typedef struct CompletedReq {
45 #define MAX_REQUESTS 200
47 static CRITICAL_SECTION queue_lock;
48 static HANDLE completed_req_event;
49 static HANDLE abandon_req_wait;
50 static HANDLE wait_handles[2];
51 static CompletedReq completedTable[MAX_REQUESTS];
52 static int completed_hw;
53 static HANDLE completed_table_sema;
54 static int issued_reqs;
57 onIOComplete(unsigned int reqID,
64 /* Deposit result of request in queue/table..when there's room. */
65 dwRes = WaitForSingleObject(completed_table_sema, INFINITE);
71 fprintf(stderr, "onIOComplete: failed to grab table semaphore, dropping request 0x%x\n", reqID);
75 EnterCriticalSection(&queue_lock);
76 if (completed_hw == MAX_REQUESTS) {
77 /* Shouldn't happen */
78 fprintf(stderr, "onIOComplete: ERROR -- Request table overflow (%d); dropping.\n", reqID);
82 fprintf(stderr, "onCompl: %d %d %d %d %d\n",
83 reqID, len, errCode, issued_reqs, completed_hw);
86 completedTable[completed_hw].reqID = reqID;
87 completedTable[completed_hw].len = len;
88 completedTable[completed_hw].errCode = errCode;
91 if (completed_hw == 1) {
92 /* The event is used to wake up the scheduler thread should it
93 * be blocked waiting for requests to complete. The event resets once
94 * that thread has cleared out the request queue/table.
96 SetEvent(completed_req_event);
99 LeaveCriticalSection(&queue_lock);
109 EnterCriticalSection(&queue_lock);
111 LeaveCriticalSection(&queue_lock);
113 fprintf(stderr, "addIOReq: %d %d %d\n", fd, forWriting, len); fflush(stderr);
115 return AddIORequest(fd,forWriting,isSock,len,buf,onIOComplete);
119 addDelayRequest(int msecs)
121 EnterCriticalSection(&queue_lock);
123 LeaveCriticalSection(&queue_lock);
125 fprintf(stderr, "addDelayReq: %d\n", msecs); fflush(stderr);
127 return AddDelayRequest(msecs,onIOComplete);
131 addDoProcRequest(void* proc, void* param)
133 EnterCriticalSection(&queue_lock);
135 LeaveCriticalSection(&queue_lock);
137 fprintf(stderr, "addProcReq: %p %p\n", proc, param); fflush(stderr);
139 return AddProcRequest(proc,param,onIOComplete);
146 if (!StartIOManager()) {
149 InitializeCriticalSection(&queue_lock);
150 /* Create a pair of events:
152 * - completed_req_event -- signals the deposit of request result; manual reset.
153 * - abandon_req_wait -- external OS thread tells current RTS/Scheduler
154 * thread to abandon wait for IO request completion.
157 completed_req_event = CreateEvent (NULL, TRUE, FALSE, NULL);
158 abandon_req_wait = CreateEvent (NULL, FALSE, FALSE, NULL);
159 wait_handles[0] = completed_req_event;
160 wait_handles[1] = abandon_req_wait;
162 if ( !(completed_table_sema = CreateSemaphore (NULL, MAX_REQUESTS, MAX_REQUESTS, NULL)) ) {
163 DWORD rc = GetLastError();
164 fprintf(stderr, "startupAsyncIO: CreateSemaphore failed 0x%x\n", rc);
168 return ( completed_req_event != INVALID_HANDLE_VALUE &&
169 abandon_req_wait != INVALID_HANDLE_VALUE &&
170 completed_table_sema != NULL );
176 CloseHandle(completed_req_event);
181 * Function: awaitRequests(wait)
183 * Check for the completion of external IO work requests. Worker
184 * threads signal completion of IO requests by depositing them
185 * in a table (completedTable). awaitRequests() matches up
186 * requests in that table with threads on the blocked_queue,
187 * making the threads whose IO requests have completed runnable
190 * awaitRequests() is called by the scheduler periodically _or_ if
191 * it is out of work, and need to wait for the completion of IO
192 * requests to make further progress. In the latter scenario,
193 * awaitRequests() will simply block waiting for worker threads
194 * to complete if the 'completedTable' is empty.
197 awaitRequests(rtsBool wait)
201 fprintf(stderr, "awaitRequests(): %d %d %d\n", issued_reqs, completed_hw, wait);
204 EnterCriticalSection(&queue_lock);
205 /* Nothing immediately available & we won't wait */
206 if ((!wait && completed_hw == 0)
208 // If we just return when wait==rtsFalse, we'll go into a busy
209 // wait loop, so I disabled this condition --SDM 18/12/2003
210 (issued_reqs == 0 && completed_hw == 0)
213 LeaveCriticalSection(&queue_lock);
216 if (completed_hw == 0) {
217 /* empty table, drop lock and wait */
218 LeaveCriticalSection(&queue_lock);
219 if ( wait && !interrupted ) {
220 DWORD dwRes = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
223 /* a request was completed */
225 case WAIT_OBJECT_0 + 1:
227 /* timeout (unlikely) or told to abandon waiting */
230 DWORD dw = GetLastError();
231 fprintf(stderr, "awaitRequests: wait failed -- error code: %lu\n", dw); fflush(stderr);
235 fprintf(stderr, "awaitRequests: unexpected wait return code %lu\n", dwRes); fflush(stderr);
246 for (i=0; i < completed_hw; i++) {
247 /* For each of the completed requests, match up their Ids
248 * with those of the threads on the blocked_queue. If the
249 * thread that made the IO request has been subsequently
250 * killed (and removed from blocked_queue), no match will
251 * be found for that request Id.
253 * i.e., killing a Haskell thread doesn't attempt to cancel
254 * the IO request it is blocked on.
257 unsigned int rID = completedTable[i].reqID;
260 for(tso = blocked_queue_hd ; tso != END_TSO_QUEUE; prev = tso, tso = tso->link) {
262 switch(tso->why_blocked) {
265 case BlockedOnDoProc:
266 if (tso->block_info.async_result->reqID == rID) {
267 /* Found the thread blocked waiting on request; stodgily fill
268 * in its result block.
270 tso->block_info.async_result->len = completedTable[i].len;
271 tso->block_info.async_result->errCode = completedTable[i].errCode;
273 /* Drop the matched TSO from blocked_queue */
275 prev->link = tso->link;
277 blocked_queue_hd = tso->link;
279 if (blocked_queue_tl == tso) {
280 blocked_queue_tl = prev;
283 /* Terminates the run queue + this inner for-loop. */
284 tso->link = END_TSO_QUEUE;
285 tso->why_blocked = NotBlocked;
286 PUSH_ON_RUN_QUEUE(tso);
291 if (tso->why_blocked != NotBlocked) {
292 barf("awaitRequests: odd thread state");
297 /* Signal that there's completed table slots available */
298 if ( !ReleaseSemaphore(completed_table_sema, 1, NULL) ) {
299 DWORD dw = GetLastError();
300 fprintf(stderr, "awaitRequests: failed to signal semaphore (error code=0x%x)\n", dw);
305 ResetEvent(completed_req_event);
306 LeaveCriticalSection(&queue_lock);
312 * Function: abandonRequestWait()
314 * Wake up a thread that's blocked waiting for new IO requests
315 * to complete (via awaitRequests().)
318 abandonRequestWait( void )
320 /* the event is auto-reset, but in case there's no thread
321 * already waiting on the event, we want to return it to
322 * a non-signalled state.
324 * Careful! There is no synchronisation between
325 * abandonRequestWait and awaitRequest, which means that
326 * abandonRequestWait might be called just before a thread
327 * goes into a wait, and we miss the abandon signal. So we
328 * must SetEvent() here rather than PulseEvent() to ensure
329 * that the event isn't lost. We can re-optimise by resetting
330 * the event somewhere safe if we know the event has been
331 * properly serviced (see resetAbandon() below). --SDM 18/12/2003
333 SetEvent(abandon_req_wait);
337 resetAbandonRequestWait( void )
339 ResetEvent(abandon_req_wait);