IOManager.c 15 KB
Newer Older
sof's avatar
sof committed
1
2
3
4
5
6
/* IOManager.c
 *
 * Non-blocking / asynchronous I/O for Win32.
 *
 * (c) sof, 2002-2003.
 */
sof's avatar
sof committed
7
#include "Rts.h"
sof's avatar
sof committed
8
9
#include "IOManager.h"
#include "WorkQueue.h"
sof's avatar
sof committed
10
#include "ConsoleHandler.h"
sof's avatar
sof committed
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <winsock.h>
#include <process.h>

/*
 * Internal state maintained by the IO manager.
 */
typedef struct IOManagerState {
sof's avatar
sof committed
21
22
23
24
25
26
27
    CritSection      manLock;
    WorkQueue*       workQueue;
    int              queueSize;
    int              numWorkers;
    int              workersIdle;
    HANDLE           hExitEvent;
    unsigned int     requestID;
sof's avatar
sof committed
28
29
30
    /* fields for keeping track of active WorkItems */
    CritSection      active_work_lock;
    WorkItem*        active_work_items;
sof's avatar
sof committed
31
32
33
34
35
} IOManagerState;

/* ToDo: wrap up this state via a IOManager handle instead? */
static IOManagerState* ioMan;

sof's avatar
sof committed
36
37
38
static void RegisterWorkItem  ( IOManagerState* iom, WorkItem* wi);
static void DeregisterWorkItem( IOManagerState* iom, WorkItem* wi);

sof's avatar
sof committed
39
40
41
42
43
44
45
46
/*
 * The routine executed by each worker thread.
 */
