a198320b7305fcd45129f4f79583cadbe64dfb37
[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 #ifdef AFS_PTHREAD_ENV
46 pthread_once_t ih_glock_once = PTHREAD_ONCE_INIT;
47 pthread_mutex_t ih_glock_mutex;
48 #endif /* AFS_PTHREAD_ENV */
49
50 /* Linked list of available inode handles */
51 IHandle_t *ihAvailHead;
52 IHandle_t *ihAvailTail;
53
54 /* Linked list of available file descriptor handles */
55 FdHandle_t *fdAvailHead;
56 FdHandle_t *fdAvailTail;
57
58 /* Linked list of available stream descriptor handles */
59 StreamHandle_t *streamAvailHead;
60 StreamHandle_t *streamAvailTail;
61
62 /* LRU list for file descriptor handles */
63 FdHandle_t *fdLruHead;
64 FdHandle_t *fdLruTail;
65
66 int ih_Inited = 0;
67 int ih_PkgDefaultsSet = 0;
68
69 /* Most of the servers use fopen/fdopen. Since the FILE structure
70  * only has eight bits for the file descriptor, the cache size
71  * has to be less than 256. The cache can be made larger as long
72  * as you are sure you don't need fopen/fdopen. */
73
74 /* As noted in ihandle.h, the fileno member of FILE on most platforms
75  * in 2008 is a 16- or 32-bit signed int. -Matt
76  */
77 int fdMaxCacheSize = 0;
78 int fdCacheSize = 0;
79
80 /* Number of in use file descriptors */
81 int fdInUseCount = 0;
82
83 /* Hash table for inode handles */
84 IHashBucket_t ihashTable[I_HANDLE_HASH_SIZE];
85
86 void *ih_sync_thread(void *);
87
88 /* start-time configurable I/O limits */
89 ih_init_params vol_io_params;
90
91 void ih_PkgDefaults(void)
92 {
93     /* once */
94     ih_PkgDefaultsSet = 1;
95
96     /* default to well-known values */
97     vol_io_params.fd_handle_setaside = FD_HANDLE_SETASIDE;
98
99     /* initial fd cachesize.  the only one that will be used if
100      * the application does not call ih_UseLargeCache().  set this
101      * to a value representable in fileno member of the system's
102      * FILE structure (or equivalent). */
103     vol_io_params.fd_initial_cachesize = FD_DEFAULT_CACHESIZE;
104
105     /* fd cache size that will be used if/when ih_UseLargeCache()
106      * is called */
107     vol_io_params.fd_max_cachesize = FD_MAX_CACHESIZE;
108 }
109
110 #ifdef AFS_PTHREAD_ENV
111 /* Initialize the global ihandle mutex */
112 void
113 ih_glock_init(void)
114 {
115     MUTEX_INIT(&ih_glock_mutex, "ih glock", MUTEX_DEFAULT, 0);
116 }
117 #endif /* AFS_PTHREAD_ENV */
118
119 /* Initialize the file descriptor cache */
120 void
121 ih_Initialize(void)
122 {
123     int i;
124     osi_Assert(!ih_Inited);
125     ih_Inited = 1;
126     DLL_INIT_LIST(ihAvailHead, ihAvailTail);
127     DLL_INIT_LIST(fdAvailHead, fdAvailTail);
128     DLL_INIT_LIST(fdLruHead, fdLruTail);
129     for (i = 0; i < I_HANDLE_HASH_SIZE; i++) {
130         DLL_INIT_LIST(ihashTable[i].ihash_head, ihashTable[i].ihash_tail);
131     }
132 #if defined(AFS_NT40_ENV)
133     fdMaxCacheSize = vol_io_params.fd_max_cachesize;
134 #elif defined(AFS_SUN5_ENV) || defined(AFS_NBSD_ENV)
135     {
136         struct rlimit rlim;
137         osi_Assert(getrlimit(RLIMIT_NOFILE, &rlim) == 0);
138         rlim.rlim_cur = rlim.rlim_max;
139         osi_Assert(setrlimit(RLIMIT_NOFILE, &rlim) == 0);
140         fdMaxCacheSize = rlim.rlim_cur - vol_io_params.fd_handle_setaside;
141 #ifdef AFS_NBSD_ENV
142         /* XXX this is to avoid using up all system fd netbsd is
143          * somewhat broken and have set maximum fd for a root process
144          * to the same as system fd that is avaible, so if the
145          * fileserver uses all up process fds, all system fd will be
146          * used up too !
147          *
148          * Check for this better
149          */
150         fdMaxCacheSize /= 4;
151 #endif
152         fdMaxCacheSize = MIN(fdMaxCacheSize, vol_io_params.fd_max_cachesize);
153         osi_Assert(fdMaxCacheSize > 0);
154     }
155 #elif defined(AFS_HPUX_ENV)
156     /* Avoid problems with "UFSOpen: igetinode failed" panics on HPUX 11.0 */
157     fdMaxCacheSize = 0;
158 #else
159     {
160         long fdMax = MAX(sysconf(_SC_OPEN_MAX) - vol_io_params.fd_handle_setaside,
161                                          0);
162         fdMaxCacheSize = (int)MIN(fdMax, vol_io_params.fd_max_cachesize);
163     }
164 #endif
165     fdCacheSize = MIN(fdMaxCacheSize, vol_io_params.fd_initial_cachesize);
166
167     {
168 #ifdef AFS_PTHREAD_ENV
169         pthread_t syncer;
170         pthread_attr_t tattr;
171
172         pthread_attr_init(&tattr);
173         pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
174
175         pthread_create(&syncer, &tattr, ih_sync_thread, NULL);
176 #else /* AFS_PTHREAD_ENV */
177         PROCESS syncer;
178         LWP_CreateProcess(ih_sync_thread, 16*1024, LWP_MAX_PRIORITY - 2,
179             NULL, "ih_syncer", &syncer);
180 #endif /* AFS_PTHREAD_ENV */
181     }
182
183 }
184
185 /* Make the file descriptor cache as big as possible. Don't this call
186  * if the program uses fopen or fdopen, if fd_max_cachesize cannot be
187  * represented in the fileno member of the system FILE structure (or
188  * equivalent).
189  */
190 void
191 ih_UseLargeCache(void)
192 {
193     IH_LOCK;
194
195     if (!ih_PkgDefaultsSet) {
196         ih_PkgDefaults();
197     }
198
199     if (!ih_Inited) {
200         ih_Initialize();
201     }
202
203     fdCacheSize = fdMaxCacheSize;
204
205     IH_UNLOCK;
206 }
207
208 /* Allocate a chunk of inode handles */
209 void
210 iHandleAllocateChunk(void)
211 {
212     int i;
213     IHandle_t *ihP;
214
215     osi_Assert(ihAvailHead == NULL);
216     ihP = (IHandle_t *) malloc(I_HANDLE_MALLOCSIZE * sizeof(IHandle_t));
217     osi_Assert(ihP != NULL);
218     for (i = 0; i < I_HANDLE_MALLOCSIZE; i++) {
219         ihP[i].ih_refcnt = 0;
220         DLL_INSERT_TAIL(&ihP[i], ihAvailHead, ihAvailTail, ih_next, ih_prev);
221     }
222 }
223
224 /* Initialize an inode handle */
225 IHandle_t *
226 ih_init(int dev, int vid, Inode ino)
227 {
228     int ihash = IH_HASH(dev, vid, ino);
229     IHandle_t *ihP;
230
231     if (!ih_PkgDefaultsSet) {
232         ih_PkgDefaults();
233     }
234
235     IH_LOCK;
236     if (!ih_Inited) {
237         ih_Initialize();
238     }
239
240     /* Do we already have a handle for this Inode? */
241     for (ihP = ihashTable[ihash].ihash_head; ihP; ihP = ihP->ih_next) {
242         if (ihP->ih_ino == ino && ihP->ih_vid == vid && ihP->ih_dev == dev) {
243             ihP->ih_refcnt++;
244             IH_UNLOCK;
245             return ihP;
246         }
247     }
248
249     /* Allocate and initialize a new Inode handle */
250     if (ihAvailHead == NULL) {
251         iHandleAllocateChunk();
252     }
253     ihP = ihAvailHead;
254     osi_Assert(ihP->ih_refcnt == 0);
255     DLL_DELETE(ihP, ihAvailHead, ihAvailTail, ih_next, ih_prev);
256     ihP->ih_dev = dev;
257     ihP->ih_vid = vid;
258     ihP->ih_ino = ino;
259     ihP->ih_flags = 0;
260     ihP->ih_synced = 0;
261     ihP->ih_refcnt = 1;
262     DLL_INIT_LIST(ihP->ih_fdhead, ihP->ih_fdtail);
263     DLL_INSERT_TAIL(ihP, ihashTable[ihash].ihash_head,
264                     ihashTable[ihash].ihash_tail, ih_next, ih_prev);
265     IH_UNLOCK;
266     return ihP;
267 }
268
269 /* Copy an inode handle */
270 IHandle_t *
271 ih_copy(IHandle_t * ihP)
272 {
273     IH_LOCK;
274     osi_Assert(ih_Inited);
275     osi_Assert(ihP->ih_refcnt > 0);
276     ihP->ih_refcnt++;
277     IH_UNLOCK;
278     return ihP;
279 }
280
281 /* Allocate a chunk of file descriptor handles */
282 void
283 fdHandleAllocateChunk(void)
284 {
285     int i;
286     FdHandle_t *fdP;
287
288     osi_Assert(fdAvailHead == NULL);
289     fdP = (FdHandle_t *) malloc(FD_HANDLE_MALLOCSIZE * sizeof(FdHandle_t));
290     osi_Assert(fdP != NULL);
291     for (i = 0; i < FD_HANDLE_MALLOCSIZE; i++) {
292         fdP[i].fd_status = FD_HANDLE_AVAIL;
293         fdP[i].fd_refcnt = 0;
294         fdP[i].fd_ih = NULL;
295         fdP[i].fd_fd = INVALID_FD;
296         fdP[i].fd_ihnext = NULL;
297         fdP[i].fd_ihprev = NULL;
298         fdP[i].fd_needs_rclose = 0;
299         DLL_INSERT_TAIL(&fdP[i], fdAvailHead, fdAvailTail, fd_next, fd_prev);
300     }
301 }
302
303 /* Allocate a chunk of stream handles */
304 void
305 streamHandleAllocateChunk(void)
306 {
307     int i;
308     StreamHandle_t *streamP;
309
310     osi_Assert(streamAvailHead == NULL);
311     streamP = (StreamHandle_t *)
312         malloc(STREAM_HANDLE_MALLOCSIZE * sizeof(StreamHandle_t));
313     osi_Assert(streamP != NULL);
314     for (i = 0; i < STREAM_HANDLE_MALLOCSIZE; i++) {
315         streamP[i].str_fd = INVALID_FD;
316         DLL_INSERT_TAIL(&streamP[i], streamAvailHead, streamAvailTail,
317                         str_next, str_prev);
318     }
319 }
320
321 /*
322  * Get a file descriptor handle given an Inode handle
323  */
324 FdHandle_t *
325 ih_open(IHandle_t * ihP)
326 {
327     FdHandle_t *fdP;
328     FD_t fd;
329     FD_t closeFd;
330
331     if (!ihP)                   /* XXX should log here in the fileserver */
332         return NULL;
333
334     IH_LOCK;
335
336     /* Do we already have an open file handle for this Inode? */
337     for (fdP = ihP->ih_fdtail; fdP != NULL; fdP = fdP->fd_ihprev) {
338 #ifndef HAVE_PIO
339         /*
340          * If we don't have positional i/o, don't try to share fds, since
341          * we can't do so in a threadsafe way.
342          */
343         if (fdP->fd_status != FD_HANDLE_INUSE) {
344             osi_Assert(fdP->fd_status == FD_HANDLE_OPEN);
345 #else /* HAVE_PIO */
346         if (fdP->fd_status != FD_HANDLE_AVAIL) {
347 #endif /* HAVE_PIO */
348             fdP->fd_refcnt++;
349             if (fdP->fd_status == FD_HANDLE_OPEN) {
350             fdP->fd_status = FD_HANDLE_INUSE;
351             DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
352             }
353             ihP->ih_refcnt++;
354             IH_UNLOCK;
355             return fdP;
356         }
357     }
358
359     /*
360      * Try to open the Inode, return NULL on error.
361      */
362     fdInUseCount += 1;
363     IH_UNLOCK;
364 ih_open_retry:
365     fd = OS_IOPEN(ihP);
366     IH_LOCK;
367     if (fd == INVALID_FD && (errno != EMFILE || fdLruHead == NULL) ) {
368         fdInUseCount -= 1;
369         IH_UNLOCK;
370         return NULL;
371     }
372
373     /* fdCacheSize limits the size of the descriptor cache, but
374      * we permit the number of open files to exceed fdCacheSize.
375      * We only recycle open file descriptors when the number
376      * of open files reaches the size of the cache */
377     if ((fdInUseCount > fdCacheSize || fd == INVALID_FD)  && fdLruHead != NULL) {
378         fdP = fdLruHead;
379         osi_Assert(fdP->fd_status == FD_HANDLE_OPEN);
380         DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
381         DLL_DELETE(fdP, fdP->fd_ih->ih_fdhead, fdP->fd_ih->ih_fdtail,
382                    fd_ihnext, fd_ihprev);
383         closeFd = fdP->fd_fd;
384         if (fd == INVALID_FD) {
385             fdCacheSize--;          /* reduce in order to not run into here too often */
386             DLL_INSERT_TAIL(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
387             fdP->fd_status = FD_HANDLE_AVAIL;
388             fdP->fd_ih = NULL;
389             fdP->fd_fd = INVALID_FD;
390             fdP->fd_needs_rclose = 0;
391             IH_UNLOCK;
392             OS_CLOSE(closeFd);
393             goto ih_open_retry;
394         }
395     } else {
396         if (fdAvailHead == NULL) {
397             fdHandleAllocateChunk();
398         }
399         fdP = fdAvailHead;
400         osi_Assert(fdP->fd_status == FD_HANDLE_AVAIL);
401         DLL_DELETE(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
402         closeFd = INVALID_FD;
403     }
404
405     fdP->fd_status = FD_HANDLE_INUSE;
406     fdP->fd_fd = fd;
407     fdP->fd_ih = ihP;
408     fdP->fd_needs_rclose = 0;
409     fdP->fd_refcnt++;
410
411     ihP->ih_refcnt++;
412
413     /* Add this handle to the Inode's list of open descriptors */
414     DLL_INSERT_TAIL(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext,
415                     fd_ihprev);
416
417     if (closeFd != INVALID_FD) {
418         IH_UNLOCK;
419         OS_CLOSE(closeFd);
420         IH_LOCK;
421         fdInUseCount -= 1;
422     }
423
424     IH_UNLOCK;
425     return fdP;
426 }
427
428 /*
429  * Return a file descriptor handle to the cache
430  */
431 int
432 fd_close(FdHandle_t * fdP)
433 {
434     IHandle_t *ihP;
435
436     if (!fdP)
437         return 0;
438
439     IH_LOCK;
440     osi_Assert(ih_Inited);
441     osi_Assert(fdInUseCount > 0);
442     osi_Assert(fdP->fd_status == FD_HANDLE_INUSE);
443
444     ihP = fdP->fd_ih;
445
446     /* Call fd_reallyclose to really close the unused file handles if
447      * the previous attempt to close (ih_reallyclose()) all file handles
448      * failed (this is determined by checking the ihandle for the flag
449      * IH_REALLY_CLOSED) or we have too many open files.
450      */
451     if (ihP->ih_flags & IH_REALLY_CLOSED || fdInUseCount > fdCacheSize ||
452         fdP->fd_needs_rclose) {
453
454         IH_UNLOCK;
455         return fd_reallyclose(fdP);
456     }
457
458     fdP->fd_refcnt--;
459     if (fdP->fd_refcnt == 0) {
460         /* Put this descriptor back into the cache */
461         fdP->fd_status = FD_HANDLE_OPEN;
462         DLL_INSERT_TAIL(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
463     }
464
465     /* If this is not the only reference to the Inode then we can decrement
466      * the reference count, otherwise we need to call ih_release.
467      */
468     if (ihP->ih_refcnt > 1) {
469         ihP->ih_refcnt--;
470         IH_UNLOCK;
471     } else {
472         IH_UNLOCK;
473         ih_release(ihP);
474     }
475
476     return 0;
477 }
478
479 /*
480  * Actually close the file descriptor handle and return it to
481  * the free list.
482  */
483 int
484 fd_reallyclose(FdHandle_t * fdP)
485 {
486     FD_t closeFd;
487     IHandle_t *ihP;
488
489     if (!fdP)
490         return 0;
491
492     IH_LOCK;
493     osi_Assert(ih_Inited);
494     osi_Assert(fdInUseCount > 0);
495     osi_Assert(fdP->fd_status == FD_HANDLE_INUSE);
496
497     ihP = fdP->fd_ih;
498     closeFd = fdP->fd_fd;
499     fdP->fd_refcnt--;
500
501     if (fdP->fd_refcnt == 0) {
502         DLL_DELETE(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext, fd_ihprev);
503         DLL_INSERT_TAIL(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
504
505         fdP->fd_status = FD_HANDLE_AVAIL;
506         fdP->fd_refcnt = 0;
507         fdP->fd_ih = NULL;
508         fdP->fd_fd = INVALID_FD;
509         fdP->fd_needs_rclose = 0;
510     } else {
511         fdP->fd_needs_rclose = 1;
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         fdP->fd_needs_rclose = 0;
840         closeCount++;
841     }
842
843     IH_LOCK;
844     osi_Assert(fdInUseCount >= closeCount);
845     fdInUseCount -= closeCount;
846
847     /*
848      * Append the temporary queue to the list of available descriptors
849      */
850     if (fdAvailHead == NULL) {
851         fdAvailHead = head;
852         fdAvailTail = tail;
853     } else {
854         fdAvailTail->fd_next = head;
855         head->fd_prev = fdAvailTail;
856         fdAvailTail = tail;
857     }
858
859     return 0;
860 }
861
862 /* Close all cached file descriptors for this inode. */
863 int
864 ih_reallyclose(IHandle_t * ihP)
865 {
866     if (!ihP)
867         return 0;
868
869     IH_LOCK;
870     ihP->ih_refcnt++;   /* must not disappear over unlock */
871     if (ihP->ih_synced) {
872         FdHandle_t *fdP;
873         ihP->ih_synced = 0;
874         IH_UNLOCK;
875
876         fdP = IH_OPEN(ihP);
877         if (fdP) {
878             OS_SYNC(fdP->fd_fd);
879             FDH_CLOSE(fdP);
880         }
881
882         IH_LOCK;
883     }
884
885     osi_Assert(ihP->ih_refcnt > 0);
886
887     ih_fdclose(ihP);
888
889     if (ihP->ih_refcnt > 1) {
890         ihP->ih_refcnt--;
891         IH_UNLOCK;
892     } else {
893         IH_UNLOCK;
894         ih_release(ihP);
895     }
896     return 0;
897 }
898
899 /* Release an Inode handle. All cached file descriptors for this
900  * inode are closed when the last reference to this handle is released
901  */
902 int
903 ih_release(IHandle_t * ihP)
904 {
905     int ihash;
906
907     if (!ihP)
908         return 0;
909
910     IH_LOCK;
911     osi_Assert(ihP->ih_refcnt > 0);
912
913     if (ihP->ih_refcnt > 1) {
914         ihP->ih_refcnt--;
915         IH_UNLOCK;
916         return 0;
917     }
918
919     ihash = IH_HASH(ihP->ih_dev, ihP->ih_vid, ihP->ih_ino);
920     DLL_DELETE(ihP, ihashTable[ihash].ihash_head,
921                ihashTable[ihash].ihash_tail, ih_next, ih_prev);
922
923     ih_fdclose(ihP);
924
925     ihP->ih_refcnt--;
926
927     DLL_INSERT_TAIL(ihP, ihAvailHead, ihAvailTail, ih_next, ih_prev);
928
929     IH_UNLOCK;
930     return 0;
931 }
932
933 /* Sync an inode to disk if its handle isn't NULL */
934 int
935 ih_condsync(IHandle_t * ihP)
936 {
937     int code;
938     FdHandle_t *fdP;
939
940     if (!ihP)
941         return 0;
942
943     fdP = IH_OPEN(ihP);
944     if (fdP == NULL)
945         return -1;
946
947     code = FDH_SYNC(fdP);
948     FDH_CLOSE(fdP);
949
950     return code;
951 }
952
953 void
954 ih_sync_all(void) {
955
956     int ihash;
957
958     IH_LOCK;
959     for (ihash = 0; ihash < I_HANDLE_HASH_SIZE; ihash++) {
960         IHandle_t *ihP, *ihPnext;
961
962         ihP = ihashTable[ihash].ihash_head;
963         if (ihP)
964             ihP->ih_refcnt++;   /* must not disappear over unlock */
965         for (; ihP; ihP = ihPnext) {
966
967             if (ihP->ih_synced) {
968                 FdHandle_t *fdP;
969
970                 ihP->ih_synced = 0;
971                 IH_UNLOCK;
972
973                 fdP = IH_OPEN(ihP);
974                 if (fdP) {
975                     OS_SYNC(fdP->fd_fd);
976                     FDH_CLOSE(fdP);
977                 }
978
979                 IH_LOCK;
980             }
981
982             /* when decrementing the refcount, the ihandle might disappear
983                and we might not even be able to proceed to the next one.
984                Hence the gymnastics putting a hold on the next one already */
985             ihPnext = ihP->ih_next;
986             if (ihPnext) ihPnext->ih_refcnt++;
987
988             if (ihP->ih_refcnt > 1) {
989                 ihP->ih_refcnt--;
990             } else {
991                 IH_UNLOCK;
992                 ih_release(ihP);
993                 IH_LOCK;
994             }
995
996         }
997     }
998     IH_UNLOCK;
999 }
1000
1001 void *
1002 ih_sync_thread(void *dummy) {
1003     while(1) {
1004
1005 #ifdef AFS_PTHREAD_ENV
1006         sleep(10);
1007 #else /* AFS_PTHREAD_ENV */
1008         IOMGR_Sleep(60);
1009 #endif /* AFS_PTHREAD_ENV */
1010
1011         ih_sync_all();
1012     }
1013     return NULL;
1014 }
1015
1016
1017 /*************************************************************************
1018  * OS specific support routines.
1019  *************************************************************************/
1020 #ifndef AFS_NAMEI_ENV
1021 Inode
1022 ih_icreate(IHandle_t * ih, int dev, char *part, Inode nI, int p1, int p2,
1023            int p3, int p4)
1024 {
1025     Inode ino;
1026 #ifdef  AFS_3DISPARES
1027     /* See viceinode.h */
1028     if (p2 == INODESPECIAL) {
1029         int tp = p3;
1030         p3 = p4;
1031         p4 = tp;
1032     }
1033 #endif
1034     ino = ICREATE(dev, part, nI, p1, p2, p3, p4);
1035     return ino;
1036 }
1037 #endif /* AFS_NAMEI_ENV */
1038
1039 afs_sfsize_t
1040 ih_size(FD_t fd)
1041 {
1042 #ifdef AFS_NT40_ENV
1043     LARGE_INTEGER size;
1044     if (!GetFileSizeEx(fd, &size))
1045         return -1;
1046     return size.QuadPart;
1047 #else
1048     struct afs_stat_st status;
1049     if (afs_fstat(fd, &status) < 0)
1050         return -1;
1051     return status.st_size;
1052 #endif
1053 }
1054
1055 #ifndef HAVE_PIO
1056 ssize_t
1057 ih_pread(int fd, void * buf, size_t count, afs_foff_t offset)
1058 {
1059         afs_foff_t code;
1060         code = OS_SEEK(fd, offset, 0);
1061         if (code < 0)
1062             return code;
1063         return OS_READ(fd, buf, count);
1064 }
1065
1066 ssize_t
1067 ih_pwrite(int fd, const void * buf, size_t count, afs_foff_t offset)
1068 {
1069         afs_foff_t code;
1070         code = OS_SEEK(fd, offset, 0);
1071         if (code < 0)
1072             return code;
1073         return OS_WRITE(fd, buf, count);
1074 }
1075 #endif /* !HAVE_PIO */