File: WaitFor.c

package info (click to toggle)
nas 1.2p5-7
  • links: PTS
  • area: main
  • in suites: slink
  • size: 4,188 kB
  • ctags: 5,551
  • sloc: ansic: 53,034; perl: 1,104; yacc: 228; makefile: 211; cpp: 199; sh: 96; lex: 44
file content (701 lines) | stat: -rw-r--r-- 17,233 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/*
 * Copyright 1993 Network Computing Devices, Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software and
 * its documentation for any purpose is hereby granted without fee, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name Network Computing Devices, Inc. not be
 * used in advertising or publicity pertaining to distribution of this 
 * software without specific, written prior permission.
 * 
 * THIS SOFTWARE IS PROVIDED `AS-IS'.  NETWORK COMPUTING DEVICES, INC.,
 * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT
 * LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NONINFRINGEMENT.  IN NO EVENT SHALL NETWORK
 * COMPUTING DEVICES, INC., BE LIABLE FOR ANY DAMAGES WHATSOEVER, INCLUDING
 * SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, INCLUDING LOSS OF USE, DATA,
 * OR PROFITS, EVEN IF ADVISED OF THE POSSIBILITY THEREOF, AND REGARDLESS OF
 * WHETHER IN AN ACTION IN CONTRACT, TORT OR NEGLIGENCE, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 * 
 * $NCDId: @(#)WaitFor.c,v 1.10 1996/04/24 17:15:18 greg Exp $
 */
/***********************************************************
Some portions derived from:

Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts,
and the Massachusetts Institute of Technology, Cambridge, Massachusetts.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the names of Digital or MIT not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

******************************************************************/

/*****************************************************************
 * OS Depedent input routines:
 *
 *  WaitForSomething,  GetEvent
 *
 *****************************************************************/

#include <audio/audio.h>
#include <audio/Aproto.h>
#include <audio/Aos.h>

#include <errno.h>
#include <stdio.h>
#include "misc.h"

#ifndef _MINIX
#include <sys/param.h>
#endif /* !_MINIX */
#include <signal.h>

#ifdef _MINIX
#include <assert.h>
#endif /* _MINIX */

#include "osdep.h"
#include "dixstruct.h"
#include "opaque.h"

#ifndef _MINIX
extern long AllSockets[];
extern long AllClients[];
extern long LastSelectMask[];
extern long WellKnownConnections;
extern long ClientsWithInput[];
extern long ClientsWriteBlocked[];
extern long OutputPending[];
extern int ConnectionTranslation[];
#else /* _MINIX */
extern asio_fd_set_t InprogressFdSet;
extern asio_fd_set_t ListenFdSet;
extern asio_fd_set_t ClientFdSet;
extern asio_fd_set_t CompletedFdSet;
extern asio_fd_set_t IgnoreFdSet;
extern asio_fd_set_t GrabFdSet;

extern Bool AnyClientsWithInput;
extern int GrabInProgress;

void EnqueueNewConnection();
void UpdateClientIOStatus();
#endif /* _MINIX */

extern Bool NewOutputPending;
#ifndef _MINIX
extern Bool AnyClientsWriteBlocked;
#endif

extern WorkQueuePtr workQueue;

#ifdef STARTSERVER
extern int timeoutWithNoClients;
#endif /* STARTSERVER */

extern void CheckConnections();
extern Bool EstablishNewConnections();
extern void ResetOsBuffers();

extern int errno;

#ifdef apollo
extern long apInputMask[];

static long LastWriteMask[mskcnt];
#endif

#ifdef XTESTEXT1
/*
 * defined in xtestext1dd.c
 */
extern int playback_on;
#endif /* XTESTEXT1 */

#if defined(SYSV) || defined(SVR4)
#ifdef hpux
#define signal  _local_signal
#define sigset  _local_signal