static
unsigned
WINAPI
IOWorkerProc(PVOID param)
{
sof's avatar
sof committed
47
48
49
50
51
52
    HANDLE  hWaits[2];
    DWORD   rc;
    IOManagerState* iom = (IOManagerState*)param;
    WorkQueue* pq = iom->workQueue;
    WorkItem*  work;
    int        len = 0, fd = 0;
sof's avatar
sof committed
53
    DWORD      errCode = 0;
sof's avatar
sof committed
54
    void*      complData;
sof's avatar
sof committed
55

sof's avatar
sof committed
56
57
    hWaits[0] = (HANDLE)iom->hExitEvent;
    hWaits[1] = GetWorkQueueHandle(pq);
sof's avatar
sof committed
58
  
sof's avatar
sof committed
59
60
61
62
63
64
65
66
67
68
69
70
71
    while (1) {
	/* The error code is communicated back on completion of request; reset. */
	errCode = 0;
	
	EnterCriticalSection(&iom->manLock);
	/* Signal that the worker is idle.
	 *
	 * 'workersIdle' is used when determining whether or not to
	 * increase the worker thread pool when adding a new request.
	 * (see addIORequest().)
	 */
	iom->workersIdle++;
	LeaveCriticalSection(&iom->manLock);
sof's avatar
sof committed
72
73
74
75
76
77
78
	
	/*
	 * A possible future refinement is to make long-term idle threads
	 * wake up and decide to shut down should the number of idle threads
	 * be above some threshold.
	 *
	 */
sof's avatar
sof committed
79
	rc = WaitForMultipleObjects( 2, hWaits, FALSE, INFINITE );
sof's avatar
sof committed
80

81
82
	if (rc == WAIT_OBJECT_0) {
	    // we received the exit event
Simon Marlow's avatar
Simon Marlow committed
83
84
85
	    EnterCriticalSection(&iom->manLock);
	    ioMan->numWorkers--;
	    LeaveCriticalSection(&iom->manLock);
86
87
88
	    return 0;
	}

sof's avatar
sof committed
89
90
91
92
93
94
95
	EnterCriticalSection(&iom->manLock);
	/* Signal that the thread is 'non-idle' and about to consume 
	 * a work item.
	 */
	iom->workersIdle--;
	iom->queueSize--;
	LeaveCriticalSection(&iom->manLock);
sof's avatar
sof committed
96
    
97
	if ( rc == (WAIT_OBJECT_0 + 1) ) {
sof's avatar
sof committed
98
99
	    /* work item available, fetch it. */
	    if (FetchWork(pq,(void**)&work)) {
sof's avatar
sof committed
100
101
		work->abandonOp = 0;
		RegisterWorkItem(iom,work);
sof's avatar
sof committed
102
103
104
105
106
107
108
109
110
111
		if ( work->workKind & WORKER_READ ) {
		    if ( work->workKind & WORKER_FOR_SOCKET ) {
			len = recv(work->workData.ioData.fd, 
				   work->workData.ioData.buf,
				   work->workData.ioData.len,
				   0);
			if (len == SOCKET_ERROR) {
			    errCode = WSAGetLastError();
			}
		    } else {
sof's avatar
sof committed
112
			while (1) {
sof's avatar
sof committed
113
			/* Do the read(), with extra-special handling for Ctrl+C */
sof's avatar
sof committed
114
115
116
			len = read(work->workData.ioData.fd,
				   work->workData.ioData.buf,
				   work->workData.ioData.len);
sof's avatar
sof committed
117
118
119
120
121
122
123
124
125
126
127
128
			if ( len == 0 && work->workData.ioData.len != 0 ) {
			    /* Given the following scenario:
			     *     - a console handler has been registered that handles Ctrl+C
			     *       events.
			     *     - we've not tweaked the 'console mode' settings to turn on
			     *       ENABLE_PROCESSED_INPUT.
			     *     - we're blocked waiting on input from standard input.
			     *     - the user hits Ctrl+C.
			     *
			     * The OS will invoke the console handler (in a separate OS thread),
			     * and the above read() (i.e., under the hood, a ReadFile() op) returns
			     * 0, with the error set to ERROR_OPERATION_ABORTED. We don't
sof's avatar
sof committed
129
130
131
132
133
134
135
			     * want to percolate this error condition back to the Haskell user.
			     * Do this by waiting for the completion of the Haskell console handler.
			     * If upon completion of the console handler routine, the Haskell thread 
			     * that issued the request is found to have been thrown an exception, 
			     * the worker abandons the request (since that's what the Haskell thread 
			     * has done.) If the Haskell thread hasn't been interrupted, the worker 
			     * retries the read request as if nothing happened.
sof's avatar
sof committed
136
			     */
sof's avatar
sof committed
137
138
139
140
			    if ( (GetLastError()) == ERROR_OPERATION_ABORTED ) {
				/* For now, only abort when dealing with the standard input handle.
				 * i.e., for all others, an error is raised.
				 */
sof's avatar
sof committed
141
142
				HANDLE h  = (HANDLE)GetStdHandle(STD_INPUT_HANDLE);
				if ( _get_osfhandle(work->workData.ioData.fd) == (long)h ) {
sof's avatar
sof committed
143
144
145
146
147
148
149
150
151
152
153
154
155
				    if (rts_waitConsoleHandlerCompletion()) {
					/* If the Scheduler has set work->abandonOp, the Haskell thread has 
					 * been thrown an exception (=> the worker must abandon this request.)
					 * We test for this below before invoking the on-completion routine.
					 */
					if (work->abandonOp) {
					    break;
					} else {
					    continue;
					}
				    } 
				} else { 
				    break; /* Treat it like an error */
sof's avatar
sof committed
156
				}
sof's avatar
sof committed
157
158
			    } else {
				break;
sof's avatar
sof committed
159
			    }
sof's avatar
sof committed
160
161
162
			} else {
			    break;
			}
sof's avatar
sof committed
163
			}
sof's avatar
sof committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
			if (len == -1) { errCode = errno; }
		    }
		    complData = work->workData.ioData.buf;
		    fd = work->workData.ioData.fd;
		} else if ( work->workKind & WORKER_WRITE ) {
		    if ( work->workKind & WORKER_FOR_SOCKET ) {
			len = send(work->workData.ioData.fd,
				   work->workData.ioData.buf,
				   work->workData.ioData.len,
				   0);
			if (len == SOCKET_ERROR) {
			    errCode = WSAGetLastError();
			}
		    } else {
			len = write(work->workData.ioData.fd,
				    work->workData.ioData.buf,
				    work->workData.ioData.len);
			if (len == -1) { errCode = errno; }
		    }
		    complData = work->workData.ioData.buf;
		    fd = work->workData.ioData.fd;
		} else if ( work->workKind & WORKER_DELAY ) {
		    /* Approximate implementation of threadDelay;
		     * 
		     * Note: Sleep() is in milliseconds, not micros.
		     */
		    Sleep(work->workData.delayData.msecs / 1000);
		    len = work->workData.delayData.msecs;
		    complData = NULL;
		    fd = 0;
		    errCode = 0;
		} else if ( work->workKind & WORKER_DO_PROC ) {
		    /* perform operation/proc on behalf of Haskell thread. */
		    if (work->workData.procData.proc) {
			/* The procedure is assumed to encode result + success/failure
			 * via its param.
			 */
			errCode=work->workData.procData.proc(work->workData.procData.param);
		    } else {
			errCode=1;
		    }
		    complData = work->workData.procData.param;
		} else {
		    fprintf(stderr, "unknown work request type (%d) , ignoring.\n", work->workKind);
		    fflush(stderr);
		    continue;
		}
sof's avatar
sof committed
211
212
213
214
215
216
217
		if (!work->abandonOp) {
		    work->onCompletion(work->requestID,
				       fd,
				       len,
				       complData,
				       errCode);
		}
sof's avatar
sof committed
218
		/* Free the WorkItem */
sof's avatar
sof committed
219
		DeregisterWorkItem(iom,work);
sof's avatar
sof committed
220
		free(work);
sof's avatar
sof committed
221
	    } else {
sof's avatar
sof committed
222
		fprintf(stderr, "unable to fetch work; fatal.\n"); fflush(stderr);
223
224
225
		EnterCriticalSection(&iom->manLock);
		ioMan->numWorkers--;
		LeaveCriticalSection(&iom->manLock);
sof's avatar
sof committed
226
		return 1;
sof's avatar
sof committed
227
	    }
sof's avatar
sof committed
228
	} else {
sof's avatar
sof committed
229
	    fprintf(stderr, "waiting failed (%lu); fatal.\n", rc); fflush(stderr);
230
231
232
	    EnterCriticalSection(&iom->manLock);
	    ioMan->numWorkers--;
	    LeaveCriticalSection(&iom->manLock);
sof's avatar
sof committed
233
	    return 1;
sof's avatar
sof committed
234
235
	}
    }
sof's avatar
sof committed
236
    return 0;
sof's avatar
sof committed
237
238
239
240
241
242
}

