vol: clear ih_synced before dropping lock
[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         fdP[i].fd_ihnext = NULL;
307         fdP[i].fd_ihprev = NULL;
308         DLL_INSERT_TAIL(&fdP[i], fdAvailHead, fdAvailTail, fd_next, fd_prev);
309     }
310 }
311
312 /* Allocate a chunk of stream handles */
313 void
314 streamHandleAllocateChunk(void)
315 {
316     int i;
317     StreamHandle_t *streamP;
318
319     osi_Assert(streamAvailHead == NULL);
320     streamP = (StreamHandle_t *)
321         malloc(STREAM_HANDLE_MALLOCSIZE * sizeof(StreamHandle_t));
322     osi_Assert(streamP != NULL);
323     for (i = 0; i < STREAM_HANDLE_MALLOCSIZE; i++) {
324         streamP[i].str_fd = INVALID_FD;
325         DLL_INSERT_TAIL(&streamP[i], streamAvailHead, streamAvailTail,
326                         str_next, str_prev);
327     }
328 }
329
330 /*
331  * Get a file descriptor handle given an Inode handle
332  */
333 FdHandle_t *
334 ih_open(IHandle_t * ihP)
335 {
336     FdHandle_t *fdP;
337     FD_t fd;
338     FD_t closeFd;
339
340     if (!ihP)                   /* XXX should log here in the fileserver */
341         return NULL;
342
343     IH_LOCK;
344
345     /* Do we already have an open file handle for this Inode? */
346     for (fdP = ihP->ih_fdtail; fdP != NULL; fdP = fdP->fd_ihprev) {
347 #ifndef HAVE_PIO
348         /*
349          * If we don't have positional i/o, don't try to share fds, since
350          * we can't do so in a threadsafe way.
351          */
352         if (fdP->fd_status != FD_HANDLE_INUSE) {
353             osi_Assert(fdP->fd_status == FD_HANDLE_OPEN);
354 #else /* HAVE_PIO */
355         if (fdP->fd_status != FD_HANDLE_AVAIL) {
356 #endif /* HAVE_PIO */
357             fdP->fd_refcnt++;
358             if (fdP->fd_status == FD_HANDLE_OPEN) {
359             fdP->fd_status = FD_HANDLE_INUSE;
360             DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
361             }
362             ihP->ih_refcnt++;
363             IH_UNLOCK;
364             return fdP;
365         }
366     }
367
368     /*
369      * Try to open the Inode, return NULL on error.
370      */
371     fdInUseCount += 1;
372     IH_UNLOCK;
373 ih_open_retry:
374     fd = OS_IOPEN(ihP);
375     IH_LOCK;
376     if (fd == INVALID_FD && (errno != EMFILE || fdLruHead == NULL) ) {
377         fdInUseCount -= 1;
378         IH_UNLOCK;
379         return NULL;
380     }
381
382     /* fdCacheSize limits the size of the descriptor cache, but
383      * we permit the number of open files to exceed fdCacheSize.
384      * We only recycle open file descriptors when the number
385      * of open files reaches the size of the cache */
386     if ((fdInUseCount > fdCacheSize || fd == INVALID_FD)  && fdLruHead != NULL) {
387         fdP = fdLruHead;
388         osi_Assert(fdP->fd_status == FD_HANDLE_OPEN);
389         DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
390         DLL_DELETE(fdP, fdP->fd_ih->ih_fdhead, fdP->fd_ih->ih_fdtail,
391                    fd_ihnext, fd_ihprev);
392         closeFd = fdP->fd_fd;
393         if (fd == INVALID_FD) {
394             fdCacheSize--;          /* reduce in order to not run into here too often */
395             DLL_INSERT_TAIL(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
396             fdP->fd_status = FD_HANDLE_AVAIL;
397             fdP->fd_ih = NULL;
398             fdP->fd_fd = INVALID_FD;
399             IH_UNLOCK;
400             OS_CLOSE(closeFd);
401             goto ih_open_retry;
402         }
403     } else {
404         if (fdAvailHead == NULL) {
405             fdHandleAllocateChunk();
406         }
407         fdP = fdAvailHead;
408         osi_Assert(fdP->fd_status == FD_HANDLE_AVAIL);
409         DLL_DELETE(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
410         closeFd = INVALID_FD;
411     }
412
413     fdP->fd_status = FD_HANDLE_INUSE;
414     fdP->fd_fd = fd;
415     fdP->fd_ih = ihP;
416     fdP->fd_refcnt++;
417
418     ihP->ih_refcnt++;
419
420     /* Add this handle to the Inode's list of open descriptors */
421     DLL_INSERT_TAIL(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext,
422                     fd_ihprev);
423
424     if (closeFd != INVALID_FD) {
425         IH_UNLOCK;
426         OS_CLOSE(closeFd);
427         IH_LOCK;
428         fdInUseCount -= 1;
429     }
430
431     IH_UNLOCK;
432     return fdP;
433 }
434
435 /*
436  * Return a file descriptor handle to the cache
437  */
438 int
439 fd_close(FdHandle_t * fdP)
440 {
441     IHandle_t *ihP;
442
443     if (!fdP)
444         return 0;
445
446     IH_LOCK;
447     osi_Assert(ih_Inited);
448     osi_Assert(fdInUseCount > 0);
449     osi_Assert(fdP->fd_status == FD_HANDLE_INUSE);
450
451     ihP = fdP->fd_ih;
452
453     /* Call fd_reallyclose to really close the unused file handles if
454      * the previous attempt to close (ih_reallyclose()) all file handles
455      * failed (this is determined by checking the ihandle for the flag
456      * IH_REALLY_CLOSED) or we have too many open files.
457      */
458     if (ihP->ih_flags & IH_REALLY_CLOSED || fdInUseCount > fdCacheSize) {
459         IH_UNLOCK;
460         return fd_reallyclose(fdP);
461     }
462
463     fdP->fd_refcnt--;
464     if (fdP->fd_refcnt == 0) {
465     /* Put this descriptor back into the cache */
466     fdP->fd_status = FD_HANDLE_OPEN;
467     DLL_INSERT_TAIL(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
468     }
469
470     /* If this is not the only reference to the Inode then we can decrement
471      * the reference count, otherwise we need to call ih_release.
472      */
473     if (ihP->ih_refcnt > 1) {
474         ihP->ih_refcnt--;
475         IH_UNLOCK;
476     } else {
477         IH_UNLOCK;
478         ih_release(ihP);
479     }
480
481     return 0;
482 }
483
484 /*
485  * Actually close the file descriptor handle and return it to
486  * the free list.
487  */
488 int
489 fd_reallyclose(FdHandle_t * fdP)
490 {
491     FD_t closeFd;
492     IHandle_t *ihP;
493
494     if (!fdP)
495         return 0;
496
497     IH_LOCK;
498     osi_Assert(ih_Inited);
499     osi_Assert(fdInUseCount > 0);
500     osi_Assert(fdP->fd_status == FD_HANDLE_INUSE);
501
502     ihP = fdP->fd_ih;
503     closeFd = fdP->fd_fd;
504     fdP->fd_refcnt--;
505
506     if (fdP->fd_refcnt == 0) {
507     DLL_DELETE(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext, fd_ihprev);
508     DLL_INSERT_TAIL(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
509
510     fdP->fd_status = FD_HANDLE_AVAIL;
511     fdP->fd_refcnt = 0;
512     fdP->fd_ih = NULL;
513     fdP->fd_fd = INVALID_FD;
514     }
515
516     /* All the file descriptor handles have been closed; reset
517      * the IH_REALLY_CLOSED flag indicating that ih_reallyclose
518      * has completed its job.
519      */
520     if (!ihP->ih_fdhead) {
521         ihP->ih_flags &= ~IH_REALLY_CLOSED;
522     }
523
524     if (fdP->fd_refcnt == 0) {
525     IH_UNLOCK;
526     OS_CLOSE(closeFd);
527     IH_LOCK;
528     fdInUseCount -= 1;
529     }
530
531     /* If this is not the only reference to the Inode then we can decrement
532      * the reference count, otherwise we need to call ih_release. */
533     if (ihP->ih_refcnt > 1) {
534         ihP->ih_refcnt--;
535         IH_UNLOCK;
536     } else {
537         IH_UNLOCK;
538         ih_release(ihP);
539     }
540
541     return 0;
542 }
543
544 /* Enable buffered I/O on a file descriptor */
545 StreamHandle_t *
546 stream_fdopen(FD_t fd)
547 {
548     StreamHandle_t *streamP;
549
550     IH_LOCK;
551     if (streamAvailHead == NULL) {
552         streamHandleAllocateChunk();
553     }
554     streamP = streamAvailHead;
555     DLL_DELETE(streamP, streamAvailHead, streamAvailTail, str_next, str_prev);
556     IH_UNLOCK;
557     streamP->str_fd = fd;
558     streamP->str_buflen = 0;
559     streamP->str_bufoff = 0;
560     streamP->str_fdoff = 0;
561     streamP->str_error = 0;
562     streamP->str_eof = 0;
563     streamP->str_direction = STREAM_DIRECTION_NONE;
564     return streamP;
565 }
566
567 /* Open a file for buffered I/O */
568 StreamHandle_t *
569 stream_open(const char *filename, const char *mode)
570 {
571     FD_t fd = INVALID_FD;
572
573     if (strcmp(mode, "r") == 0) {
574         fd = OS_OPEN(filename, O_RDONLY, 0);
575     } else if (strcmp(mode, "r+") == 0) {
576         fd = OS_OPEN(filename, O_RDWR, 0);
577     } else if (strcmp(mode, "w") == 0) {
578         fd = OS_OPEN(filename, O_WRONLY | O_TRUNC | O_CREAT, 0);
579     } else if (strcmp(mode, "w+") == 0) {
580         fd = OS_OPEN(filename, O_RDWR | O_TRUNC | O_CREAT, 0);
581     } else if (strcmp(mode, "a") == 0) {
582         fd = OS_OPEN(filename, O_WRONLY | O_APPEND | O_CREAT, 0);
583     } else if (strcmp(mode, "a+") == 0) {
584         fd = OS_OPEN(filename, O_RDWR | O_APPEND | O_CREAT, 0);
585     } else {
586         osi_Assert(FALSE);              /* not implemented */
587     }
588
589     if (fd == INVALID_FD) {
590         return NULL;
591     }
592     return stream_fdopen(fd);
593 }
594
595 /* fread for buffered I/O handles */
596 afs_sfsize_t
597 stream_read(void *ptr, afs_fsize_t size, afs_fsize_t nitems,
598             StreamHandle_t * streamP)
599 {
600     afs_fsize_t nbytes, bytesRead, bytesToRead;
601     char *p;
602
603     /* Need to seek before changing direction */
604     if (streamP->str_direction == STREAM_DIRECTION_NONE) {
605         streamP->str_direction = STREAM_DIRECTION_READ;
606         streamP->str_bufoff = 0;
607         streamP->str_buflen = 0;
608     } else {
609         osi_Assert(streamP->str_direction == STREAM_DIRECTION_READ);
610     }
611
612     bytesRead = 0;
613     nbytes = size * nitems;
614     p = (char *)ptr;
615     while (nbytes > 0 && !streamP->str_eof) {
616         if (streamP->str_buflen == 0) {
617             streamP->str_bufoff = 0;
618             streamP->str_buflen =
619                 OS_PREAD(streamP->str_fd, streamP->str_buffer,
620                         STREAM_HANDLE_BUFSIZE, streamP->str_fdoff);
621             if (streamP->str_buflen < 0) {
622                 streamP->str_error = errno;
623                 streamP->str_buflen = 0;
624                 bytesRead = 0;
625                 break;
626             } else if (streamP->str_buflen == 0) {
627                 streamP->str_eof = 1;
628                 break;
629             }
630             streamP->str_fdoff += streamP->str_buflen;
631         }
632
633         bytesToRead = nbytes;
634         if (bytesToRead > streamP->str_buflen) {
635             bytesToRead = streamP->str_buflen;
636         }
637         memcpy(p, streamP->str_buffer + streamP->str_bufoff, bytesToRead);
638         p += bytesToRead;
639         streamP->str_bufoff += bytesToRead;
640         streamP->str_buflen -= bytesToRead;
641         bytesRead += bytesToRead;
642         nbytes -= bytesToRead;
643     }
644
645     return (bytesRead / size);
646 }
647
648 /* fwrite for buffered I/O handles */
649 afs_sfsize_t
650 stream_write(void *ptr, afs_fsize_t size, afs_fsize_t nitems,
651              StreamHandle_t * streamP)
652 {
653     char *p;
654     afs_sfsize_t rc;
655     afs_fsize_t nbytes, bytesWritten, bytesToWrite;
656
657     /* Need to seek before changing direction */
658     if (streamP->str_direction == STREAM_DIRECTION_NONE) {
659         streamP->str_direction = STREAM_DIRECTION_WRITE;
660         streamP->str_bufoff = 0;
661         streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
662     } else {
663         osi_Assert(streamP->str_direction == STREAM_DIRECTION_WRITE);
664     }
665
666     nbytes = size * nitems;
667     bytesWritten = 0;
668     p = (char *)ptr;
669     while (nbytes > 0) {
670         if (streamP->str_buflen == 0) {
671             rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
672                           STREAM_HANDLE_BUFSIZE, streamP->str_fdoff);
673             if (rc < 0) {
674                 streamP->str_error = errno;
675                 bytesWritten = 0;
676                 break;
677             }
678             streamP->str_fdoff += rc;
679             streamP->str_bufoff = 0;
680             streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
681         }
682
683         bytesToWrite = nbytes;
684         if (bytesToWrite > streamP->str_buflen) {
685             bytesToWrite = streamP->str_buflen;
686         }
687         memcpy(streamP->str_buffer + streamP->str_bufoff, p, bytesToWrite);
688         p += bytesToWrite;
689         streamP->str_bufoff += bytesToWrite;
690         streamP->str_buflen -= bytesToWrite;
691         bytesWritten += bytesToWrite;
692         nbytes -= bytesToWrite;
693     }
694
695     return (bytesWritten / size);
696 }
697
698 /* fseek for buffered I/O handles */
699 int
700 stream_aseek(StreamHandle_t * streamP, afs_foff_t offset)
701 {
702     ssize_t rc;
703     int retval = 0;
704
705     if (streamP->str_direction == STREAM_DIRECTION_WRITE
706         && streamP->str_bufoff > 0) {
707         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
708                       streamP->str_bufoff, streamP->str_fdoff);
709         if (rc < 0) {
710             streamP->str_error = errno;
711             retval = -1;
712         }
713     }
714     streamP->str_fdoff = offset;
715     streamP->str_bufoff = 0;
716     streamP->str_buflen = 0;
717     streamP->str_eof = 0;
718     streamP->str_direction = STREAM_DIRECTION_NONE;
719     return retval;
720 }
721
722 /* fflush for buffered I/O handles */
723 int
724 stream_flush(StreamHandle_t * streamP)
725 {
726     ssize_t rc;
727     int retval = 0;
728
729     if (streamP->str_direction == STREAM_DIRECTION_WRITE
730         && streamP->str_bufoff > 0) {
731         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
732                       streamP->str_bufoff, streamP->str_fdoff);
733         if (rc < 0) {
734             streamP->str_error = errno;
735             retval = -1;
736         } else {
737             streamP->str_fdoff += rc;
738         }
739         streamP->str_bufoff = 0;
740         streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
741     }
742
743     return retval;
744 }
745
746 /* Free a buffered I/O handle */
747 int
748 stream_close(StreamHandle_t * streamP, int reallyClose)
749 {
750     ssize_t rc;
751     int retval = 0;
752
753     osi_Assert(streamP != NULL);
754     if (streamP->str_direction == STREAM_DIRECTION_WRITE
755         && streamP->str_bufoff > 0) {
756         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
757                       streamP->str_bufoff, streamP->str_fdoff);
758         if (rc < 0) {
759             retval = -1;
760         } else {
761             streamP->str_fdoff += rc;
762         }
763     }
764     if (reallyClose) {
765         rc = OS_CLOSE(streamP->str_fd);
766         if (rc < 0) {
767             retval = -1;
768         }
769     }
770     streamP->str_fd = INVALID_FD;
771
772     IH_LOCK;
773     DLL_INSERT_TAIL(streamP, streamAvailHead, streamAvailTail,
774                     str_next, str_prev);
775     IH_UNLOCK;
776     return retval;
777 }
778
779 /* Close all unused file descriptors associated with the inode
780  * handle. Called with IH_LOCK held. May drop and reacquire
781  * IH_LOCK. Sets the IH_REALLY_CLOSED flag in the inode handle
782  * if it fails to close all file handles.
783  */
784 static int
785 ih_fdclose(IHandle_t * ihP)
786 {
787     int closeCount, closedAll;
788     FdHandle_t *fdP, *head, *tail, *next;
789
790     osi_Assert(ihP->ih_refcnt > 0);
791
792     closedAll = 1;
793     DLL_INIT_LIST(head, tail);
794     ihP->ih_flags &= ~IH_REALLY_CLOSED;
795
796     /*
797      * Remove the file descriptors for this Inode from the LRU queue
798      * and the IHandle queue and put them on a temporary queue so we
799      * can drop the lock before we close the files.
800      */
801     for (fdP = ihP->ih_fdhead; fdP != NULL; fdP = next) {
802         next = fdP->fd_ihnext;
803         osi_Assert(fdP->fd_ih == ihP);
804         osi_Assert(fdP->fd_status == FD_HANDLE_OPEN
805                || fdP->fd_status == FD_HANDLE_INUSE);
806         if (fdP->fd_status == FD_HANDLE_OPEN) {
807             DLL_DELETE(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext,
808                        fd_ihprev);
809             DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
810             DLL_INSERT_TAIL(fdP, head, tail, fd_next, fd_prev);
811         } else {
812             closedAll = 0;
813             ihP->ih_flags |= IH_REALLY_CLOSED;
814         }
815     }
816
817     /* If the ihandle reference count is 1, we should have
818      * closed all file descriptors.
819      */
820     if (ihP->ih_refcnt == 1 || closedAll) {
821         osi_Assert(closedAll);
822         osi_Assert(!ihP->ih_fdhead);
823         osi_Assert(!ihP->ih_fdtail);
824     }
825
826     if (head == NULL) {
827         return 0;               /* No file descriptors closed */
828     }
829
830     IH_UNLOCK;
831     /*
832      * Close the file descriptors
833      */
834     closeCount = 0;
835     for (fdP = head; fdP != NULL; fdP = fdP->fd_next) {
836         OS_CLOSE(fdP->fd_fd);
837         fdP->fd_status = FD_HANDLE_AVAIL;
838         fdP->fd_refcnt = 0;
839         fdP->fd_fd = INVALID_FD;
840         fdP->fd_ih = NULL;
841         closeCount++;
842     }
843
844     IH_LOCK;
845     osi_Assert(fdInUseCount >= closeCount);
846     fdInUseCount -= closeCount;
847
848     /*
849      * Append the temporary queue to the list of available descriptors
850      */
851     if (fdAvailHead == NULL) {
852         fdAvailHead = head;
853         fdAvailTail = tail;
854     } else {
855         fdAvailTail->fd_next = head;
856         head->fd_prev = fdAvailTail;
857         fdAvailTail = tail;
858     }
859
860     return 0;
861 }
862
863 /* Close all cached file descriptors for this inode. */
864 int
865 ih_reallyclose(IHandle_t * ihP)
866 {
867     if (!ihP)
868         return 0;
869
870     IH_LOCK;
871     ihP->ih_refcnt++;   /* must not disappear over unlock */
872     if (ihP->ih_synced) {
873         FdHandle_t *fdP;
874         ihP->ih_synced = 0;
875         IH_UNLOCK;
876
877         fdP = IH_OPEN(ihP);
878         if (fdP) {
879             OS_SYNC(fdP->fd_fd);
880             FDH_CLOSE(fdP);
881         }
882
883         IH_LOCK;
884     }
885
886     osi_Assert(ihP->ih_refcnt > 0);
887
888     ih_fdclose(ihP);
889
890     if (ihP->ih_refcnt > 1) {
891         ihP->ih_refcnt--;
892         IH_UNLOCK;
893     } else {
894         IH_UNLOCK;
895         ih_release(ihP);
896     }
897     return 0;
898 }
899
900 /* Release an Inode handle. All cached file descriptors for this
901  * inode are closed when the last reference to this handle is released
902  */
903 int
904 ih_release(IHandle_t * ihP)
905 {
906     int ihash;
907
908     if (!ihP)
909         return 0;
910
911     IH_LOCK;
912     osi_Assert(ihP->ih_refcnt > 0);
913
914     if (ihP->ih_refcnt > 1) {
915         ihP->ih_refcnt--;
916         IH_UNLOCK;
917         return 0;
918     }
919
920     ihash = IH_HASH(ihP->ih_dev, ihP->ih_vid, ihP->ih_ino);
921     DLL_DELETE(ihP, ihashTable[ihash].ihash_head,
922                ihashTable[ihash].ihash_tail, ih_next, ih_prev);
923
924     ih_fdclose(ihP);
925
926     ihP->ih_refcnt--;
927
928     DLL_INSERT_TAIL(ihP, ihAvailHead, ihAvailTail, ih_next, ih_prev);
929
930     IH_UNLOCK;
931     return 0;
932 }
933
934 /* Sync an inode to disk if its handle isn't NULL */
935 int
936 ih_condsync(IHandle_t * ihP)
937 {
938     int code;
939     FdHandle_t *fdP;
940
941     if (!ihP)
942         return 0;
943
944     fdP = IH_OPEN(ihP);
945     if (fdP == NULL)
946         return -1;
947
948     code = FDH_SYNC(fdP);
949     FDH_CLOSE(fdP);
950
951     return code;
952 }
953
954 void
955 ih_sync_all(void) {
956
957     int ihash;
958
959     IH_LOCK;
960     for (ihash = 0; ihash < I_HANDLE_HASH_SIZE; ihash++) {
961         IHandle_t *ihP, *ihPnext;
962
963         ihP = ihashTable[ihash].ihash_head;
964         if (ihP)
965             ihP->ih_refcnt++;   /* must not disappear over unlock */
966         for (; ihP; ihP = ihPnext) {
967
968             if (ihP->ih_synced) {
969                 FdHandle_t *fdP;
970
971                 ihP->ih_synced = 0;
972                 IH_UNLOCK;
973
974                 fdP = IH_OPEN(ihP);
975                 if (fdP) {
976                     OS_SYNC(fdP->fd_fd);
977                     FDH_CLOSE(fdP);
978                 }
979
980                 IH_LOCK;
981             }
982
983             /* when decrementing the refcount, the ihandle might disappear
984                and we might not even be able to proceed to the next one.
985                Hence the gymnastics putting a hold on the next one already */
986             ihPnext = ihP->ih_next;
987             if (ihPnext) ihPnext->ih_refcnt++;
988
989             if (ihP->ih_refcnt > 1) {
990                 ihP->ih_refcnt--;
991             } else {
992                 IH_UNLOCK;
993                 ih_release(ihP);
994                 IH_LOCK;
995             }
996
997         }
998     }
999     IH_UNLOCK;
1000 }
1001
1002 void *
1003 ih_sync_thread(void *dummy) {
1004     while(1) {
1005
1006 #ifdef AFS_PTHREAD_ENV
1007         sleep(10);
1008 #else /* AFS_PTHREAD_ENV */
1009         IOMGR_Sleep(60);
1010 #endif /* AFS_PTHREAD_ENV */
1011
1012         ih_sync_all();
1013     }
1014     return NULL;
1015 }
1016
1017
1018 /*************************************************************************
1019  * OS specific support routines.
1020  *************************************************************************/
1021 #ifndef AFS_NAMEI_ENV
1022 Inode
1023 ih_icreate(IHandle_t * ih, int dev, char *part, Inode nI, int p1, int p2,
1024            int p3, int p4)
1025 {
1026     Inode ino;
1027 #ifdef  AFS_3DISPARES
1028     /* See viceinode.h */
1029     if (p2 == INODESPECIAL) {
1030         int tp = p3;
1031         p3 = p4;
1032         p4 = tp;
1033     }
1034 #endif
1035     ino = ICREATE(dev, part, nI, p1, p2, p3, p4);
1036     return ino;
1037 }
1038 #endif /* AFS_NAMEI_ENV */
1039
1040 afs_sfsize_t
1041 ih_size(FD_t fd)
1042 {
1043 #ifdef AFS_NT40_ENV
1044     LARGE_INTEGER size;
1045     if (!GetFileSizeEx(fd, &size))
1046         return -1;
1047     return size.QuadPart;
1048 #else
1049     struct afs_stat status;
1050     if (afs_fstat(fd, &status) < 0)
1051         return -1;
1052     return status.st_size;
1053 #endif
1054 }
1055
1056 #ifndef HAVE_PIO
1057 ssize_t
1058 ih_pread(int fd, void * buf, size_t count, afs_foff_t offset)
1059 {
1060         afs_foff_t code;
1061         code = OS_SEEK(fd, offset, 0);
1062         if (code < 0)
1063             return code;
1064         return OS_READ(fd, buf, count);
1065 }
1066
1067 ssize_t
1068 ih_pwrite(int fd, const void * buf, size_t count, afs_foff_t offset)
1069 {
1070         afs_foff_t code;
1071         code = OS_SEEK(fd, offset, 0);
1072         if (code < 0)
1073             return code;
1074         return OS_WRITE(fd, buf, count);
1075 }
1076 #endif /* !HAVE_PIO */