#ifndef NeedFunctionPrototypes
static void (*_local_signal(sig, action))()
int sig;
void (*action)();
#else /* NeedFunctionPrototypes */
static void (*_local_signal(int sig, void (*action)(int)))(int)
#endif /* NeedFunctionPrototypes */
{
        struct sigvec   vec;
        struct sigvec   ovec;

        vec.sv_handler = action;
        vec.sv_flags = 0;
        sigvector(sig, &vec, &ovec);

        return(ovec.sv_handler);
}
#else
#define signal sigset
#endif
#endif

/*****************
 * WaitForSomething:
 *     Make the server suspend until there is
 *	1. data from clients or
 *	2. clients that have buffered replies/events are ready
 *
 *****************/

#if !defined(AMOEBA) || !defined(_MINIX)
int
WaitForSomething(pClientsReady)
    int *pClientsReady;
{
    int i;
    struct timeval waittime, *wt;
#ifdef STARTSERVER
    struct timeval wtim;
#endif /* STARTSERVER */
    long timeout;
    long clientsReadable[mskcnt];
    long clientsWritable[mskcnt];
    long curclient;
    int selecterr;
    int nready;

    CLEARBITS(clientsReadable);

    /* We need a while loop here to handle 
       crashed connections and the screen saver timeout */
    while (1)
    {
	/* deal with any blocked jobs */
	if (workQueue)
	    ProcessWorkQueue();

	if (ANYSET(ClientsWithInput))
	{
	    COPYBITS(ClientsWithInput, clientsReadable);
	    break;
	}
#ifdef STARTSERVER
	/* timeout if no clients */
	if (timeoutWithNoClients > 0 && currentMaxClients < 2)
	{
	    wtim.tv_sec = timeoutWithNoClients;
	    wtim.tv_usec = 0;
	    wt = &wtim;
	}
	else
#endif /* STARTSERVER */
	wt = NULL;
/* XXX need to have ResetOsBuffers() somewhere */
	COPYBITS(AllSockets, LastSelectMask);
#ifdef apollo
        COPYBITS(apInputMask, LastWriteMask);
#endif
	if (NewOutputPending)
	    FlushAllOutput();
	/* keep this check close to select() call to minimize race */
	if (dispatchException)
	    i = -1;
	else if (AnyClientsWriteBlocked)
	{
	    COPYBITS(ClientsWriteBlocked, clientsWritable);
#ifdef hpux
	    i = select (MAXSOCKS, (int *)LastSelectMask,
			(int *)clientsWritable, (int *) NULL, wt);
#else
	    i = select (MAXSOCKS, (fd_set *)LastSelectMask,
			(fd_set *)clientsWritable, (fd_set *) NULL, wt);
#endif
	}
	else
#ifdef apollo
	    i = select (MAXSOCKS, (int *)LastSelectMask,
			(fd_set *)LastWriteMask, (fd_set *) NULL, wt);
#else
#ifdef hpux

	    i = select (MAXSOCKS, (int *)LastSelectMask,
			(int *) NULL, (int *) NULL, wt);
#else
	    i = select (MAXSOCKS, (fd_set *)LastSelectMask,
			(fd_set *) NULL, (fd_set *) NULL, wt);
#endif
#endif
	selecterr = errno;
	if (i <= 0) /* An error or timeout occurred */
	{

	    if (dispatchException)
		return 0;
	    CLEARBITS(clientsWritable);
	    if (i < 0)
	    {
		if (selecterr == EBADF)    /* Some client disconnected */
		{
		    CheckConnections ();
		    if (! ANYSET (AllClients))
			return 0;
		}
		else if (selecterr != EINTR)
		    ErrorF("WaitForSomething(): select: errno=%d\n",
			selecterr);
	    }
#ifdef STARTSERVER
	    else
	    {
		/* terminate if timed out */
		dispatchException |= DE_TERMINATE;
		isItTimeToYield = TRUE;
		return(0);
	    }
#endif /* STARTSERVER */

	    {
		extern pointer AuEventQueue;

		if (AuEventQueue)
		    return 0;
	    }
	}
	else
	{
	    if (AnyClientsWriteBlocked && ANYSET (clientsWritable))
	    {
		NewOutputPending = TRUE;
		ORBITS(OutputPending, clientsWritable, OutputPending);
		UNSETBITS(ClientsWriteBlocked, clientsWritable);
		if (! ANYSET(ClientsWriteBlocked))
		    AnyClientsWriteBlocked = FALSE;
	    }

	    MASKANDSETBITS(clientsReadable, LastSelectMask, AllClients); 
	    if (LastSelectMask[0] & WellKnownConnections) 
		QueueWorkProc(EstablishNewConnections, NULL,
			      (pointer)LastSelectMask[0]);
	    if (ANYSET (clientsReadable))
		break;
	}
    }

    nready = 0;
    if (ANYSET(clientsReadable))
    {
	for (i=0; i<mskcnt; i++)
	{
	    while (clientsReadable[i])
	    {
		curclient = ffs (clientsReadable[i]) - 1;
		pClientsReady[nready++] = 
			ConnectionTranslation[curclient + (i << 5)];
		clientsReadable[i] &= ~(1 << curclient);
	    }
	}	
    }
    return nready;
}

