joe-beuhler-patches-20031122
[openafs.git] / src / lwp / iomgr.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*******************************************************************\
11 *                                                                   *
12 *       Information Technology Center                               *
13 *       Carnegie-Mellon University                                  *
14 *                                                                   *
15 *                                                                   *
16 *                                                                   *
17 \*******************************************************************/
18
19
20 /*
21         IO Manager routines & server process for VICE server.
22 */
23
24 #include <afsconfig.h>
25 #include <afs/param.h>
26
27 RCSID("$Header$");
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #ifdef AFS_NT40_ENV
33 #include <winsock2.h>
34 #include <malloc.h>
35 extern void lwp_abort(void);
36 #else
37 #include <unistd.h>             /* select() prototype */
38 #include <sys/types.h>          /* fd_set on older platforms */
39 #include <sys/time.h>           /* struct timeval, select() prototype */
40 #ifndef FD_SET
41 # include <sys/select.h>        /* fd_set on newer platforms */
42 #endif
43 #include <sys/file.h>
44 #endif /* AFS_NT40_ENV */
45 #include "lwp.h"
46 #include "timer.h"
47 #include <signal.h>
48 #include <errno.h>
49 #ifdef AFS_SUN5_ENV
50 #include <fcntl.h>
51 #endif
52 #ifdef AFS_DJGPP_ENV
53 #include "dosdefs95.h"
54 #include "netbios95.h"
55 #include <sys/socket.h>
56 #include <sys/farptr.h>
57 #include <dpmi.h>
58 #include <go32.h>
59 #include <crt0.h>
60 int _crt0_startup_flags = _CRT0_FLAG_LOCK_MEMORY;
61 #endif /* AFS_DJGPP_ENV */
62
63 #if     defined(USE_PTHREADS) || defined(USE_SOLARIS_THREADS)
64
65 void IOMGR_Initialize() /* noop */
66 { }
67
68 void IOMGR_Sleep (seconds)
69   unsigned seconds;
70 {
71     struct timespec itv;
72
73     itv.tv_sec = seconds;
74     itv.tv_nsec = 0;
75     assert(pthread_mutex_unlock(&lwp_mutex) == 0);
76     assert(pthread_delay_np(&itv) == 0);
77     assert(pthread_mutex_lock(&lwp_mutex) == 0);
78 }
79
80 #else
81
82 #ifdef  AFS_DECOSF_ENV
83 extern void *malloc();
84 #endif  /* AFS_DECOSF_ENV */
85
86 typedef unsigned char bool;
87 #define FALSE   0
88 #define TRUE    1
89
90 #ifndef MIN
91 #define MIN(a,b) ((a)>(b)) ? b : a
92 #endif
93
94 #ifndef NSIG
95 #define NSIG 8*sizeof(sigset_t)
96 #endif
97
98 static int SignalSignals();
99 \f
100 /********************************\
101 *                                *
102 *  Stuff for managing IoRequests *
103 *                                *
104 \********************************/
105
106 struct IoRequest {
107
108     /* Pid of process making request (for use in IOMGR_Cancel */
109     PROCESS             pid;
110
111     /* Descriptor masks for requests */
112     int                 nfds;
113     fd_set              *readfds;
114     fd_set              *writefds;
115     fd_set              *exceptfds;
116
117     struct TM_Elem      timeout;
118
119     /* Result of select call */
120     long                        result;
121
122 #ifdef AFS_DJGPP_ENV
123     NCB                  *ncbp;
124     dos_ptr              dos_ncb;
125 #endif /* AFS_DJGPP_ENV */
126
127 };
128 \f
129 /********************************\
130 *                                *
131 *  Stuff for managing signals    *
132 *                                *
133 \********************************/
134
135 #define badsig(signo)           (((signo) <= 0) || ((signo) >= NSIG))
136 #define mysigmask(signo)                (1 << ((signo)-1))
137
138
139 fd_set openMask;                /* mask of open files on an IOMGR abort */
140 static afs_int32 sigsHandled;   /* sigmask(signo) is on if we handle signo */
141 static int anySigsDelivered;            /* true if any have been delivered. */
142 #ifndef AFS_NT40_ENV
143 static struct sigaction oldActions[NSIG];       /* the old signal vectors */
144 #endif
145 static char *sigEvents[NSIG];           /* the event to do an LWP signal on */
146 static int sigDelivered[NSIG];          /* True for signals delivered so far.
147                                            This is an int array to make sure
148                                            there are no conflicts when trying
149                                            to write it */
150 /* software 'signals' */
151 #define NSOFTSIG                4
152 static int (*sigProc[NSOFTSIG])();
153 static char *sigRock[NSOFTSIG];
154
155 \f
156 static struct IoRequest *iorFreeList = 0;
157
158 static struct TM_Elem *Requests;        /* List of requests */
159 static struct timeval iomgr_timeout;    /* global so signal handler can zap it */
160
161 /* stuff for debugging */
162 static int iomgr_errno;
163 static struct timeval iomgr_badtv;
164 static PROCESS iomgr_badpid;
165 static void SignalIO(int fds, fd_set *rfds, fd_set *wfds, fd_set *efs,
166                     int code);
167 static void SignalTimeout(int code, struct timeval *timeout);
168
169 #ifdef AFS_DJGPP_ENV
170 /* handle Netbios NCB completion */
171 static int NCB_fd;
172 int anyNCBComplete = FALSE;
173 int handler_seg, handler_off;  /* seg:off of NCB completion handler */
174 static __dpmi_regs        callback_regs;
175 static _go32_dpmi_seginfo callback_info;
176 #endif /* AFS_DJGPP_ENV */
177
178 /* fd_set pool managment. 
179  * Use the pool instead of creating fd_set's on the stack. fd_set's can be
180  * 2K in size, so making three could put 6K in the limited space of an LWP
181  * stack.
182  */
183 struct IOMGR_fd_set {
184     struct IOMGR_fd_set *next;
185 } *iomgrFreeFDSets = (struct IOMGR_fd_set*)0;
186
187 /* IOMGR_FreeFDSet
188  * Return fd_set to the free list.
189  */
190 void IOMGR_FreeFDSet(fd_set *s)
191 {
192     struct IOMGR_fd_set *t = (struct IOMGR_fd_set *)s;
193
194     t->next = iomgrFreeFDSets;
195     iomgrFreeFDSets = t;
196 }
197
198 /* IOMGR_AllocFDSet
199  * returns a zeroed fd_set or null if could not malloc one.
200  */
201 fd_set *IOMGR_AllocFDSet(void)
202 {
203     struct IOMGR_fd_set *t;
204     if (iomgrFreeFDSets) {
205         t =  iomgrFreeFDSets;
206         iomgrFreeFDSets = iomgrFreeFDSets->next;
207     }
208     else {
209         t = (struct IOMGR_fd_set *)malloc(sizeof(fd_set));
210     }
211     if (!t)
212         return (fd_set*)0;
213     else {
214         FD_ZERO((fd_set*)t);
215         return (fd_set*)t;
216     }
217 }
218
219 #define FreeRequest(x) ((x)->result = (long) iorFreeList, iorFreeList = (x))
220
221 static struct IoRequest *NewRequest()
222 {
223     struct IoRequest *request;
224
225     if ((request=iorFreeList))
226         iorFreeList = (struct IoRequest *) (request->result);
227     else request = (struct IoRequest *) malloc(sizeof(struct IoRequest));
228
229     memset((char*)request, 0, sizeof(struct IoRequest));
230     return request;
231 }
232
233 #define Purge(list) FOR_ALL_ELTS(req, list, { free(req->BackPointer); })
234
235 \f
236 /* FD_SET support routines. All assume the fd_set size is a multiple of an int
237  * so we can at least do logical operations on ints instead of chars.
238  *
239  * For each routine, nfds is the highest bit set in either fd_set, starting
240  * with no bits == 0.
241  */
242 #ifdef AFS_NT40_ENV
243 #define FD_N_ZERO(A, x) FD_ZERO(x)
244 #else
245 #define FDS_P_POS (sizeof(int)*8)
246 #define INTS_PER_FDS(x) (((x)+(FDS_P_POS-1)) / FDS_P_POS)
247 #define FD_N_ZERO(nfds, x) memset((char*)(x), 0, (INTS_PER_FDS(nfds))*sizeof(int))
248 #endif
249
250 #if defined(AFS_LINUX22_ENV) && (__GLIBC_MINOR__ > 0)
251 /* Build for both glibc 2.0.x and 2.1.x */
252 #define FDS_BITS __fds_bits
253 #else
254 #define FDS_BITS fds_bits
255 #endif
256
257 /* FDSetCmp - returns 1 if any bits in fd_set1 are also set in fd_set2.
258  * If nfds is 0, or one of the fd_sets is null return 0 (since there is no bit
259  * set in both fd_sets).
260  */
261 static int FDSetCmp(int nfds, fd_set *fd_set1, fd_set *fd_set2)
262 {
263     unsigned int i, j;
264
265     if (fd_set1 == (fd_set*)0 || fd_set2 == (fd_set*)0)
266         return 0;
267
268 #ifdef AFS_NT40_ENV
269     if (fd_set1->fd_count == 0 || fd_set2->fd_count == 0)
270         return 0;
271
272     for (i=0; i<fd_set1->fd_count; i++) {
273         for (j=0; j<fd_set2->fd_count; j++) {
274         if (fd_set1->fd_array[i] == fd_set2->fd_array[j])
275             return 1;
276         }
277     }
278 #else
279     if (nfds == 0)
280         return 0;
281
282     j = INTS_PER_FDS(nfds);
283     for (i=0; i<j; i++) {
284         if (fd_set1->FDS_BITS[i] & fd_set2->FDS_BITS[i])
285             return 1;
286     }
287 #endif
288     return 0;
289 }
290
291 /* FDSetSet - set bits from fd_set2 into fd_set1
292  */
293 static void FDSetSet(int nfds, fd_set *fd_set1, fd_set *fd_set2)
294 {
295     unsigned int i;
296
297     if (fd_set1 == (fd_set*)0 || fd_set2 == (fd_set*)0)
298         return;
299
300 #ifdef AFS_NT40_ENV
301     if (fd_set2->fd_count==0)
302         return;
303
304     for (i=0; i<fd_set2->fd_count; i++)
305         FD_SET(fd_set2->fd_array[i], fd_set1);
306 #else
307     if (nfds == 0)
308         return;
309
310     for (i=0,n = INTS_PER_FDS(nfds); i<n; i++) {
311         fd_set1->FDS_BITS[i] |= fd_set2->FDS_BITS[i];
312     }
313 #endif
314 }
315
316 /* FDSetAnd - fd_set1  <- fd_set1 & fd_set2. 
317  */
318 #ifdef AFS_NT40_ENV
319 static void FDSetAnd(int nfds, fd_set *fd_set1, fd_set *fd_set2)
320 {
321     unsigned int i;
322     fd_set tmpset;
323
324     if (fd_set1 == NULL || fd_set1->fd_count == 0)
325         return;
326     
327     if (fd_set2 == NULL || fd_set2->fd_count == 0) {
328         FD_ZERO(fd_set1);
329     }
330     else {
331         FD_ZERO(&tmpset);
332         for (i=0; i<fd_set2->fd_count; i++) {
333             if (FD_ISSET(fd_set2->fd_array[i], fd_set1))
334                 FD_SET(fd_set2->fd_array[i], &tmpset);
335         }
336         *fd_set1 = tmpset;
337     }
338 }
339 #else
340 static void FDSetAnd(int nfds, fd_set *fd_set1, fd_set *fd_set2)
341 {
342     int i, n;
343
344     if (nfds == 0 || fd_set1 == (fd_set*)0 || fd_set2 == (fd_set*)0)
345         return;
346
347     n = INTS_PER_FDS(nfds);
348     for (i=0; i<n; i++) {
349         fd_set1->FDS_BITS[i] &= fd_set2->FDS_BITS[i];
350     }
351 }
352 #endif
353             
354 /* FDSetEmpty - return true if fd_set is empty 
355  */
356 static int FDSetEmpty(int nfds, fd_set *fds)
357 {
358 #ifndef AFS_NT40_ENV
359     int i, n;
360
361     if (nfds == 0)
362         return 1;
363 #endif
364     if (fds == (fd_set*)0)
365         return 1;
366
367 #ifdef AFS_NT40_ENV
368     if (fds->fd_count == 0)
369         return 1;
370     else
371         return 0;
372 #else
373     n = INTS_PER_FDS(nfds);
374
375     for (i=n-1; i>=0; i--) {
376         if (fds->FDS_BITS[i])
377             break;
378     }
379
380     if (i>=0)
381         return 0;
382     else
383         return 1;
384 #endif
385 }
386
387 /* The IOMGR process */
388
389 /*
390  * Important invariant: process->iomgrRequest is null iff request not in timer
391  * queue.
392  * also, request->pid is valid while request is in queue,
393  * also, don't signal selector while request in queue, since selector frees
394  *  request.
395  */
396
397 /* These are not declared in IOMGR so that they don't use up 6K of stack. */
398 static fd_set IOMGR_readfds, IOMGR_writefds, IOMGR_exceptfds;
399 static int IOMGR_nfds = 0;
400
401 static int IOMGR(void *dummy)
402 {
403     for (;;) {
404         int code;
405         struct TM_Elem *earliest;
406         struct timeval timeout, junk;
407         bool woke_someone;
408
409         FD_ZERO(&IOMGR_readfds);
410         FD_ZERO(&IOMGR_writefds);
411         FD_ZERO(&IOMGR_exceptfds);
412         IOMGR_nfds = 0;
413
414         /* Wake up anyone who has expired or who has received a
415            Unix signal between executions.  Keep going until we
416            run out. */
417         do {
418             woke_someone = FALSE;
419             /* Wake up anyone waiting on signals. */
420             /* Note: SignalSignals() may yield! */
421             if (anySigsDelivered && SignalSignals ())
422                 woke_someone = TRUE;
423 #ifndef AFS_DJGPP_ENV
424             FT_GetTimeOfDay(&junk, 0);    /* force accurate time check */
425 #endif
426             TM_Rescan(Requests);
427             for (;;) {
428                 register struct IoRequest *req;
429                 struct TM_Elem *expired;
430                 expired = TM_GetExpired(Requests);
431                 if (expired == NULL) break;
432                 woke_someone = TRUE;
433                 req = (struct IoRequest *) expired -> BackPointer;
434 #ifdef DEBUG
435                 if (lwp_debug != 0) puts("[Polling SELECT]");
436 #endif /* DEBUG */
437                 /* no data ready */
438                 if (req->readfds)   FD_N_ZERO(req->nfds, req->readfds);
439                 if (req->writefds)  FD_N_ZERO(req->nfds, req->writefds);
440                 if (req->exceptfds) FD_N_ZERO(req->nfds, req->exceptfds);
441                 req->nfds = 0;
442                 req->result = 0; /* no fds ready */
443                 TM_Remove(Requests, &req->timeout);
444 #ifdef DEBUG
445                 req -> timeout.Next = (struct TM_Elem *) 2;
446                 req -> timeout.Prev = (struct TM_Elem *) 2;
447 #endif /* DEBUG */
448                 LWP_QSignal(req->pid);
449                 req->pid->iomgrRequest = 0;
450             }
451
452 #ifdef AFS_DJGPP_ENV
453             if (IOMGR_CheckNCB())    /* check for completed netbios requests */
454               woke_someone = TRUE;
455 #endif /* AFS_DJGPP_ENV */
456
457             if (woke_someone) LWP_DispatchProcess();
458         } while (woke_someone);
459
460         /* Collect requests & update times */
461         FD_ZERO(&IOMGR_readfds);
462         FD_ZERO(&IOMGR_writefds);
463         FD_ZERO(&IOMGR_exceptfds);
464         IOMGR_nfds = 0;
465
466         FOR_ALL_ELTS(r, Requests, {
467             register struct IoRequest *req;
468             req = (struct IoRequest *) r -> BackPointer;
469             FDSetSet(req->nfds, &IOMGR_readfds,   req->readfds);
470             FDSetSet(req->nfds, &IOMGR_writefds,  req->writefds);
471             FDSetSet(req->nfds, &IOMGR_exceptfds, req->exceptfds);
472             if (req->nfds > IOMGR_nfds)
473                 IOMGR_nfds = req->nfds;
474         })
475         earliest = TM_GetEarliest(Requests);
476         if (earliest != NULL) {
477             timeout = earliest -> TimeLeft;
478
479
480             /* Do select */
481 #ifdef DEBUG
482             if (lwp_debug != 0) {
483 #ifdef AFS_NT40_ENV
484                 int idbg;
485                 printf("[Read Select:");
486                 if (IOMGR_readfds.fd_count == 0)
487                     printf(" none]\n");
488                 else {
489                     for (idbg=0; idbg<IOMGR_readfds.fd_count; idbg++)
490                         printf(" %d", IOMGR_readfds.fd_array[idbg]);
491                     printf("]\n");
492                 }
493                 printf("[Write Select:");
494                 if (IOMGR_writefds.fd_count == 0)
495                     printf(" none]\n");
496                 else {
497                     for (idbg=0; idbg<IOMGR_writefds.fd_count; idbg++)
498                         printf(" %d", IOMGR_writefds.fd_array[idbg]);
499                     printf("]\n");
500                 }
501                 printf("[Except Select:");
502                 if (IOMGR_exceptfds.fd_count == 0)
503                     printf(" none]\n");
504                 else {
505                     for (idbg=0; idbg<IOMGR_exceptfds.fd_count; idbg++)
506                         printf(" %d", IOMGR_exceptfds.fd_array[idbg]);
507                     printf("]\n");
508                 }
509 #else
510                 /* Only prints first 32. */
511                 printf("[select(%d, 0x%x, 0x%x, 0x%x, ", IOMGR_nfds,
512                        *(int*)&IOMGR_readfds, *(int*)&IOMGR_writefds,
513                        *(int*)&IOMGR_exceptfds);
514 #endif /* AFS_NT40_ENV */
515                 if (timeout.tv_sec == -1 && timeout.tv_usec == -1)
516                     puts("INFINITE)]");
517                 else
518                     printf("<%d, %d>)]\n", timeout.tv_sec, timeout.tv_usec);
519             }
520 #endif /* DEBUG */
521             iomgr_timeout = timeout;
522             if (timeout.tv_sec == -1 && timeout.tv_usec == -1) {
523                 /* infinite, sort of */
524                 iomgr_timeout.tv_sec = 100000000;
525                 iomgr_timeout.tv_usec = 0;
526             }
527 #ifdef AFS_NT40_ENV
528             /* On NT, signals don't interrupt a select call. So this can potentially
529              * lead to long wait times before a signal is honored. To avoid this we
530              * dont do select() for longer than IOMGR_MAXWAITTIME (5 secs) */
531             if (iomgr_timeout.tv_sec > (IOMGR_MAXWAITTIME - 1)) {
532               iomgr_timeout.tv_sec = IOMGR_MAXWAITTIME;
533               iomgr_timeout.tv_usec = 0;
534             }
535 #endif /* NT40 */
536
537 #ifdef AFS_DJGPP_ENV
538             /* We do this also for the DOS-box Win95 client, since
539                NCB calls don't interrupt a select, but we want to catch them
540                in a reasonable amount of time (say, half a second). */
541             iomgr_timeout.tv_sec = 0;
542             iomgr_timeout.tv_usec = IOMGR_WIN95WAITTIME;
543 #endif /* DJGPP */
544
545             /* Check one last time for a signal delivery.  If one comes after
546                this, the signal handler will set iomgr_timeout to zero, causing
547                the select to return immediately.  The timer package won't return
548                a zero timeval because all of those guys were handled above.
549
550                I'm assuming that the kernel masks signals while it's picking up
551                the parameters to select.  This may a bad assumption.  -DN */
552             if (anySigsDelivered)
553                 continue;       /* go to the top and handle them. */
554
555 #ifdef AFS_DJGPP_ENV
556             if (IOMGR_CheckNCB())    /* check for completed netbios requests */
557               LWP_DispatchProcess();
558 #endif /* AFS_DJGPP_ENV */
559
560 #ifdef AFS_NT40_ENV
561             if (IOMGR_readfds.fd_count == 0 && IOMGR_writefds.fd_count == 0
562                 && IOMGR_exceptfds.fd_count == 0) {
563                 DWORD stime;
564                 code = 0;
565                 if (iomgr_timeout.tv_sec || iomgr_timeout.tv_usec) {
566                     stime = iomgr_timeout.tv_sec * 1000
567                         + iomgr_timeout.tv_usec/1000;
568                     if (!stime)
569                         stime = 1;
570                     Sleep(stime);
571                 }
572             }
573             else
574 #endif
575                 {    /* select runs much faster if 0's are passed instead of &0s */
576                     code = select(IOMGR_nfds,
577                                   (FDSetEmpty(IOMGR_nfds, &IOMGR_readfds)) ?
578                                   (fd_set*)0 : &IOMGR_readfds,
579                                   (FDSetEmpty(IOMGR_nfds, &IOMGR_writefds)) ?
580                                   (fd_set*)0 : &IOMGR_writefds,
581                                   (FDSetEmpty(IOMGR_nfds, &IOMGR_exceptfds)) ?
582                                   (fd_set*)0 : &IOMGR_exceptfds,
583                                   &iomgr_timeout);
584                 }
585
586             if (code < 0) {
587                int e=1;
588
589 #if defined(AFS_SUN_ENV)
590                /* Tape drives on Sun boxes do not support select and return ENXIO */
591                if (errno == ENXIO) e=0, code=1;
592 #endif
593 #if defined(AFS_SGI_ENV) || defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV) || defined(AFS_AIX32_ENV)
594                /* For SGI and SVR4 - poll & select can return EAGAIN ... */
595                if (errno == EAGAIN) e=0;
596 #endif
597 #if defined(AFS_SUN5_ENV)
598                /* On sun4x_55, select doesn't block signal. It could be
599                   interupted by a signal that changes iomgr_timeout, and
600                   then select returns with EINVAL. In this case, we need
601                   to retry.
602                 */
603                if (errno==EINVAL && anySigsDelivered)
604                    e = 0;
605 #endif /* AFS_SUN5_ENV */
606
607                if ((errno != EINTR) && e) {
608 #ifndef AFS_NT40_ENV
609                   int i;
610                   for(i=0; i<FD_SETSIZE; i++) {
611                      if (fcntl(i, F_GETFD, 0) < 0 && errno == EBADF)
612                          FD_SET(i, &openMask);
613                   }
614 #endif
615                   iomgr_errno = errno;
616                   lwp_abort();
617                }
618             }
619
620             /* See what happened */
621             if (code > 0) {
622                 /* Action -- wake up everyone involved */
623                 SignalIO(IOMGR_nfds, &IOMGR_readfds, &IOMGR_writefds,
624                          &IOMGR_exceptfds, code);
625             }
626             else if (code == 0
627                 && (iomgr_timeout.tv_sec != 0 || iomgr_timeout.tv_usec != 0)) {
628                 /* Real timeout only if signal handler hasn't set
629                    iomgr_timeout to zero. */
630
631 #ifdef AFS_NT40_ENV
632                 /* On NT, real timeout only if above and if iomgr_timeout
633                  * interval is equal to timeout interval (i.e., not adjusted
634                  * to check for pseudo-signals).
635                  */
636                 if (iomgr_timeout.tv_sec  != timeout.tv_sec ||
637                     iomgr_timeout.tv_usec != timeout.tv_usec) {
638                     /* signal check interval timed out; not real timeout */
639                     continue;
640                 }
641 #endif /* AFS_NT40_ENV */
642 #ifndef AFS_DJGPP_ENV
643                 FT_GetTimeOfDay(&junk, 0);
644 #endif
645                 SignalTimeout(code, &timeout);
646             }
647 #ifdef AFS_DJGPP_ENV
648             IOMGR_CheckNCB();
649 #endif /* AFS_DJGPP_ENV */
650         }
651         LWP_DispatchProcess();
652     }
653     return -1; /* keeps compilers happy. */
654 }
655 \f
656 /************************\
657 *                        *
658 *  Signalling routines   *
659 *                        *
660 \************************/
661
662 static void SignalIO(int fds, fd_set *readfds, fd_set *writefds,
663                      fd_set *exceptfds, int code)
664 {
665     int nfds;
666     /* Look at everyone who's bit mask was affected */
667     FOR_ALL_ELTS(r, Requests, {
668         register struct IoRequest *req;
669         register PROCESS pid;
670         req = (struct IoRequest *) r -> BackPointer;
671         nfds = MIN(fds, req->nfds);
672         if (FDSetCmp(nfds, req->readfds, readfds) ||
673             FDSetCmp(nfds, req->writefds, writefds) ||
674             FDSetCmp(nfds, req->exceptfds, exceptfds)) {
675             /* put ready fd's into request. */
676             FDSetAnd(nfds, req->readfds, readfds);
677             FDSetAnd(nfds, req->writefds, writefds);
678             FDSetAnd(nfds, req->exceptfds, exceptfds);
679             req -> result = code;
680             TM_Remove(Requests, &req->timeout);
681             LWP_QSignal(pid=req->pid);
682             pid->iomgrRequest = 0;
683         }
684     })
685 }
686
687 static void SignalTimeout(int code, struct timeval *timeout)
688 {
689     /* Find everyone who has specified timeout */
690     FOR_ALL_ELTS(r, Requests, {
691         register struct IoRequest *req;
692         register PROCESS pid;
693         req = (struct IoRequest *) r -> BackPointer;
694         if (TM_eql(&r->TimeLeft, timeout)) {
695             req -> result = code;
696             TM_Remove(Requests, &req->timeout);
697             LWP_QSignal(pid=req->pid);
698             pid->iomgrRequest = 0;
699         } else
700             return;
701     })
702 }
703 \f
704 /*****************************************************\
705 *                                                     *
706 *  Signal handling routine (not to be confused with   *
707 *  signalling routines, above).                       *
708 *                                                     *
709 \*****************************************************/
710 static void SigHandler (signo)
711     int signo;
712 {
713     if (badsig(signo) || (sigsHandled & mysigmask(signo)) == 0)
714         return;         /* can't happen. */
715     sigDelivered[signo] = TRUE;
716     anySigsDelivered = TRUE;
717     /* Make sure that the IOMGR process doesn't pause on the select. */
718     iomgr_timeout.tv_sec = 0;
719     iomgr_timeout.tv_usec = 0;
720 }
721
722 /* Alright, this is the signal signalling routine.  It delivers LWP signals
723    to LWPs waiting on Unix signals. NOW ALSO CAN YIELD!! */
724 static int SignalSignals (void)
725 {
726     bool gotone = FALSE;
727     register int i;
728     register int (*p)();
729     afs_int32 stackSize;
730
731     anySigsDelivered = FALSE;
732
733     /* handle software signals */
734     stackSize = (AFS_LWP_MINSTACKSIZE < lwp_MaxStackSeen? lwp_MaxStackSeen : AFS_LWP_MINSTACKSIZE);
735     for (i=0; i < NSOFTSIG; i++) {
736         PROCESS pid;
737         if (p=sigProc[i]) /* This yields!!! */
738             LWP_CreateProcess2(p, stackSize, LWP_NORMAL_PRIORITY, 
739                                (void *) sigRock[i], "SignalHandler", &pid);
740         sigProc[i] = 0;
741     }
742
743     for (i = 1; i <= NSIG; ++i)  /* forall !badsig(i) */
744         if ((sigsHandled & mysigmask(i)) && sigDelivered[i] == TRUE) {
745             sigDelivered[i] = FALSE;
746             LWP_NoYieldSignal (sigEvents[i]);
747             gotone = TRUE;
748         }
749     return gotone;
750 }
751
752 \f
753 /***************************\
754 *                           *
755 *  User-callable routines   *
756 *                           *
757 \***************************/
758
759
760 /* Keep IOMGR process id */
761 static PROCESS IOMGR_Id = NULL;
762
763 int IOMGR_SoftSig(aproc, arock)
764 int (*aproc)();
765 char *arock; {
766     register int i;
767     for (i=0;i<NSOFTSIG;i++) {
768         if (sigProc[i] == 0) {
769             /* a free entry */
770             sigProc[i] = aproc;
771             sigRock[i] = arock;
772             anySigsDelivered = TRUE;
773             iomgr_timeout.tv_sec = 0;
774             iomgr_timeout.tv_usec = 0;
775             return 0;
776         }
777     }
778     return -1;
779 }
780
781
782 unsigned char allOnes[100];
783
784 int IOMGR_Initialize(void)
785 {
786     extern int TM_Init();
787     PROCESS pid;
788
789     /* If lready initialized, just return */
790     if (IOMGR_Id != NULL) return LWP_SUCCESS;
791
792     /* Init LWP if someone hasn't yet. */
793     if (LWP_InitializeProcessSupport (LWP_NORMAL_PRIORITY, &pid) != LWP_SUCCESS)
794         return -1;
795
796     /* Initialize request lists */
797     if (TM_Init(&Requests) < 0) return -1;
798
799     /* Initialize signal handling stuff. */
800     sigsHandled = 0;
801     anySigsDelivered = TRUE; /* A soft signal may have happened before
802         IOMGR_Initialize:  so force a check for signals regardless */
803     memset(allOnes, 0xff, sizeof(allOnes));
804
805 #ifdef AFS_DJGPP_ENV
806     install_ncb_handler();
807 #endif /* AFS_DJGPP_ENV */
808
809     return LWP_CreateProcess(IOMGR, AFS_LWP_MINSTACKSIZE, 0, (void *) 0, 
810                              "IO MANAGER", &IOMGR_Id);
811 }
812
813 int IOMGR_Finalize()
814 {
815     int status;
816
817     Purge(Requests)
818     TM_Final(&Requests);
819     status = LWP_DestroyProcess(IOMGR_Id);
820     IOMGR_Id = NULL;
821     return status;
822 }
823 \f
824 /* signal I/O for anyone who is waiting for a FD or a timeout; not too cheap,
825  * since forces select and timeofday check */
826 int IOMGR_Poll(void) {
827     fd_set *readfds, *writefds, *exceptfds;
828     afs_int32 code;
829     struct timeval tv;
830     int fds;
831
832     FT_GetTimeOfDay(&tv, 0);    /* force accurate time check */
833     TM_Rescan(Requests);
834     for (;;) {
835         register struct IoRequest *req;
836         struct TM_Elem *expired;
837         expired = TM_GetExpired(Requests);
838         if (expired == NULL) break;
839         req = (struct IoRequest *) expired -> BackPointer;
840 #ifdef DEBUG
841         if (lwp_debug != 0) puts("[Polling SELECT]");
842 #endif /* DEBUG */
843         /* no data ready */
844         if (req->readfds)   FD_N_ZERO(req->nfds, req->readfds);
845         if (req->writefds)  FD_N_ZERO(req->nfds, req->writefds);
846         if (req->exceptfds) FD_N_ZERO(req->nfds, req->exceptfds);
847         req->nfds = 0;
848         req->result = 0; /* no fds ready */
849         TM_Remove(Requests, &req->timeout);
850 #ifdef DEBUG
851         req -> timeout.Next = (struct TM_Elem *) 2;
852         req -> timeout.Prev = (struct TM_Elem *) 2;
853 #endif /* DEBUG */
854         LWP_QSignal(req->pid);
855         req->pid->iomgrRequest = 0;
856     }
857
858     /* Collect requests & update times */
859     readfds = IOMGR_AllocFDSet();
860     writefds = IOMGR_AllocFDSet();
861     exceptfds = IOMGR_AllocFDSet();
862     if (!(readfds && writefds && exceptfds)) {
863         fprintf(stderr, "IOMGR_Poll: Could not malloc space for fd_sets.\n");
864         fflush(stderr);
865     }
866
867     fds = 0;
868
869     FOR_ALL_ELTS(r, Requests, {
870         register struct IoRequest *req;
871         req = (struct IoRequest *) r -> BackPointer;
872         FDSetSet(req->nfds, readfds,   req->readfds);
873         FDSetSet(req->nfds, writefds,  req->writefds);
874         FDSetSet(req->nfds, exceptfds, req->exceptfds);
875         if (fds < req->nfds)
876             fds = req->nfds;
877     })
878         
879     tv.tv_sec = 0;
880     tv.tv_usec = 0;
881 #ifdef AFS_NT40_ENV
882     code = -1;
883     if (readfds->fd_count == 0 && writefds->fd_count == 0
884         && exceptfds->fd_count == 0)
885 #endif
886         code = select(fds, readfds, writefds, exceptfds, &tv);
887     if (code > 0) {
888         SignalIO(fds, readfds, writefds, exceptfds, code);
889     }
890
891     if (readfds) IOMGR_FreeFDSet(readfds);
892     if (writefds) IOMGR_FreeFDSet(writefds);
893     if (exceptfds) IOMGR_FreeFDSet(exceptfds);
894
895
896     LWP_DispatchProcess();  /* make sure others run */
897     LWP_DispatchProcess();
898     return 0;
899 }
900
901 int IOMGR_Select(fds, readfds, writefds, exceptfds, timeout)
902      int fds;
903      fd_set *readfds, *writefds, *exceptfds;
904      struct timeval *timeout;
905 {
906     register struct IoRequest *request;
907     int result;
908
909 #ifndef AFS_NT40_ENV
910     if(fds > FD_SETSIZE) {
911         fprintf(stderr, "IOMGR_Select: fds=%d, more than max %d\n",
912                 fds, FD_SETSIZE);
913         fflush(stderr);
914         lwp_abort();
915     }
916 #endif
917
918     /* See if polling request. If so, handle right here */
919     if (timeout != NULL) {
920         if (timeout->tv_sec == 0 && timeout->tv_usec == 0) {
921             int code;
922 #ifdef DEBUG
923             if (lwp_debug != 0) puts("[Polling SELECT]");
924 #endif /* DEBUG */
925 again:
926             code = select(fds, readfds, writefds, exceptfds, timeout);
927 #if     defined(AFS_SGI_ENV) || defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV) || defined(AFS_AIX32_ENV)
928             /*
929              * For SGI and SVR4 - poll & select can return EAGAIN ...
930              */
931             /*
932              * this is basically for SGI, but I believe stock SVR4 (Solaris?)
933              * can also get this error return
934              */
935             if (code < 0 && errno == EAGAIN)
936                 goto again;     
937 #endif
938 #ifdef AFS_NT40_ENV
939             if (code == SOCKET_ERROR) {
940                 if (WSAGetLastError() == WSAEINPROGRESS)
941                     goto again;
942
943                 code = -1;
944             }
945 #endif
946             return (code > 1 ? 1 : code);
947         }
948     }
949
950     /* Construct request block & insert */
951     request = NewRequest(); /* zeroes fd_set's */
952     if (readfds && !FDSetEmpty(fds, readfds))
953         request->readfds = readfds;
954     if (writefds && !FDSetEmpty(fds, writefds))
955         request->writefds = writefds;
956     if (exceptfds && !FDSetEmpty(fds, exceptfds))
957         request->exceptfds = exceptfds;
958     request->nfds = fds;
959
960     if (timeout == NULL) {
961         request -> timeout.TotalTime.tv_sec = -1;
962         request -> timeout.TotalTime.tv_usec = -1;
963     } else {
964         request -> timeout.TotalTime = *timeout;
965         /* check for bad request */
966         if (timeout->tv_sec < 0 || timeout->tv_usec < 0 || timeout->tv_usec > 999999) {
967             /* invalid arg */
968             iomgr_badtv = *timeout;
969             iomgr_badpid = LWP_ActiveProcess;
970             /* now fixup request */
971             if(request->timeout.TotalTime.tv_sec < 0)
972                 request->timeout.TotalTime.tv_sec = 1;
973             request->timeout.TotalTime.tv_usec = 100000;
974         }
975     }
976
977     request -> timeout.BackPointer = (char *) request;
978
979     /* Insert my PID in case of IOMGR_Cancel */
980     request -> pid = LWP_ActiveProcess;
981     LWP_ActiveProcess -> iomgrRequest = request;
982
983 #ifdef DEBUG
984     request -> timeout.Next = (struct TM_Elem *) 1;
985     request -> timeout.Prev = (struct TM_Elem *) 1;
986 #endif /* DEBUG */
987     TM_Insert(Requests, &request->timeout);
988
989     /* Wait for action */
990     LWP_QWait();
991
992     /* Update parameters & return */
993     result = request -> result;
994
995     FreeRequest(request);
996     return (result > 1 ? 1 : result);
997 }
998 \f
999 int IOMGR_Cancel(PROCESS pid)
1000 {
1001     register struct IoRequest *request;
1002
1003     if ((request = pid->iomgrRequest) == 0) return -1;  /* Pid not found */
1004
1005     if (request->readfds)   FD_N_ZERO(request->nfds, request->readfds);
1006     if (request->writefds)  FD_N_ZERO(request->nfds, request->writefds);
1007     if (request->exceptfds) FD_N_ZERO(request->nfds, request->exceptfds);
1008     request->nfds = 0;
1009
1010     request -> result = -2;
1011     TM_Remove(Requests, &request->timeout);
1012 #ifdef DEBUG
1013     request -> timeout.Next = (struct TM_Elem *) 5;
1014     request -> timeout.Prev = (struct TM_Elem *) 5;
1015 #endif /* DEBUG */
1016     LWP_QSignal(request->pid);
1017     pid->iomgrRequest = 0;
1018
1019     return 0;
1020 }
1021 \f
1022 #ifndef AFS_NT40_ENV
1023 /* Cause delivery of signal signo to result in a LWP_SignalProcess of
1024    event. */
1025 int IOMGR_Signal (int signo, char *event)
1026 {
1027     struct sigaction sa;
1028
1029     if (badsig(signo))
1030         return LWP_EBADSIG;
1031     if (event == NULL)
1032         return LWP_EBADEVENT;
1033     sa.sa_handler = SigHandler;
1034     sa.sa_mask = *((sigset_t *) allOnes);       /* mask all signals */
1035     sa.sa_flags = 0;
1036     sigsHandled |= mysigmask(signo);
1037     sigEvents[signo] = event;
1038     sigDelivered[signo] = FALSE;
1039     if (sigaction (signo, &sa, &oldActions[signo]) == -1)
1040         return LWP_ESYSTEM;
1041     return LWP_SUCCESS;
1042 }
1043
1044 /* Stop handling occurrences of signo. */
1045 int IOMGR_CancelSignal (int signo)
1046 {
1047     if (badsig(signo) || (sigsHandled & mysigmask(signo)) == 0)
1048         return LWP_EBADSIG;
1049     sigaction (signo, &oldActions[signo], NULL);
1050     sigsHandled &= ~mysigmask(signo);
1051     return LWP_SUCCESS;
1052 }
1053 #endif /* AFS_NT40_ENV */
1054 /* This routine calls select is a fashion that simulates the standard sleep routine */
1055 void IOMGR_Sleep (int seconds)
1056 {
1057 #ifndef AFS_DJGPP_ENV
1058     struct timeval timeout;
1059
1060     timeout.tv_sec = seconds;
1061     timeout.tv_usec = 0;
1062     IOMGR_Select(0, 0, 0, 0, &timeout);
1063 #else
1064     struct timeval timeout;
1065     int s;
1066     fd_set set, empty;
1067     FD_ZERO(&empty);
1068     FD_ZERO(&set);
1069     s = socket(AF_INET,SOCK_STREAM,0);
1070     FD_SET(s,&set);
1071
1072     timeout.tv_sec = seconds;
1073     timeout.tv_usec = 0;
1074     IOMGR_Select(1,&set,&empty,&empty,&timeout);
1075     close(s);
1076 #endif            /* DJGPP  */
1077 }
1078 #endif  /* USE_PTHREADS */
1079
1080
1081 #ifdef AFS_DJGPP_ENV
1082
1083 /* Netbios code for djgpp port */
1084
1085 int IOMGR_NCBSelect(NCB *ncbp, dos_ptr dos_ncb, struct timeval *timeout)
1086 {
1087   struct IoRequest *request;
1088   int result;
1089   
1090   if (timeout != NULL && timeout->tv_sec == 0 && timeout->tv_usec == 0)
1091   {
1092     /* Poll */
1093     if (ncbp->ncb_event != NULL)
1094     {
1095       /* error */
1096       return -1;
1097     }
1098     
1099     if (get_dos_member_b(NCB, dos_ncb, ncb_cmd_cplt) != 0xff)
1100     {
1101       return 1;
1102     }
1103     else {
1104       return 0;
1105     }
1106   }
1107
1108   /* Construct request block & insert */
1109   request = NewRequest();
1110   request->ncbp = ncbp;
1111   request->dos_ncb = dos_ncb;
1112   
1113   if (timeout == NULL)
1114   {
1115     request->timeout.TotalTime.tv_sec = -1;
1116     request->timeout.TotalTime.tv_usec = -1;
1117   }
1118   else
1119   {
1120     request -> timeout.TotalTime = *timeout;
1121     /* check for bad request */
1122     if (timeout->tv_sec < 0 || timeout->tv_usec < 0 || timeout->tv_usec > 999999)
1123     {
1124       /* invalid arg */
1125       iomgr_badtv = *timeout;
1126       iomgr_badpid = LWP_ActiveProcess;
1127       /* now fixup request */
1128       if(request->timeout.TotalTime.tv_sec < 0)
1129         request->timeout.TotalTime.tv_sec = 1;
1130       request->timeout.TotalTime.tv_usec = 100000;
1131     }
1132   }
1133
1134   request->timeout.BackPointer = (char *)request;
1135
1136   /* Insert my PID in case of IOMGR_Cancel */
1137   request -> pid = LWP_ActiveProcess;
1138   LWP_ActiveProcess -> iomgrRequest = request;
1139   
1140 #ifdef DEBUG
1141   request -> timeout.Next = (struct TM_Elem *) 1;
1142   request -> timeout.Prev = (struct TM_Elem *) 1;
1143 #endif /* DEBUG */
1144   TM_Insert(Requests, &request->timeout);
1145
1146   if (ncbp->ncb_event != NULL)
1147   {
1148     /* since we were given an event, we can return immediately and just
1149        signal the event once the request completes. */
1150     return 0;
1151   }
1152   else
1153   {
1154     /* Wait for action */
1155     
1156     LWP_QWait();
1157     
1158     /* Update parameters & return */
1159     result = request -> result;
1160
1161     FreeRequest(request);
1162     return (result > 1 ? 1 : result);
1163   }
1164 }
1165       
1166 int IOMGR_CheckNCB(void)
1167 {
1168   int woke_someone = FALSE;
1169   EVENT_HANDLE ev;
1170   PROCESS pid;
1171   
1172   anyNCBComplete = FALSE;
1173   FOR_ALL_ELTS(r, Requests, {
1174     register struct IoRequest *req;
1175     req = (struct IoRequest *) r -> BackPointer;
1176
1177     if (req->dos_ncb && get_dos_member_b(NCB, req->dos_ncb, ncb_cmd_cplt) != 0xff)
1178     {
1179       /* this NCB has completed */
1180       TM_Remove(Requests, &req->timeout);
1181
1182       /* copy out NCB from DOS to virtual space */
1183       dosmemget(req->dos_ncb, sizeof(NCB), (char *) req->ncbp);
1184
1185       if (ev = req->ncbp->ncb_event)
1186       {
1187         thrd_SetEvent(ev);
1188       }
1189       else
1190       {
1191         woke_someone = TRUE;
1192         LWP_QSignal(pid=req->pid);
1193         pid->iomgrRequest = 0;
1194       }
1195     }
1196   })
1197   return woke_someone;
1198 }
1199
1200 int ncb_handler(__dpmi_regs *r)
1201 {
1202   anyNCBComplete = TRUE;  /* NCB completed */
1203   /* Make sure that the IOMGR process doesn't pause on the select. */
1204   iomgr_timeout.tv_sec = 0;
1205   iomgr_timeout.tv_usec = 0;
1206   return;
1207 }
1208
1209 int install_ncb_handler(void)
1210 {
1211   callback_info.pm_offset = (long) ncb_handler;
1212   if (_go32_dpmi_allocate_real_mode_callback_retf(&callback_info,
1213                                                   &callback_regs))
1214  {
1215       fprintf(stderr, "error, allocate_real_mode_callback_retf failed\n");
1216       return -1;
1217  }
1218
1219  handler_seg = callback_info.rm_segment;
1220  handler_off = callback_info.rm_offset;
1221  
1222  /*printf("NCB handler_seg=0x%x, off=0x%x\n", handler_seg, handler_off);*/
1223 }
1224 #endif /* AFS_DJGPP_ENV */