static 
BOOL
NewIOWorkerThread(IOManagerState* iom)
{
sof's avatar
sof committed
243
244
245
246
247
248
249
    unsigned threadId;
    return ( 0 != _beginthreadex(NULL,
				 0,
				 IOWorkerProc,
				 (LPVOID)iom,
				 0,
				 &threadId) );
sof's avatar
sof committed
250
251
252
253
254
}

BOOL
StartIOManager(void)
{
sof's avatar
sof committed
255
256
    HANDLE hExit;
    WorkQueue* wq;
sof's avatar
sof committed
257

sof's avatar
sof committed
258
259
    wq = NewWorkQueue();
    if ( !wq ) return FALSE;  
sof's avatar
sof committed
260
  
sof's avatar
sof committed
261
    ioMan = (IOManagerState*)malloc(sizeof(IOManagerState));
sof's avatar
sof committed
262
  
sof's avatar
sof committed
263
264
265
266
    if (!ioMan) {
	FreeWorkQueue(wq);
	return FALSE;
    }
sof's avatar
sof committed
267

sof's avatar
sof committed
268
269
270
271
272
273
274
    /* A manual-reset event */
    hExit = CreateEvent ( NULL, TRUE, FALSE, NULL );
    if ( !hExit ) {
	FreeWorkQueue(wq);
	free(ioMan);
	return FALSE;
    }
sof's avatar
sof committed
275
  
sof's avatar
sof committed
276
277
278
279
280
281
282
    ioMan->hExitEvent = hExit;
    InitializeCriticalSection(&ioMan->manLock);
    ioMan->workQueue   = wq;
    ioMan->numWorkers  = 0;
    ioMan->workersIdle = 0;
    ioMan->queueSize   = 0;
    ioMan->requestID   = 1;
sof's avatar
sof committed
283
284
    InitializeCriticalSection(&ioMan->active_work_lock);
    ioMan->active_work_items = NULL;
sof's avatar
sof committed
285
 
sof's avatar
sof committed
286
    return TRUE;
sof's avatar
sof committed
287
288
289
}

/*
sof's avatar
sof committed
290
291
292
293
294
 * Function: depositWorkItem()
 *
 * Local function which deposits a WorkItem onto a work queue,
 * deciding in the process whether or not the thread pool needs
 * to be augmented with another thread to handle the new request.
sof's avatar
sof committed
295
296
 *
 */
sof's avatar
sof committed
297
static
sof's avatar
sof committed
298
int
sof's avatar
sof committed
299
300
depositWorkItem( unsigned int reqID,
		 WorkItem* wItem )