#ifndef ANYSET
/*
 * This is not always a macro.
 */
ANYSET(src)
    long	*src;
{
    int i;

    for (i=0; i<mskcnt; i++)
	if (src[ i ])
	    return (TRUE);
    return (FALSE);
}
#endif

#else /* AMOEBA || _MINIX */
#ifdef AMOEBA
int init_waiters = 0;
semaphore init_sema;

/*
 * Force caller thread to wait until main has
 * finished the initialization
 */
void
WaitForInitialization()
{
    init_waiters++;
    sema_down(&init_sema);
}

static semaphore main_sema;

/*
 * The audio-server consists of one main thread, running the non re-entrant
 * audio code, and a number of auxilary threads that take care of reading
 * the input streams, and input devices. The following set of routines
 * wake up the main thread when it has something to do.
 */
void
InitMainThread()
{
    sema_init(&main_sema, 0);
}

void
WakeUpMainThread()
{
    sema_up(&main_sema);
}

static int
SleepMainThread(timo)
    interval timo;
{

    return (sema_trydown(&main_sema, timo) == 0) ? 0 : -1;
}

int
WaitForSomething(pClientsReady)
    int		*pClientsReady;
{
    register int	i, wt, nt;
    struct timeval	*wtp;
    long        	alwaysCheckForInput[2];
    int 		nready;

    /*
     * First, wakeup threads in initial sleep
     */
    if (init_waiters > 0) {
	while (init_waiters-- > 0)
	    sema_up(&init_sema);
    }

    /*
     * Be sure to check for input on every sweep in the dispatcher.
     * This routine should be in InitInput, but since this is more
     * or less a device dependent routine, and the semantics of it
     * are device independent I decided to put it here.
     */
    alwaysCheckForInput[0] = 0;
    alwaysCheckForInput[1] = 1;
    SetInputCheck(&alwaysCheckForInput[0], &alwaysCheckForInput[1]);

    while (TRUE) {
	/*
	 * Deal with any blocked jobs
	 */
	if (workQueue) ProcessWorkQueue();

	wt = -1;

	/*
	 * Check for new clients. We do this here and not in the
	 * listener() threads because we cannot be sure that dix
	 * is re-entrant, and we need to call some dix routines
	 * during startup.
	 */
	if (nNewConns) EstablishNewConnections();

	/*
	 * Every device driver can install handlers which are called after
	 * a certain amount of time. These handlers implement, for example,
	 * key repeat on a Sun. The following construction will determine
	 * the correct time-out value, given the available handlers. For
	 * compatibility the timeout is a timeval structure.
	 */
	wtp = (struct timeval *) NULL;
	BlockHandler((pointer)&wtp, (pointer)NULL);
	if (wtp) wt = (wtp->tv_sec * 1000) + (wtp->tv_usec / 1000);

	/*
	 * Check for clients needing attention. They might want to
	 * die or they might have input. In the second case, only
	 * accept from the grabClient (if there is one).
	 */
	for (i = 0, nready = 0; i < maxClient; i++) {
	    if (Clients[i] && Clients[i]->osPrivate) {
		register OsCommPtr oc = (OsCommPtr)Clients[i]->osPrivate;
		register int n;

		if (oc->status & CONN_KILLED) {
		    CloseDownClient(Clients[i]);
		    if (maxClient == i) maxClient--;
		    continue;
		}
		if ((n = am_avail(oc, VC_IN)) < 0) {
		    CloseDownClient(Clients[i]);
		    if (maxClient == i) maxClient--;
		    continue;
		}
		if (n > 0 || oc->status & REQ_PUSHBACK) {
		    if (grabClient == NULL || grabClient == Clients[i]) {
			*pClientsReady++ = Clients[i]->index;
			nready++;
		    }
		}
	    }
	}

	/*
	 * Well, if we found some work, or the hardware has
	 * events available, we return.
	 */
	if (nready || AmoebaEventsAvailable()) break;

	/*
	 * Nothing interesting is available. Go to sleep with a
	 * timeout and the other threads will wake us when needed.
	 */
	if (dispatchException) return 0;
	i = SleepMainThread(wt);

	/*
	 * Wake up any of the sleeping handlers
	 */
	WakeupHandler((unsigned long)0, (pointer)NULL);
	if (dispatchException) return 0;

	/*
	 * An error or timeout occurred
	 */
	if (i == -1) return 0;
    }
    return nready;
}
#endif /* AMOEBA */

