libroken: Build on windows
[openafs.git] / src / vol / ihandle.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 /*  ihandle.c   - file descriptor cacheing for Inode handles.           */
11 /*                                                                      */
12 /************************************************************************/
13
14 #include <afsconfig.h>
15 #include <afs/param.h>
16
17 #include <roken.h>
18
19 #include <stdio.h>
20 #include <sys/types.h>
21 #include <errno.h>
22 #include <string.h>
23 #ifdef AFS_NT40_ENV
24 #include <fcntl.h>
25 #else
26 #include <sys/file.h>
27 #include <unistd.h>
28 #include <sys/stat.h>
29 #if defined(AFS_SUN5_ENV) || defined(AFS_NBSD_ENV)
30 #include <sys/fcntl.h>
31 #include <sys/resource.h>
32 #endif
33 #endif
34
35 #include <rx/xdr.h>
36 #include <afs/afsint.h>
37 #include <errno.h>
38 #include <afs/afssyscalls.h>
39 #include "nfs.h"
40 #include "ihandle.h"
41 #include "viceinode.h"
42 #include "afs/afs_assert.h"
43 #include <limits.h>
44
45 #ifndef AFS_NT40_ENV
46 #ifdef O_LARGEFILE
47 #define afs_stat        stat64
48 #define afs_fstat       fstat64
49 #else /* !O_LARGEFILE */
50 #define afs_stat        stat
51 #define afs_fstat       fstat
52 #endif /* !O_LARGEFILE */
53 #endif /* AFS_NT40_ENV */
54
55 #ifdef AFS_PTHREAD_ENV
56 pthread_once_t ih_glock_once = PTHREAD_ONCE_INIT;
57 pthread_mutex_t ih_glock_mutex;
58 #endif /* AFS_PTHREAD_ENV */
59
60 /* Linked list of available inode handles */
61 IHandle_t *ihAvailHead;
62 IHandle_t *ihAvailTail;
63
64 /* Linked list of available file descriptor handles */
65 FdHandle_t *fdAvailHead;
66 FdHandle_t *fdAvailTail;
67
68 /* Linked list of available stream descriptor handles */
69 StreamHandle_t *streamAvailHead;
70 StreamHandle_t *streamAvailTail;
71
72 /* LRU list for file descriptor handles */
73 FdHandle_t *fdLruHead;
74 FdHandle_t *fdLruTail;
75
76 int ih_Inited = 0;
77 int ih_PkgDefaultsSet = 0;
78
79 /* Most of the servers use fopen/fdopen. Since the FILE structure
80  * only has eight bits for the file descriptor, the cache size
81  * has to be less than 256. The cache can be made larger as long
82  * as you are sure you don't need fopen/fdopen. */
83
84 /* As noted in ihandle.h, the fileno member of FILE on most platforms
85  * in 2008 is a 16- or 32-bit signed int. -Matt
86  */
87 int fdMaxCacheSize = 0;
88 int fdCacheSize = 0;
89
90 /* Number of in use file descriptors */
91 int fdInUseCount = 0;
92
93 /* Hash table for inode handles */
94 IHashBucket_t ihashTable[I_HANDLE_HASH_SIZE];
95
96 void *ih_sync_thread(void *);
97
98 /* start-time configurable I/O limits */
99 ih_init_params vol_io_params;
100
101 void ih_PkgDefaults(void)
102 {
103     /* once */
104     ih_PkgDefaultsSet = 1;
105
106     /* default to well-known values */
107     vol_io_params.fd_handle_setaside = FD_HANDLE_SETASIDE;
108
109     /* initial fd cachesize.  the only one that will be used if
110      * the application does not call ih_UseLargeCache().  set this
111      * to a value representable in fileno member of the system's
112      * FILE structure (or equivalent). */
113     vol_io_params.fd_initial_cachesize = FD_DEFAULT_CACHESIZE;
114
115     /* fd cache size that will be used if/when ih_UseLargeCache()
116      * is called */
117     vol_io_params.fd_max_cachesize = FD_MAX_CACHESIZE;
118 }
119
120 #ifdef AFS_PTHREAD_ENV
121 /* Initialize the global ihandle mutex */
122 void
123 ih_glock_init(void)
124 {
125     MUTEX_INIT(&ih_glock_mutex, "ih glock", MUTEX_DEFAULT, 0);
126 }
127 #endif /* AFS_PTHREAD_ENV */
128
129 /* Initialize the file descriptor cache */
130 void
131 ih_Initialize(void)
132 {
133     int i;
134     osi_Assert(!ih_Inited);
135     ih_Inited = 1;
136     DLL_INIT_LIST(ihAvailHead, ihAvailTail);
137     DLL_INIT_LIST(fdAvailHead, fdAvailTail);
138     DLL_INIT_LIST(fdLruHead, fdLruTail);
139     for (i = 0; i < I_HANDLE_HASH_SIZE; i++) {
140         DLL_INIT_LIST(ihashTable[i].ihash_head, ihashTable[i].ihash_tail);
141     }
142 #if defined(AFS_NT40_ENV)
143     fdMaxCacheSize = vol_io_params.fd_max_cachesize;
144 #elif defined(AFS_SUN5_ENV) || defined(AFS_NBSD_ENV)
145     {
146         struct rlimit rlim;
147         osi_Assert(getrlimit(RLIMIT_NOFILE, &rlim) == 0);
148         rlim.rlim_cur = rlim.rlim_max;
149         osi_Assert(setrlimit(RLIMIT_NOFILE, &rlim) == 0);
150         fdMaxCacheSize = rlim.rlim_cur - vol_io_params.fd_handle_setaside;
151 #ifdef AFS_NBSD_ENV
152         /* XXX this is to avoid using up all system fd netbsd is
153          * somewhat broken and have set maximum fd for a root process
154          * to the same as system fd that is avaible, so if the
155          * fileserver uses all up process fds, all system fd will be
156          * used up too !
157          *
158          * Check for this better
159          */
160         fdMaxCacheSize /= 4;
161 #endif
162         fdMaxCacheSize = MIN(fdMaxCacheSize, vol_io_params.fd_max_cachesize);
163         osi_Assert(fdMaxCacheSize > 0);
164     }
165 #elif defined(AFS_HPUX_ENV)
166     /* Avoid problems with "UFSOpen: igetinode failed" panics on HPUX 11.0 */
167     fdMaxCacheSize = 0;
168 #else
169     {
170         long fdMax = MAX(sysconf(_SC_OPEN_MAX) - vol_io_params.fd_handle_setaside,
171                                          0);
172         fdMaxCacheSize = (int)MIN(fdMax, vol_io_params.fd_max_cachesize);
173     }
174 #endif
175     fdCacheSize = MIN(fdMaxCacheSize, vol_io_params.fd_initial_cachesize);
176
177     {
178 #ifdef AFS_PTHREAD_ENV
179         pthread_t syncer;
180         pthread_attr_t tattr;
181
182         pthread_attr_init(&tattr);
183         pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
184
185         pthread_create(&syncer, &tattr, ih_sync_thread, NULL);
186 #else /* AFS_PTHREAD_ENV */
187         PROCESS syncer;
188         LWP_CreateProcess(ih_sync_thread, 16*1024, LWP_MAX_PRIORITY - 2,
189             NULL, "ih_syncer", &syncer);
190 #endif /* AFS_PTHREAD_ENV */
191     }
192
193 }
194
195 /* Make the file descriptor cache as big as possible. Don't this call
196  * if the program uses fopen or fdopen, if fd_max_cachesize cannot be
197  * represented in the fileno member of the system FILE structure (or
198  * equivalent).
199  */
200 void
201 ih_UseLargeCache(void)
202 {
203     IH_LOCK;
204
205     if (!ih_PkgDefaultsSet) {
206         ih_PkgDefaults();
207     }
208
209     if (!ih_Inited) {
210         ih_Initialize();
211     }
212
213     fdCacheSize = fdMaxCacheSize;
214
215     IH_UNLOCK;
216 }
217
218 /* Allocate a chunk of inode handles */
219 void
220 iHandleAllocateChunk(void)
221 {
222     int i;
223     IHandle_t *ihP;
224
225     osi_Assert(ihAvailHead == NULL);
226     ihP = (IHandle_t *) malloc(I_HANDLE_MALLOCSIZE * sizeof(IHandle_t));
227     osi_Assert(ihP != NULL);
228     for (i = 0; i < I_HANDLE_MALLOCSIZE; i++) {
229         ihP[i].ih_refcnt = 0;
230         DLL_INSERT_TAIL(&ihP[i], ihAvailHead, ihAvailTail, ih_next, ih_prev);
231     }
232 }
233
234 /* Initialize an inode handle */
235 IHandle_t *
236 ih_init(int dev, int vid, Inode ino)
237 {
238     int ihash = IH_HASH(dev, vid, ino);
239     IHandle_t *ihP;
240
241     if (!ih_PkgDefaultsSet) {
242         ih_PkgDefaults();
243     }
244
245     IH_LOCK;
246     if (!ih_Inited) {
247         ih_Initialize();
248     }
249
250     /* Do we already have a handle for this Inode? */
251     for (ihP = ihashTable[ihash].ihash_head; ihP; ihP = ihP->ih_next) {
252         if (ihP->ih_ino == ino && ihP->ih_vid == vid && ihP->ih_dev == dev) {
253             ihP->ih_refcnt++;
254             IH_UNLOCK;
255             return ihP;
256         }
257     }
258
259     /* Allocate and initialize a new Inode handle */
260     if (ihAvailHead == NULL) {
261         iHandleAllocateChunk();
262     }
263     ihP = ihAvailHead;
264     osi_Assert(ihP->ih_refcnt == 0);
265     DLL_DELETE(ihP, ihAvailHead, ihAvailTail, ih_next, ih_prev);
266     ihP->ih_dev = dev;
267     ihP->ih_vid = vid;
268     ihP->ih_ino = ino;
269     ihP->ih_flags = 0;
270     ihP->ih_synced = 0;
271     ihP->ih_refcnt = 1;
272     DLL_INIT_LIST(ihP->ih_fdhead, ihP->ih_fdtail);
273     DLL_INSERT_TAIL(ihP, ihashTable[ihash].ihash_head,
274                     ihashTable[ihash].ihash_tail, ih_next, ih_prev);
275     IH_UNLOCK;
276     return ihP;
277 }
278
279 /* Copy an inode handle */
280 IHandle_t *
281 ih_copy(IHandle_t * ihP)
282 {
283     IH_LOCK;
284     osi_Assert(ih_Inited);
285     osi_Assert(ihP->ih_refcnt > 0);
286     ihP->ih_refcnt++;
287     IH_UNLOCK;
288     return ihP;
289 }
290
291 /* Allocate a chunk of file descriptor handles */
292 void
293 fdHandleAllocateChunk(void)
294 {
295     int i;
296     FdHandle_t *fdP;
297
298     osi_Assert(fdAvailHead == NULL);
299     fdP = (FdHandle_t *) malloc(FD_HANDLE_MALLOCSIZE * sizeof(FdHandle_t));
300     osi_Assert(fdP != NULL);
301     for (i = 0; i < FD_HANDLE_MALLOCSIZE; i++) {
302         fdP[i].fd_status = FD_HANDLE_AVAIL;
303         fdP[i].fd_refcnt = 0;
304         fdP[i].fd_ih = NULL;
305         fdP[i].fd_fd = INVALID_FD;
306         DLL_INSERT_TAIL(&fdP[i], fdAvailHead, fdAvailTail, fd_next, fd_prev);
307     }
308 }
309
310 /* Allocate a chunk of stream handles */
311 void
312 streamHandleAllocateChunk(void)
313 {
314     int i;
315     StreamHandle_t *streamP;
316
317     osi_Assert(streamAvailHead == NULL);
318     streamP = (StreamHandle_t *)
319         malloc(STREAM_HANDLE_MALLOCSIZE * sizeof(StreamHandle_t));
320     osi_Assert(streamP != NULL);
321     for (i = 0; i < STREAM_HANDLE_MALLOCSIZE; i++) {
322         streamP[i].str_fd = INVALID_FD;
323         DLL_INSERT_TAIL(&streamP[i], streamAvailHead, streamAvailTail,
324                         str_next, str_prev);
325     }
326 }
327
328 /*
329  * Get a file descriptor handle given an Inode handle
330  */
331 FdHandle_t *
332 ih_open(IHandle_t * ihP)
333 {
334     FdHandle_t *fdP;
335     FD_t fd;
336     FD_t closeFd;
337
338     if (!ihP)                   /* XXX should log here in the fileserver */
339         return NULL;
340
341     IH_LOCK;
342
343     /* Do we already have an open file handle for this Inode? */
344     for (fdP = ihP->ih_fdtail; fdP != NULL; fdP = fdP->fd_ihprev) {
345 #ifndef HAVE_PIO
346         /*
347          * If we don't have positional i/o, don't try to share fds, since
348          * we can't do so in a threadsafe way.
349          */
350         if (fdP->fd_status != FD_HANDLE_INUSE) {
351             osi_Assert(fdP->fd_status == FD_HANDLE_OPEN);
352 #else /* HAVE_PIO */
353         if (fdP->fd_status != FD_HANDLE_AVAIL) {
354 #endif /* HAVE_PIO */
355             fdP->fd_refcnt++;
356             if (fdP->fd_status == FD_HANDLE_OPEN) {
357             fdP->fd_status = FD_HANDLE_INUSE;
358             DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
359             }
360             ihP->ih_refcnt++;
361             IH_UNLOCK;
362             return fdP;
363         }
364     }
365
366     /*
367      * Try to open the Inode, return NULL on error.
368      */
369     fdInUseCount += 1;
370     IH_UNLOCK;
371 ih_open_retry:
372     fd = OS_IOPEN(ihP);
373     IH_LOCK;
374     if (fd == INVALID_FD && (errno != EMFILE || fdLruHead == NULL) ) {
375         fdInUseCount -= 1;
376         IH_UNLOCK;
377         return NULL;
378     }
379
380     /* fdCacheSize limits the size of the descriptor cache, but
381      * we permit the number of open files to exceed fdCacheSize.
382      * We only recycle open file descriptors when the number
383      * of open files reaches the size of the cache */
384     if ((fdInUseCount > fdCacheSize || fd == INVALID_FD)  && fdLruHead != NULL) {
385         fdP = fdLruHead;
386         osi_Assert(fdP->fd_status == FD_HANDLE_OPEN);
387         DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
388         DLL_DELETE(fdP, fdP->fd_ih->ih_fdhead, fdP->fd_ih->ih_fdtail,
389                    fd_ihnext, fd_ihprev);
390         closeFd = fdP->fd_fd;
391         if (fd == INVALID_FD) {
392             fdCacheSize--;          /* reduce in order to not run into here too often */
393             DLL_INSERT_TAIL(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
394             fdP->fd_status = FD_HANDLE_AVAIL;
395             fdP->fd_ih = NULL;
396             fdP->fd_fd = INVALID_FD;
397             IH_UNLOCK;
398             OS_CLOSE(closeFd);
399             goto ih_open_retry;
400         }
401     } else {
402         if (fdAvailHead == NULL) {
403             fdHandleAllocateChunk();
404         }
405         fdP = fdAvailHead;
406         osi_Assert(fdP->fd_status == FD_HANDLE_AVAIL);
407         DLL_DELETE(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
408         closeFd = INVALID_FD;
409     }
410
411     fdP->fd_status = FD_HANDLE_INUSE;
412     fdP->fd_fd = fd;
413     fdP->fd_ih = ihP;
414     fdP->fd_refcnt++;
415
416     ihP->ih_refcnt++;
417
418     /* Add this handle to the Inode's list of open descriptors */
419     DLL_INSERT_TAIL(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext,
420                     fd_ihprev);
421
422     if (closeFd != INVALID_FD) {
423         IH_UNLOCK;
424         OS_CLOSE(closeFd);
425         IH_LOCK;
426         fdInUseCount -= 1;
427     }
428
429     IH_UNLOCK;
430     return fdP;
431 }
432
433 /*
434  * Return a file descriptor handle to the cache
435  */
436 int
437 fd_close(FdHandle_t * fdP)
438 {
439     IHandle_t *ihP;
440
441     if (!fdP)
442         return 0;
443
444     IH_LOCK;
445     osi_Assert(ih_Inited);
446     osi_Assert(fdInUseCount > 0);
447     osi_Assert(fdP->fd_status == FD_HANDLE_INUSE);
448
449     ihP = fdP->fd_ih;
450
451     /* Call fd_reallyclose to really close the unused file handles if
452      * the previous attempt to close (ih_reallyclose()) all file handles
453      * failed (this is determined by checking the ihandle for the flag
454      * IH_REALLY_CLOSED) or we have too many open files.
455      */
456     if (ihP->ih_flags & IH_REALLY_CLOSED || fdInUseCount > fdCacheSize) {
457         IH_UNLOCK;
458         return fd_reallyclose(fdP);
459     }
460
461     fdP->fd_refcnt--;
462     if (fdP->fd_refcnt == 0) {
463     /* Put this descriptor back into the cache */
464     fdP->fd_status = FD_HANDLE_OPEN;
465     DLL_INSERT_TAIL(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
466     }
467
468     /* If this is not the only reference to the Inode then we can decrement
469      * the reference count, otherwise we need to call ih_release.
470      */
471     if (ihP->ih_refcnt > 1) {
472         ihP->ih_refcnt--;
473         IH_UNLOCK;
474     } else {
475         IH_UNLOCK;
476         ih_release(ihP);
477     }
478
479     return 0;
480 }
481
482 /*
483  * Actually close the file descriptor handle and return it to
484  * the free list.
485  */
486 int
487 fd_reallyclose(FdHandle_t * fdP)
488 {
489     FD_t closeFd;
490     IHandle_t *ihP;
491
492     if (!fdP)
493         return 0;
494
495     IH_LOCK;
496     osi_Assert(ih_Inited);
497     osi_Assert(fdInUseCount > 0);
498     osi_Assert(fdP->fd_status == FD_HANDLE_INUSE);
499
500     ihP = fdP->fd_ih;
501     closeFd = fdP->fd_fd;
502     fdP->fd_refcnt--;
503
504     if (fdP->fd_refcnt == 0) {
505     DLL_DELETE(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext, fd_ihprev);
506     DLL_INSERT_TAIL(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
507
508     fdP->fd_status = FD_HANDLE_AVAIL;
509     fdP->fd_refcnt = 0;
510     fdP->fd_ih = NULL;
511     fdP->fd_fd = INVALID_FD;
512     }
513
514     /* All the file descriptor handles have been closed; reset
515      * the IH_REALLY_CLOSED flag indicating that ih_reallyclose
516      * has completed its job.
517      */
518     if (!ihP->ih_fdhead) {
519         ihP->ih_flags &= ~IH_REALLY_CLOSED;
520     }
521
522     if (fdP->fd_refcnt == 0) {
523     IH_UNLOCK;
524     OS_CLOSE(closeFd);
525     IH_LOCK;
526     fdInUseCount -= 1;
527     }
528
529     /* If this is not the only reference to the Inode then we can decrement
530      * the reference count, otherwise we need to call ih_release. */
531     if (ihP->ih_refcnt > 1) {
532         ihP->ih_refcnt--;
533         IH_UNLOCK;
534     } else {
535         IH_UNLOCK;
536         ih_release(ihP);
537     }
538
539     return 0;
540 }
541
542 /* Enable buffered I/O on a file descriptor */
543 StreamHandle_t *
544 stream_fdopen(FD_t fd)
545 {
546     StreamHandle_t *streamP;
547
548     IH_LOCK;
549     if (streamAvailHead == NULL) {
550         streamHandleAllocateChunk();
551     }
552     streamP = streamAvailHead;
553     DLL_DELETE(streamP, streamAvailHead, streamAvailTail, str_next, str_prev);
554     IH_UNLOCK;
555     streamP->str_fd = fd;
556     streamP->str_buflen = 0;
557     streamP->str_bufoff = 0;
558     streamP->str_fdoff = 0;
559     streamP->str_error = 0;
560     streamP->str_eof = 0;
561     streamP->str_direction = STREAM_DIRECTION_NONE;
562     return streamP;
563 }
564
565 /* Open a file for buffered I/O */
566 StreamHandle_t *
567 stream_open(const char *filename, const char *mode)
568 {
569     FD_t fd = INVALID_FD;
570
571     if (strcmp(mode, "r") == 0) {
572         fd = OS_OPEN(filename, O_RDONLY, 0);
573     } else if (strcmp(mode, "r+") == 0) {
574         fd = OS_OPEN(filename, O_RDWR, 0);
575     } else if (strcmp(mode, "w") == 0) {
576         fd = OS_OPEN(filename, O_WRONLY | O_TRUNC | O_CREAT, 0);
577     } else if (strcmp(mode, "w+") == 0) {
578         fd = OS_OPEN(filename, O_RDWR | O_TRUNC | O_CREAT, 0);
579     } else if (strcmp(mode, "a") == 0) {
580         fd = OS_OPEN(filename, O_WRONLY | O_APPEND | O_CREAT, 0);
581     } else if (strcmp(mode, "a+") == 0) {
582         fd = OS_OPEN(filename, O_RDWR | O_APPEND | O_CREAT, 0);
583     } else {
584         osi_Assert(FALSE);              /* not implemented */
585     }
586
587     if (fd == INVALID_FD) {
588         return NULL;
589     }
590     return stream_fdopen(fd);
591 }
592
593 /* fread for buffered I/O handles */
594 afs_sfsize_t
595 stream_read(void *ptr, afs_fsize_t size, afs_fsize_t nitems,
596             StreamHandle_t * streamP)
597 {
598     afs_fsize_t nbytes, bytesRead, bytesToRead;
599     char *p;
600
601     /* Need to seek before changing direction */
602     if (streamP->str_direction == STREAM_DIRECTION_NONE) {
603         streamP->str_direction = STREAM_DIRECTION_READ;
604         streamP->str_bufoff = 0;
605         streamP->str_buflen = 0;
606     } else {
607         osi_Assert(streamP->str_direction == STREAM_DIRECTION_READ);
608     }
609
610     bytesRead = 0;
611     nbytes = size * nitems;
612     p = (char *)ptr;
613     while (nbytes > 0 && !streamP->str_eof) {
614         if (streamP->str_buflen == 0) {
615             streamP->str_bufoff = 0;
616             streamP->str_buflen =
617                 OS_PREAD(streamP->str_fd, streamP->str_buffer,
618                         STREAM_HANDLE_BUFSIZE, streamP->str_fdoff);
619             if (streamP->str_buflen < 0) {
620                 streamP->str_error = errno;
621                 streamP->str_buflen = 0;
622                 bytesRead = 0;
623                 break;
624             } else if (streamP->str_buflen == 0) {
625                 streamP->str_eof = 1;
626                 break;
627             }
628             streamP->str_fdoff += streamP->str_buflen;
629         }
630
631         bytesToRead = nbytes;
632         if (bytesToRead > streamP->str_buflen) {
633             bytesToRead = streamP->str_buflen;
634         }
635         memcpy(p, streamP->str_buffer + streamP->str_bufoff, bytesToRead);
636         p += bytesToRead;
637         streamP->str_bufoff += bytesToRead;
638         streamP->str_buflen -= bytesToRead;
639         bytesRead += bytesToRead;
640         nbytes -= bytesToRead;
641     }
642
643     return (bytesRead / size);
644 }
645
646 /* fwrite for buffered I/O handles */
647 afs_sfsize_t
648 stream_write(void *ptr, afs_fsize_t size, afs_fsize_t nitems,
649              StreamHandle_t * streamP)
650 {
651     char *p;
652     afs_sfsize_t rc;
653     afs_fsize_t nbytes, bytesWritten, bytesToWrite;
654
655     /* Need to seek before changing direction */
656     if (streamP->str_direction == STREAM_DIRECTION_NONE) {
657         streamP->str_direction = STREAM_DIRECTION_WRITE;
658         streamP->str_bufoff = 0;
659         streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
660     } else {
661         osi_Assert(streamP->str_direction == STREAM_DIRECTION_WRITE);
662     }
663
664     nbytes = size * nitems;
665     bytesWritten = 0;
666     p = (char *)ptr;
667     while (nbytes > 0) {
668         if (streamP->str_buflen == 0) {
669             rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
670                           STREAM_HANDLE_BUFSIZE, streamP->str_fdoff);
671             if (rc < 0) {
672                 streamP->str_error = errno;
673                 bytesWritten = 0;
674                 break;
675             }
676             streamP->str_fdoff += rc;
677             streamP->str_bufoff = 0;
678             streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
679         }
680
681         bytesToWrite = nbytes;
682         if (bytesToWrite > streamP->str_buflen) {
683             bytesToWrite = streamP->str_buflen;
684         }
685         memcpy(streamP->str_buffer + streamP->str_bufoff, p, bytesToWrite);
686         p += bytesToWrite;
687         streamP->str_bufoff += bytesToWrite;
688         streamP->str_buflen -= bytesToWrite;
689         bytesWritten += bytesToWrite;
690         nbytes -= bytesToWrite;
691     }
692
693     return (bytesWritten / size);
694 }
695
696 /* fseek for buffered I/O handles */
697 int
698 stream_aseek(StreamHandle_t * streamP, afs_foff_t offset)
699 {
700     ssize_t rc;
701     int retval = 0;
702
703     if (streamP->str_direction == STREAM_DIRECTION_WRITE
704         && streamP->str_bufoff > 0) {
705         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
706                       streamP->str_bufoff, streamP->str_fdoff);
707         if (rc < 0) {
708             streamP->str_error = errno;
709             retval = -1;
710         }
711     }
712     streamP->str_fdoff = offset;
713     streamP->str_bufoff = 0;
714     streamP->str_buflen = 0;
715     streamP->str_eof = 0;
716     streamP->str_direction = STREAM_DIRECTION_NONE;
717     return retval;
718 }
719
720 /* fflush for buffered I/O handles */
721 int
722 stream_flush(StreamHandle_t * streamP)
723 {
724     ssize_t rc;
725     int retval = 0;
726
727     if (streamP->str_direction == STREAM_DIRECTION_WRITE
728         && streamP->str_bufoff > 0) {
729         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
730                       streamP->str_bufoff, streamP->str_fdoff);
731         if (rc < 0) {
732             streamP->str_error = errno;
733             retval = -1;
734         } else {
735             streamP->str_fdoff += rc;
736         }
737         streamP->str_bufoff = 0;
738         streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
739     }
740
741     return retval;
742 }
743
744 /* Free a buffered I/O handle */
745 int
746 stream_close(StreamHandle_t * streamP, int reallyClose)
747 {
748     ssize_t rc;
749     int retval = 0;
750
751     osi_Assert(streamP != NULL);
752     if (streamP->str_direction == STREAM_DIRECTION_WRITE
753         && streamP->str_bufoff > 0) {
754         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
755                       streamP->str_bufoff, streamP->str_fdoff);
756         if (rc < 0) {
757             retval = -1;
758         } else {
759             streamP->str_fdoff += rc;
760         }
761     }
762     if (reallyClose) {
763         rc = OS_CLOSE(streamP->str_fd);
764         if (rc < 0) {
765             retval = -1;
766         }
767     }
768     streamP->str_fd = INVALID_FD;
769
770     IH_LOCK;
771     DLL_INSERT_TAIL(streamP, streamAvailHead, streamAvailTail,
772                     str_next, str_prev);
773     IH_UNLOCK;
774     return retval;
775 }
776
777 /* Close all unused file descriptors associated with the inode
778  * handle. Called with IH_LOCK held. May drop and reacquire
779  * IH_LOCK. Sets the IH_REALLY_CLOSED flag in the inode handle
780  * if it fails to close all file handles.
781  */
782 static int
783 ih_fdclose(IHandle_t * ihP)
784 {
785     int closeCount, closedAll;
786     FdHandle_t *fdP, *head, *tail, *next;
787
788     osi_Assert(ihP->ih_refcnt > 0);
789
790     closedAll = 1;
791     DLL_INIT_LIST(head, tail);
792     ihP->ih_flags &= ~IH_REALLY_CLOSED;
793
794     /*
795      * Remove the file descriptors for this Inode from the LRU queue
796      * and the IHandle queue and put them on a temporary queue so we
797      * can drop the lock before we close the files.
798      */
799     for (fdP = ihP->ih_fdhead; fdP != NULL; fdP = next) {
800         next = fdP->fd_ihnext;
801         osi_Assert(fdP->fd_ih == ihP);
802         osi_Assert(fdP->fd_status == FD_HANDLE_OPEN
803                || fdP->fd_status == FD_HANDLE_INUSE);
804         if (fdP->fd_status == FD_HANDLE_OPEN) {
805             DLL_DELETE(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext,
806                        fd_ihprev);
807             DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
808             DLL_INSERT_TAIL(fdP, head, tail, fd_next, fd_prev);
809         } else {
810             closedAll = 0;
811             ihP->ih_flags |= IH_REALLY_CLOSED;
812         }
813     }
814
815     /* If the ihandle reference count is 1, we should have
816      * closed all file descriptors.
817      */
818     if (ihP->ih_refcnt == 1 || closedAll) {
819         osi_Assert(closedAll);
820         osi_Assert(!ihP->ih_fdhead);
821         osi_Assert(!ihP->ih_fdtail);
822     }
823
824     if (head == NULL) {
825         return 0;               /* No file descriptors closed */
826     }
827
828     IH_UNLOCK;
829     /*
830      * Close the file descriptors
831      */
832     closeCount = 0;
833     for (fdP = head; fdP != NULL; fdP = fdP->fd_next) {
834         OS_CLOSE(fdP->fd_fd);
835         fdP->fd_status = FD_HANDLE_AVAIL;
836         fdP->fd_refcnt = 0;
837         fdP->fd_fd = INVALID_FD;
838         fdP->fd_ih = NULL;
839         closeCount++;
840     }
841
842     IH_LOCK;
843     osi_Assert(fdInUseCount >= closeCount);
844     fdInUseCount -= closeCount;
845
846     /*
847      * Append the temporary queue to the list of available descriptors
848      */
849     if (fdAvailHead == NULL) {
850         fdAvailHead = head;
851         fdAvailTail = tail;
852     } else {
853         fdAvailTail->fd_next = head;
854         head->fd_prev = fdAvailTail;
855         fdAvailTail = tail;
856     }
857
858     return 0;
859 }
860
861 /* Close all cached file descriptors for this inode. */
862 int
863 ih_reallyclose(IHandle_t * ihP)
864 {
865     if (!ihP)
866         return 0;
867
868     IH_LOCK;
869     ihP->ih_refcnt++;   /* must not disappear over unlock */
870     if (ihP->ih_synced) {
871         FdHandle_t *fdP;
872         IH_UNLOCK;
873
874         fdP = IH_OPEN(ihP);
875         if (fdP) {
876             OS_SYNC(fdP->fd_fd);
877             FDH_CLOSE(fdP);
878         }
879
880         IH_LOCK;
881     }
882
883     osi_Assert(ihP->ih_refcnt > 0);
884     ihP->ih_synced = 0;
885
886     ih_fdclose(ihP);
887
888     if (ihP->ih_refcnt > 1) {
889         ihP->ih_refcnt--;
890         IH_UNLOCK;
891     } else {
892         IH_UNLOCK;
893         ih_release(ihP);
894     }
895     return 0;
896 }
897
898 /* Release an Inode handle. All cached file descriptors for this
899  * inode are closed when the last reference to this handle is released
900  */
901 int
902 ih_release(IHandle_t * ihP)
903 {
904     int ihash;
905
906     if (!ihP)
907         return 0;
908
909     IH_LOCK;
910     osi_Assert(ihP->ih_refcnt > 0);
911
912     if (ihP->ih_refcnt > 1) {
913         ihP->ih_refcnt--;
914         IH_UNLOCK;
915         return 0;
916     }
917
918     ihash = IH_HASH(ihP->ih_dev, ihP->ih_vid, ihP->ih_ino);
919     DLL_DELETE(ihP, ihashTable[ihash].ihash_head,
920                ihashTable[ihash].ihash_tail, ih_next, ih_prev);
921
922     ih_fdclose(ihP);
923
924     ihP->ih_refcnt--;
925
926     DLL_INSERT_TAIL(ihP, ihAvailHead, ihAvailTail, ih_next, ih_prev);
927
928     IH_UNLOCK;
929     return 0;
930 }
931
932 /* Sync an inode to disk if its handle isn't NULL */
933 int
934 ih_condsync(IHandle_t * ihP)
935 {
936     int code;
937     FdHandle_t *fdP;
938
939     if (!ihP)
940         return 0;
941
942     fdP = IH_OPEN(ihP);
943     if (fdP == NULL)
944         return -1;
945
946     code = FDH_SYNC(fdP);
947     FDH_CLOSE(fdP);
948
949     return code;
950 }
951
952 void
953 ih_sync_all(void) {
954
955     int ihash;
956
957     IH_LOCK;
958     for (ihash = 0; ihash < I_HANDLE_HASH_SIZE; ihash++) {
959         IHandle_t *ihP, *ihPnext;
960
961         ihP = ihashTable[ihash].ihash_head;
962         if (ihP)
963             ihP->ih_refcnt++;   /* must not disappear over unlock */
964         for (; ihP; ihP = ihPnext) {
965
966             if (ihP->ih_synced) {
967                 FdHandle_t *fdP;
968
969                 ihP->ih_synced = 0;
970                 IH_UNLOCK;
971
972                 fdP = IH_OPEN(ihP);
973                 if (fdP) {
974                     OS_SYNC(fdP->fd_fd);
975                     FDH_CLOSE(fdP);
976                 }
977
978                 IH_LOCK;
979             }
980
981             /* when decrementing the refcount, the ihandle might disappear
982                and we might not even be able to proceed to the next one.
983                Hence the gymnastics putting a hold on the next one already */
984             ihPnext = ihP->ih_next;
985             if (ihPnext) ihPnext->ih_refcnt++;
986
987             if (ihP->ih_refcnt > 1) {
988                 ihP->ih_refcnt--;
989             } else {
990                 IH_UNLOCK;
991                 ih_release(ihP);
992                 IH_LOCK;
993             }
994
995         }
996     }
997     IH_UNLOCK;
998 }
999
1000 void *
1001 ih_sync_thread(void *dummy) {
1002     while(1) {
1003
1004 #ifdef AFS_PTHREAD_ENV
1005         sleep(10);
1006 #else /* AFS_PTHREAD_ENV */
1007         IOMGR_Sleep(60);
1008 #endif /* AFS_PTHREAD_ENV */
1009
1010         ih_sync_all();
1011     }
1012     return NULL;
1013 }
1014
1015
1016 /*************************************************************************
1017  * OS specific support routines.
1018  *************************************************************************/
1019 #ifndef AFS_NAMEI_ENV
1020 Inode
1021 ih_icreate(IHandle_t * ih, int dev, char *part, Inode nI, int p1, int p2,
1022            int p3, int p4)
1023 {
1024     Inode ino;
1025 #ifdef  AFS_3DISPARES
1026     /* See viceinode.h */
1027     if (p2 == INODESPECIAL) {
1028         int tp = p3;
1029         p3 = p4;
1030         p4 = tp;
1031     }
1032 #endif
1033     ino = ICREATE(dev, part, nI, p1, p2, p3, p4);
1034     return ino;
1035 }
1036 #endif /* AFS_NAMEI_ENV */
1037
1038 afs_sfsize_t
1039 ih_size(FD_t fd)
1040 {
1041 #ifdef AFS_NT40_ENV
1042     LARGE_INTEGER size;
1043     if (!GetFileSizeEx(fd, &size))
1044         return -1;
1045     return size.QuadPart;
1046 #else
1047     struct afs_stat status;
1048     if (afs_fstat(fd, &status) < 0)
1049         return -1;
1050     return status.st_size;
1051 #endif
1052 }
1053
1054 #ifndef HAVE_PIO
1055 ssize_t
1056 ih_pread(int fd, void * buf, size_t count, afs_foff_t offset)
1057 {
1058         afs_foff_t code;
1059         code = OS_SEEK(fd, offset, 0);
1060         if (code < 0)
1061             return code;
1062         return OS_READ(fd, buf, count);
1063 }
1064
1065 ssize_t
1066 ih_pwrite(int fd, const void * buf, size_t count, afs_foff_t offset)
1067 {
1068         afs_foff_t code;
1069         code = OS_SEEK(fd, offset, 0);
1070         if (code < 0)
1071             return code;
1072         return OS_WRITE(fd, buf, count);
1073 }
1074 #endif /* !HAVE_PIO */