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