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