sof's avatar
sof committed
301
{
sof's avatar
sof committed
302
    EnterCriticalSection(&ioMan->manLock);
sof's avatar
sof committed
303

sof's avatar
sof committed
304
#if 0
sof's avatar
sof committed
305
    fprintf(stderr, "depositWorkItem: %d/%d\n", ioMan->workersIdle, ioMan->numWorkers); 
sof's avatar
sof committed
306
    fflush(stderr);
sof's avatar
sof committed
307
#endif
sof's avatar
sof committed
308
309
310
311
312
313
314
315
316
317
318
319
    /* A new worker thread is created when there are fewer idle threads
     * than non-consumed queue requests. This ensures that requests will
     * be dealt with in a timely manner.
     *
     * [Long explanation of why the previous thread pool policy lead to 
     * trouble]
     *
     * Previously, the thread pool was augmented iff no idle worker threads
     * were available. That strategy runs the risk of repeatedly adding to
     * the request queue without expanding the thread pool to handle this
     * sudden spike in queued requests. 
     * [How? Assume workersIdle is 1, and addIORequest() is called. No new 
sof's avatar
sof committed
320
     * thread is created and the request is simply queued. If addIORequest()
sof's avatar
sof committed
321
322
323
324
325
326
327
328
329
330
331
332
333
     * is called again _before the OS schedules a worker thread to pull the
     * request off the queue_, workersIdle is still 1 and another request is 
     * simply added to the queue. Once the worker thread is run, only one
     * request is de-queued, leaving the 2nd request in the queue]
     * 
     * Assuming none of the queued requests take an inordinate amount of to 
     * complete, the request queue would eventually be drained. But if that's 
     * not the case, the later requests will end up languishing in the queue 
     * indefinitely. The non-timely handling of requests may cause CH applications
     * to misbehave / hang; bad.
     *
     */
    ioMan->queueSize++;
sof's avatar
sof committed
334
335
336
    if ( (ioMan->workersIdle < ioMan->queueSize) ) {
	/* see if giving up our quantum ferrets out some idle threads.
	 */
sof's avatar
sof committed
337
	LeaveCriticalSection(&ioMan->manLock);
sof's avatar
sof committed
338
339
340
341
342
	Sleep(0);
	EnterCriticalSection(&ioMan->manLock);
	if ( (ioMan->workersIdle < ioMan->queueSize) ) {
	    /* No, go ahead and create another. */
	    ioMan->numWorkers++;
343
	    if (!NewIOWorkerThread(ioMan)) {
344
345
		ioMan->numWorkers--;
	    }
sof's avatar
sof committed
346
	}
sof's avatar
sof committed
347
    }
348
    LeaveCriticalSection(&ioMan->manLock);
sof's avatar
sof committed
349
  
sof's avatar
sof committed
350
351
352
353
354
355
356
357
    if (SubmitWork(ioMan->workQueue,wItem)) {
	/* Note: the work item has potentially been consumed by a worker thread
	 *       (and freed) at this point, so we cannot use wItem's requestID.
	 */
	return reqID;
    } else {
	return 0;
    }
sof's avatar
sof committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
}

/*
 * Function: AddIORequest()
 *
 * Conduit to underlying WorkQueue's SubmitWork(); adds IO
 * request to work queue, deciding whether or not to augment
 * the thread pool in the process. 
 */
int
AddIORequest ( int   fd,
	       BOOL  forWriting,
	       BOOL  isSocket,
	       int   len,
	       char* buffer,
	       CompletionProc onCompletion)
{
    WorkItem* wItem    = (WorkItem*)malloc(sizeof(WorkItem));
    unsigned int reqID = ioMan->requestID++;
    if (!ioMan || !wItem) return 0;
  
    /* Fill in the blanks */
    wItem->workKind     = ( isSocket   ? WORKER_FOR_SOCKET : 0 ) | 
	                  ( forWriting ? WORKER_WRITE : WORKER_READ );
    wItem->workData.ioData.fd  = fd;
    wItem->workData.ioData.len = len;
    wItem->workData.ioData.buf = buffer;
sof's avatar
sof committed
385
    wItem->link = NULL;
sof's avatar
sof committed
386
387
388
389
390

    wItem->onCompletion        = onCompletion;
    wItem->requestID           = reqID;
  
    return depositWorkItem(reqID, wItem);
sof's avatar
sof committed
391
}       
sof's avatar
sof committed
392
393
394
395

/*
 * Function: AddDelayRequest()
 *
sof's avatar
sof committed
396
397
 * Like AddIORequest(), but this time adding a delay request to
 * the request queue.
sof's avatar
sof committed
398
399
400
401
402
 */
BOOL
AddDelayRequest ( unsigned int   msecs,
		  CompletionProc onCompletion)
{
sof's avatar
sof committed
403
404
405
    WorkItem* wItem = (WorkItem*)malloc(sizeof(WorkItem));
    unsigned int reqID = ioMan->requestID++;
    if (!ioMan || !wItem) return FALSE;
sof's avatar
sof committed
406
  
sof's avatar
sof committed
407
408
409
410
411
    /* Fill in the blanks */
    wItem->workKind     = WORKER_DELAY;
    wItem->workData.delayData.msecs = msecs;
    wItem->onCompletion = onCompletion;
    wItem->requestID    = reqID;
sof's avatar
sof committed
412
    wItem->link         = NULL;
sof's avatar
sof committed
413

sof's avatar
sof committed
414
    return depositWorkItem(reqID, wItem);
sof's avatar
sof committed
415
416
417
}