#ifdef _MINIX
static int timed_fwait();

int
WaitForSomething(pClientsReady)
    int *pClientsReady;
{
    long timeout;
    struct timeval waittime[2];
    int nready;
    struct fwait fw;
    asio_fd_set_t wait_fd_set;
    int i, r;
    int fw_fd, fw_operation, fw_result, fw_errno;

    /* We need a while loop here to handle 
       crashed connections and the screen saver timeout */
    nready= 0;
    while (1)
    {
	/* deal with any blocked jobs */
	if (workQueue)
	    ProcessWorkQueue();

	wait_fd_set= InprogressFdSet;

	/* Let's fill in the fwait structure */
	fw.fw_flags= FWF_MORE;	/* Ignored by the kernel, but makes loop 
				 * termination easier
				 */

	fw.fw_bits= wait_fd_set.afds_bits;
	fw.fw_maxfd= ASIO_FD_SETSIZE;

	if (AnyClientsWithInput)
		fw.fw_flags |= FWF_NONBLOCK;

	BlockHandler((pointer)waittime, (pointer)&wait_fd_set);
	if (NewOutputPending)
	    FlushAllOutput();
	for(;fw.fw_flags & FWF_MORE; fw.fw_flags |= FWF_NONBLOCK)
	{
	    /* keep this check close to select() call to minimize race */
	    if (dispatchException)
	    {
		r = -1;
		errno= EAGAIN;
	    }
	    else if (waittime[0].tv_sec != 0)
	    {
	    	assert(waittime[0].tv_sec >= waittime[1].tv_sec);
		r= timed_fwait(&fw, &waittime[0]);
	    }
	    else
		r= fwait(&fw);
	    if (r == -1)
	    	break;
	    fw_fd= fw.fw_fd;
	    fw_operation= fw.fw_operation;
	    fw_result= fw.fw_result;
	    fw_errno= fw.fw_errno;
	    if (ASIO_FD_ISSET(fw_fd, fw_operation, &ListenFdSet))
	    {
	    	/* Got a new connection */
	    	EnqueueNewConnection(fw_fd, fw_operation, fw_result, fw_errno);
		fw.fw_fd= -1;
	    	continue;
	    }
	    if (ASIO_FD_ISSET(fw_fd, fw_operation, &ClientFdSet))
	    {
	    	/* The read or write of a client is done */
	    	UpdateClientIOStatus(fw_fd, fw_operation, fw_result, fw_errno);
		fw.fw_fd= -1;

		/* Store the client in the ready set if the operation was a
		 * read
		 */
		if (fw_operation == ASIO_READ)
		{
		    pClientsReady[nready++] = ConnectionTranslation[fw_fd];
		}
		continue;
	    }

	    /* Only thing left is a device, let's break out of this loop */
	    break;
	}
	if (r == -1)
	{
	    if (errno != EINTR && errno != EAGAIN)
		    FatalError("WaitForSomething(): fwait error: %s\n",
			strerror(errno));
	    WakeupHandler(0, NULL);	/* Nothing happend to a device */
	}
	else
	{
	    WakeupHandler(0, (pointer)&fw);
	    if (fw.fw_fd != -1)
	    	FatalError("Unable to locate module for completed I/O\n");
	}
	if (r < 0) /* An error or timeout occurred */
	{

	    if (dispatchException)
		return 0;
	    if (*checkForInput[0] != *checkForInput[1])
		return 0;
	}

	break;
    }

    if (AnyClientsWithInput)
    {
    	/* These were left over from the previous round */
    	AnyClientsWithInput= FALSE;
    	for (i= 0; i<ASIO_FD_SETSIZE; i++)
    	{
    		if (ASIO_FD_ISSET(i, ASIO_READ, &CompletedFdSet))
    		{
		    if (GrabInProgress && !ASIO_FD_ISSET(i, ASIO_READ,
								&GrabFdSet))
		    {
		    	continue;
		    }
		    if (ASIO_FD_ISSET(i, ASIO_READ, &IgnoreFdSet))
		    	continue;
		    pClientsReady[nready++] = ConnectionTranslation[i];
		}
	}
    }
    return nready;
}

