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