/*
sof's avatar
sof committed
418
 * Function: AddProcRequest()
sof's avatar
sof committed
419
 *
sof's avatar
sof committed
420
 * Add an asynchronous procedure request.
sof's avatar
sof committed
421
422
423
424
425
426
 */
BOOL
AddProcRequest ( void* proc,
		 void* param,
		 CompletionProc onCompletion)
{
sof's avatar
sof committed
427
428
429
    WorkItem* wItem = (WorkItem*)malloc(sizeof(WorkItem));
    unsigned int reqID = ioMan->requestID++;
    if (!ioMan || !wItem) return FALSE;
sof's avatar
sof committed
430
  
sof's avatar
sof committed
431
432
433
434
435
436
    /* Fill in the blanks */
    wItem->workKind     = WORKER_DO_PROC;
    wItem->workData.procData.proc  = proc;
    wItem->workData.procData.param = param;
    wItem->onCompletion = onCompletion;
    wItem->requestID    = reqID;
sof's avatar
sof committed
437
438
    wItem->abandonOp    = 0;
    wItem->link         = NULL;
sof's avatar
sof committed
439

sof's avatar
sof committed
440
    return depositWorkItem(reqID, wItem);
sof's avatar
sof committed
441
442
}

443
void ShutdownIOManager ( void )
sof's avatar
sof committed
444
{
Simon Marlow's avatar
Simon Marlow committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
    int num;

    SetEvent(ioMan->hExitEvent);
  
    /* Wait for all worker threads to die. */
    for (;;) {
        EnterCriticalSection(&ioMan->manLock);
	num = ioMan->numWorkers;
	LeaveCriticalSection(&ioMan->manLock);
	if (num == 0)
	    break;
	Sleep(10);
    }
    FreeWorkQueue(ioMan->workQueue);
    CloseHandle(ioMan->hExitEvent);
    free(ioMan);
    ioMan = NULL;
sof's avatar
sof committed
462
}
sof's avatar
sof committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528

/* Keep track of WorkItems currently being serviced. */
static 
void
RegisterWorkItem(IOManagerState* ioMan, 
		 WorkItem* wi)
{
    EnterCriticalSection(&ioMan->active_work_lock);
    wi->link = ioMan->active_work_items;
    ioMan->active_work_items = wi;
    LeaveCriticalSection(&ioMan->active_work_lock);
}

static 
void
DeregisterWorkItem(IOManagerState* ioMan, 
		   WorkItem* wi)
{
    WorkItem *ptr, *prev;
    
    EnterCriticalSection(&ioMan->active_work_lock);
    for(prev=NULL,ptr=ioMan->active_work_items;ptr;prev=ptr,ptr=ptr->link) {
	if (wi->requestID == ptr->requestID) {
	    if (prev==NULL) {
		ioMan->active_work_items = ptr->link;
	    } else {
		prev->link = ptr->link;
	    }
	    LeaveCriticalSection(&ioMan->active_work_lock);
	    return;
	}
    }
    fprintf(stderr, "DeregisterWorkItem: unable to locate work item %d\n", wi->requestID);
    LeaveCriticalSection(&ioMan->active_work_lock);
}


/*
 * Function: abandonWorkRequest()
 *
 * Signal that a work request isn't of interest. Called by the Scheduler
 * if a blocked Haskell thread has an exception thrown to it.
 *
 * Note: we're not aborting the system call that a worker might be blocked on
 * here, just disabling the propagation of its result once its finished. We
 * may have to go the whole hog here and switch to overlapped I/O so that we
 * can abort blocked system calls.
 */
void
abandonWorkRequest ( int reqID )
{
    WorkItem *ptr;
    EnterCriticalSection(&ioMan->active_work_lock);
    for(ptr=ioMan->active_work_items;ptr;ptr=ptr->link) {
	if (ptr->requestID == (unsigned int)reqID ) {
	    ptr->abandonOp = 1;
	    LeaveCriticalSection(&ioMan->active_work_lock);
	    return;
	}
    }
    /* Note: if the request ID isn't present, the worker will have
     * finished sometime since awaitRequests() last drained the completed
     * request table; i.e., not an error.
     */
    LeaveCriticalSection(&ioMan->active_work_lock);
}