static int timer_running= FALSE;
static struct timeval timer_value;
static int tf_critical= FALSE;
static int tf_expired= FALSE;

void tf_handler(sig)
int sig;
{
	struct timeval tv;

	tf_expired= TRUE;
	if (!tf_critical)
	{
		timer_running= FALSE;
		return;
	}
	signal(SIGALRM, tf_handler);
	sysutime(UTIME_TIMEOFDAY, &tv);
	tv.tv_sec++;
	/* Fake a high value to force to timer to be reloaded */
	timer_value.tv_sec= tv.tv_sec + 1000000;
	sysutime(UTIME_SETALARM, &tv);
}

static int
timed_fwait(fwp, tvp)
struct fwait *fwp;
struct timeval *tvp;
{
	struct timeval tv;
	int r;

#if DEBUG & 256
 { sysutime(UTIME_TIMEOFDAY, &tv); tv.tv_sec= tvp->tv_sec - tv.tv_sec;
 	tv.tv_usec= tvp->tv_usec - tv.tv_usec; if (tv.tv_usec < 0)
 	{ tv.tv_usec += 1000000; tv.tv_sec--; }
 	ErrorF("timed_fwait: timeout at now+%d.%06d\n", tv.tv_sec, 
 	tv.tv_usec); }
#endif

	/* Assume that only timed_fwait is allowed to let the timer running
	 * between calls.
	 */
	tv= *tvp;
	if (!timer_running)
	{
		signal(SIGALRM, tf_handler);
		sysutime(UTIME_SETALARM, &tv);
		assert(tv.tv_sec == 0);
		timer_value= *tvp;
		timer_running= TRUE;
	}
	else if (tv.tv_sec < timer_value.tv_sec || 
		(tv.tv_sec == timer_value.tv_sec && 
		tv.tv_usec < timer_value.tv_usec))
	{
		/* If the previous timer expires just before we set the 
		 * new timer, the handler is lost unless tf_critical is set,
		 * then the handler will set a new new timer 1 second later.
		 */
		tf_critical= TRUE;
		sysutime(UTIME_SETALARM, &tv);
		timer_value= *tvp;
		tf_critical= FALSE;
	}
	tf_critical= TRUE;
	if (tf_expired)
	{
		tf_critical= FALSE;
		tf_expired= FALSE;
		errno= EINTR;
		return -1;
	}
	r= fwait(fwp);
	tf_critical= FALSE;
	return r;
}
#endif /* _MINIX */
#endif /* AMOEBA || _MINIX */