3 * Integrating Win32 asynchronous I/O with the GHC RTS.
8 #if !defined(THREADED_RTS)
16 #include "Capability.h"
17 #include "win32/AsyncIO.h"
18 #include "win32/IOManager.h"
23 * Haskell code issue asynchronous I/O requests via the
24 * async{Read,Write,DoOp}# primops. These cause addIORequest()
25 * to be invoked, which forwards the request to the underlying
26 * asynchronous I/O subsystem. Each request is tagged with a unique
29 * addIORequest() returns this ID, so that when the blocked CH
30 * thread is added onto blocked_queue, its TSO is annotated with
31 * it. Upon completion of an I/O request, the async I/O handling
32 * code makes a back-call to signal its completion; the local
33 * onIOComplete() routine. It adds the IO request ID (along with
34 * its result data) to a queue of completed requests before returning.
36 * The queue of completed IO request is read by the thread operating
37 * the RTS scheduler. It de-queues the CH threads corresponding
38 * to the request IDs, making them runnable again.
42 typedef struct CompletedReq {
48 #define MAX_REQUESTS 200
50 static CRITICAL_SECTION queue_lock;
51 static HANDLE completed_req_event = INVALID_HANDLE_VALUE;
52 static HANDLE abandon_req_wait = INVALID_HANDLE_VALUE;
53 static HANDLE wait_handles[2];
54 static CompletedReq completedTable[MAX_REQUESTS];
55 static int completed_hw;
56 static HANDLE completed_table_sema;
57 static int issued_reqs;
60 onIOComplete(unsigned int reqID,
67 /* Deposit result of request in queue/table..when there's room. */
68 dwRes = WaitForSingleObject(completed_table_sema, INFINITE);
74 fprintf(stderr, "onIOComplete: failed to grab table semaphore, dropping request 0x%x\n", reqID);
78 EnterCriticalSection(&queue_lock);
79 if (completed_hw == MAX_REQUESTS) {
80 /* Shouldn't happen */
81 fprintf(stderr, "onIOComplete: ERROR -- Request table overflow (%d); dropping.\n", reqID);
85 fprintf(stderr, "onCompl: %d %d %d %d %d\n",
86 reqID, len, errCode, issued_reqs, completed_hw);
89 completedTable[completed_hw].reqID = reqID;
90 completedTable[completed_hw].len = len;
91 completedTable[completed_hw].errCode = errCode;
94 if (completed_hw == 1) {
95 /* The event is used to wake up the scheduler thread should it
96 * be blocked waiting for requests to complete. The event resets once
97 * that thread has cleared out the request queue/table.
99 SetEvent(completed_req_event);
102 LeaveCriticalSection(&queue_lock);
112 EnterCriticalSection(&queue_lock);
114 LeaveCriticalSection(&queue_lock);
116 fprintf(stderr, "addIOReq: %d %d %d\n", fd, forWriting, len); fflush(stderr);
118 return AddIORequest(fd,forWriting,isSock,len,buf,onIOComplete);
122 addDelayRequest(int msecs)
124 EnterCriticalSection(&queue_lock);
126 LeaveCriticalSection(&queue_lock);
128 fprintf(stderr, "addDelayReq: %d\n", msecs); fflush(stderr);
130 return AddDelayRequest(msecs,onIOComplete);
134 addDoProcRequest(void* proc, void* param)
136 EnterCriticalSection(&queue_lock);
138 LeaveCriticalSection(&queue_lock);
140 fprintf(stderr, "addProcReq: %p %p\n", proc, param); fflush(stderr);
142 return AddProcRequest(proc,param,onIOComplete);
149 if (!StartIOManager()) {
152 InitializeCriticalSection(&queue_lock);
153 /* Create a pair of events:
155 * - completed_req_event -- signals the deposit of request result; manual reset.
156 * - abandon_req_wait -- external OS thread tells current RTS/Scheduler
157 * thread to abandon wait for IO request completion.
160 completed_req_event = CreateEvent (NULL, TRUE, FALSE, NULL);
161 abandon_req_wait = CreateEvent (NULL, FALSE, FALSE, NULL);
162 wait_handles[0] = completed_req_event;
163 wait_handles[1] = abandon_req_wait;
165 if ( !(completed_table_sema = CreateSemaphore (NULL, MAX_REQUESTS, MAX_REQUESTS, NULL)) ) {
166 DWORD rc = GetLastError();
167 fprintf(stderr, "startupAsyncIO: CreateSemaphore failed 0x%x\n", (int)rc);
171 return ( completed_req_event != INVALID_HANDLE_VALUE &&
172 abandon_req_wait != INVALID_HANDLE_VALUE &&
173 completed_table_sema != NULL );
180 if (completed_req_event != INVALID_HANDLE_VALUE) {
181 CloseHandle(completed_req_event);
182 completed_req_event = INVALID_HANDLE_VALUE;
184 if (abandon_req_wait != INVALID_HANDLE_VALUE) {
185 CloseHandle(abandon_req_wait);
186 abandon_req_wait = INVALID_HANDLE_VALUE;
188 if (completed_table_sema != NULL) {
189 CloseHandle(completed_table_sema);
190 completed_table_sema = NULL;
195 * Function: awaitRequests(wait)
197 * Check for the completion of external IO work requests. Worker
198 * threads signal completion of IO requests by depositing them
199 * in a table (completedTable). awaitRequests() matches up
200 * requests in that table with threads on the blocked_queue,
201 * making the threads whose IO requests have completed runnable
204 * awaitRequests() is called by the scheduler periodically _or_ if
205 * it is out of work, and need to wait for the completion of IO
206 * requests to make further progress. In the latter scenario,
207 * awaitRequests() will simply block waiting for worker threads
208 * to complete if the 'completedTable' is empty.
211 awaitRequests(rtsBool wait)
214 // none of this is actually used in the threaded RTS
218 fprintf(stderr, "awaitRequests(): %d %d %d\n", issued_reqs, completed_hw, wait);
221 EnterCriticalSection(&queue_lock);
222 /* Nothing immediately available & we won't wait */
223 if ((!wait && completed_hw == 0)
225 // If we just return when wait==rtsFalse, we'll go into a busy
226 // wait loop, so I disabled this condition --SDM 18/12/2003
227 (issued_reqs == 0 && completed_hw == 0)
230 LeaveCriticalSection(&queue_lock);
233 if (completed_hw == 0) {
234 /* empty table, drop lock and wait */
235 LeaveCriticalSection(&queue_lock);
236 if ( wait && sched_state == SCHED_RUNNING ) {
237 DWORD dwRes = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
240 /* a request was completed */
242 case WAIT_OBJECT_0 + 1:
244 /* timeout (unlikely) or told to abandon waiting */
247 DWORD dw = GetLastError();
248 fprintf(stderr, "awaitRequests: wait failed -- error code: %lu\n", dw); fflush(stderr);
252 fprintf(stderr, "awaitRequests: unexpected wait return code %lu\n", dwRes); fflush(stderr);
263 for (i=0; i < completed_hw; i++) {
264 /* For each of the completed requests, match up their Ids
265 * with those of the threads on the blocked_queue. If the
266 * thread that made the IO request has been subsequently
267 * killed (and removed from blocked_queue), no match will
268 * be found for that request Id.
270 * i.e., killing a Haskell thread doesn't attempt to cancel
271 * the IO request it is blocked on.
274 unsigned int rID = completedTable[i].reqID;
277 for(tso = blocked_queue_hd ; tso != END_TSO_QUEUE; prev = tso, tso = tso->link) {
279 switch(tso->why_blocked) {
282 case BlockedOnDoProc:
283 if (tso->block_info.async_result->reqID == rID) {
284 /* Found the thread blocked waiting on request; stodgily fill
285 * in its result block.
287 tso->block_info.async_result->len = completedTable[i].len;
288 tso->block_info.async_result->errCode = completedTable[i].errCode;
290 /* Drop the matched TSO from blocked_queue */
292 prev->link = tso->link;
294 blocked_queue_hd = tso->link;
296 if (blocked_queue_tl == tso) {
297 blocked_queue_tl = prev ? prev : END_TSO_QUEUE;
300 /* Terminates the run queue + this inner for-loop. */
301 tso->link = END_TSO_QUEUE;
302 tso->why_blocked = NotBlocked;
303 pushOnRunQueue(&MainCapability, tso);
308 if (tso->why_blocked != NotBlocked) {
309 barf("awaitRequests: odd thread state");
314 /* Signal that there's completed table slots available */
315 if ( !ReleaseSemaphore(completed_table_sema, 1, NULL) ) {
316 DWORD dw = GetLastError();
317 fprintf(stderr, "awaitRequests: failed to signal semaphore (error code=0x%x)\n", (int)dw);
322 ResetEvent(completed_req_event);
323 LeaveCriticalSection(&queue_lock);
326 #endif /* !THREADED_RTS */
330 * Function: abandonRequestWait()
332 * Wake up a thread that's blocked waiting for new IO requests
333 * to complete (via awaitRequests().)
336 abandonRequestWait( void )
338 /* the event is auto-reset, but in case there's no thread
339 * already waiting on the event, we want to return it to
340 * a non-signalled state.
342 * Careful! There is no synchronisation between
343 * abandonRequestWait and awaitRequest, which means that
344 * abandonRequestWait might be called just before a thread
345 * goes into a wait, and we miss the abandon signal. So we
346 * must SetEvent() here rather than PulseEvent() to ensure
347 * that the event isn't lost. We can re-optimise by resetting
348 * the event somewhere safe if we know the event has been
349 * properly serviced (see resetAbandon() below). --SDM 18/12/2003
351 SetEvent(abandon_req_wait);
355 resetAbandonRequestWait( void )
357 ResetEvent(abandon_req_wait);
360 #endif /* !defined(THREADED_RTS) */