vol: Tidy up 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 #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
29 #include "nfs.h"
30 #include "ihandle.h"
31 #include "viceinode.h"
32 #include "afs/afs_assert.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 = (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     else
456         _ih_release_r(ihP);
457
458     IH_UNLOCK;
459
460     return 0;
461 }
462
463 /*
464  * Actually close the file descriptor handle and return it to
465  * the free list.
466  */
467 int
468 fd_reallyclose(FdHandle_t * fdP)
469 {
470     FD_t closeFd;
471     IHandle_t *ihP;
472
473     if (!fdP)
474         return 0;
475
476     IH_LOCK;
477     osi_Assert(ih_Inited);
478     osi_Assert(fdInUseCount > 0);
479     osi_Assert(fdP->fd_status == FD_HANDLE_INUSE);
480
481     ihP = fdP->fd_ih;
482     closeFd = fdP->fd_fd;
483     fdP->fd_refcnt--;
484
485     if (fdP->fd_refcnt == 0) {
486         DLL_DELETE(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext, fd_ihprev);
487         DLL_INSERT_TAIL(fdP, fdAvailHead, fdAvailTail, fd_next, fd_prev);
488
489         fdP->fd_status = FD_HANDLE_AVAIL;
490         fdP->fd_refcnt = 0;
491         fdP->fd_ih = NULL;
492         fdP->fd_fd = INVALID_FD;
493     }
494
495     /* All the file descriptor handles have been closed; reset
496      * the IH_REALLY_CLOSED flag indicating that ih_reallyclose
497      * has completed its job.
498      */
499     if (!ihP->ih_fdhead) {
500         ihP->ih_flags &= ~IH_REALLY_CLOSED;
501     }
502
503     if (fdP->fd_refcnt == 0) {
504         IH_UNLOCK;
505         OS_CLOSE(closeFd);
506         IH_LOCK;
507         fdInUseCount -= 1;
508     }
509
510     /* If this is not the only reference to the Inode then we can decrement
511      * the reference count, otherwise we need to call ih_release. */
512     if (ihP->ih_refcnt > 1)
513         ihP->ih_refcnt--;
514     else
515         _ih_release_r(ihP);
516
517     IH_UNLOCK;
518
519     return 0;
520 }
521
522 /* Enable buffered I/O on a file descriptor */
523 StreamHandle_t *
524 stream_fdopen(FD_t fd)
525 {
526     StreamHandle_t *streamP;
527
528     IH_LOCK;
529     if (streamAvailHead == NULL) {
530         streamHandleAllocateChunk();
531     }
532     streamP = streamAvailHead;
533     DLL_DELETE(streamP, streamAvailHead, streamAvailTail, str_next, str_prev);
534     IH_UNLOCK;
535     streamP->str_fd = fd;
536     streamP->str_buflen = 0;
537     streamP->str_bufoff = 0;
538     streamP->str_fdoff = 0;
539     streamP->str_error = 0;
540     streamP->str_eof = 0;
541     streamP->str_direction = STREAM_DIRECTION_NONE;
542     return streamP;
543 }
544
545 /* Open a file for buffered I/O */
546 StreamHandle_t *
547 stream_open(const char *filename, const char *mode)
548 {
549     FD_t fd = INVALID_FD;
550
551     if (strcmp(mode, "r") == 0) {
552         fd = OS_OPEN(filename, O_RDONLY, 0);
553     } else if (strcmp(mode, "r+") == 0) {
554         fd = OS_OPEN(filename, O_RDWR, 0);
555     } else if (strcmp(mode, "w") == 0) {
556         fd = OS_OPEN(filename, O_WRONLY | O_TRUNC | O_CREAT, 0);
557     } else if (strcmp(mode, "w+") == 0) {
558         fd = OS_OPEN(filename, O_RDWR | O_TRUNC | O_CREAT, 0);
559     } else if (strcmp(mode, "a") == 0) {
560         fd = OS_OPEN(filename, O_WRONLY | O_APPEND | O_CREAT, 0);
561     } else if (strcmp(mode, "a+") == 0) {
562         fd = OS_OPEN(filename, O_RDWR | O_APPEND | O_CREAT, 0);
563     } else {
564         osi_Assert(FALSE);              /* not implemented */
565     }
566
567     if (fd == INVALID_FD) {
568         return NULL;
569     }
570     return stream_fdopen(fd);
571 }
572
573 /* fread for buffered I/O handles */
574 afs_sfsize_t
575 stream_read(void *ptr, afs_fsize_t size, afs_fsize_t nitems,
576             StreamHandle_t * streamP)
577 {
578     afs_fsize_t nbytes, bytesRead, bytesToRead;
579     char *p;
580
581     /* Need to seek before changing direction */
582     if (streamP->str_direction == STREAM_DIRECTION_NONE) {
583         streamP->str_direction = STREAM_DIRECTION_READ;
584         streamP->str_bufoff = 0;
585         streamP->str_buflen = 0;
586     } else {
587         osi_Assert(streamP->str_direction == STREAM_DIRECTION_READ);
588     }
589
590     bytesRead = 0;
591     nbytes = size * nitems;
592     p = (char *)ptr;
593     while (nbytes > 0 && !streamP->str_eof) {
594         if (streamP->str_buflen == 0) {
595             streamP->str_bufoff = 0;
596             streamP->str_buflen =
597                 OS_PREAD(streamP->str_fd, streamP->str_buffer,
598                         STREAM_HANDLE_BUFSIZE, streamP->str_fdoff);
599             if (streamP->str_buflen < 0) {
600                 streamP->str_error = errno;
601                 streamP->str_buflen = 0;
602                 bytesRead = 0;
603                 break;
604             } else if (streamP->str_buflen == 0) {
605                 streamP->str_eof = 1;
606                 break;
607             }
608             streamP->str_fdoff += streamP->str_buflen;
609         }
610
611         bytesToRead = nbytes;
612         if (bytesToRead > streamP->str_buflen) {
613             bytesToRead = streamP->str_buflen;
614         }
615         memcpy(p, streamP->str_buffer + streamP->str_bufoff, bytesToRead);
616         p += bytesToRead;
617         streamP->str_bufoff += bytesToRead;
618         streamP->str_buflen -= bytesToRead;
619         bytesRead += bytesToRead;
620         nbytes -= bytesToRead;
621     }
622
623     return (bytesRead / size);
624 }
625
626 /* fwrite for buffered I/O handles */
627 afs_sfsize_t
628 stream_write(void *ptr, afs_fsize_t size, afs_fsize_t nitems,
629              StreamHandle_t * streamP)
630 {
631     char *p;
632     afs_sfsize_t rc;
633     afs_fsize_t nbytes, bytesWritten, bytesToWrite;
634
635     /* Need to seek before changing direction */
636     if (streamP->str_direction == STREAM_DIRECTION_NONE) {
637         streamP->str_direction = STREAM_DIRECTION_WRITE;
638         streamP->str_bufoff = 0;
639         streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
640     } else {
641         osi_Assert(streamP->str_direction == STREAM_DIRECTION_WRITE);
642     }
643
644     nbytes = size * nitems;
645     bytesWritten = 0;
646     p = (char *)ptr;
647     while (nbytes > 0) {
648         if (streamP->str_buflen == 0) {
649             rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
650                           STREAM_HANDLE_BUFSIZE, streamP->str_fdoff);
651             if (rc < 0) {
652                 streamP->str_error = errno;
653                 bytesWritten = 0;
654                 break;
655             }
656             streamP->str_fdoff += rc;
657             streamP->str_bufoff = 0;
658             streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
659         }
660
661         bytesToWrite = nbytes;
662         if (bytesToWrite > streamP->str_buflen) {
663             bytesToWrite = streamP->str_buflen;
664         }
665         memcpy(streamP->str_buffer + streamP->str_bufoff, p, bytesToWrite);
666         p += bytesToWrite;
667         streamP->str_bufoff += bytesToWrite;
668         streamP->str_buflen -= bytesToWrite;
669         bytesWritten += bytesToWrite;
670         nbytes -= bytesToWrite;
671     }
672
673     return (bytesWritten / size);
674 }
675
676 /* fseek for buffered I/O handles */
677 int
678 stream_aseek(StreamHandle_t * streamP, afs_foff_t offset)
679 {
680     ssize_t rc;
681     int retval = 0;
682
683     if (streamP->str_direction == STREAM_DIRECTION_WRITE
684         && streamP->str_bufoff > 0) {
685         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
686                       streamP->str_bufoff, streamP->str_fdoff);
687         if (rc < 0) {
688             streamP->str_error = errno;
689             retval = -1;
690         }
691     }
692     streamP->str_fdoff = offset;
693     streamP->str_bufoff = 0;
694     streamP->str_buflen = 0;
695     streamP->str_eof = 0;
696     streamP->str_direction = STREAM_DIRECTION_NONE;
697     return retval;
698 }
699
700 /* fflush for buffered I/O handles */
701 int
702 stream_flush(StreamHandle_t * streamP)
703 {
704     ssize_t rc;
705     int retval = 0;
706
707     if (streamP->str_direction == STREAM_DIRECTION_WRITE
708         && streamP->str_bufoff > 0) {
709         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
710                       streamP->str_bufoff, streamP->str_fdoff);
711         if (rc < 0) {
712             streamP->str_error = errno;
713             retval = -1;
714         } else {
715             streamP->str_fdoff += rc;
716         }
717         streamP->str_bufoff = 0;
718         streamP->str_buflen = STREAM_HANDLE_BUFSIZE;
719     }
720
721     return retval;
722 }
723
724 /* Free a buffered I/O handle */
725 int
726 stream_close(StreamHandle_t * streamP, int reallyClose)
727 {
728     ssize_t rc;
729     int retval = 0;
730
731     osi_Assert(streamP != NULL);
732     if (streamP->str_direction == STREAM_DIRECTION_WRITE
733         && streamP->str_bufoff > 0) {
734         rc = OS_PWRITE(streamP->str_fd, streamP->str_buffer,
735                       streamP->str_bufoff, streamP->str_fdoff);
736         if (rc < 0) {
737             retval = -1;
738         } else {
739             streamP->str_fdoff += rc;
740         }
741     }
742     if (reallyClose) {
743         rc = OS_CLOSE(streamP->str_fd);
744         if (rc < 0) {
745             retval = -1;
746         }
747     }
748     streamP->str_fd = INVALID_FD;
749
750     IH_LOCK;
751     DLL_INSERT_TAIL(streamP, streamAvailHead, streamAvailTail,
752                     str_next, str_prev);
753     IH_UNLOCK;
754     return retval;
755 }
756
757 /* Close all unused file descriptors associated with the inode
758  * handle. Called with IH_LOCK held. May drop and reacquire
759  * IH_LOCK. Sets the IH_REALLY_CLOSED flag in the inode handle
760  * if it fails to close all file handles.
761  */
762 static int
763 ih_fdclose(IHandle_t * ihP)
764 {
765     int closeCount, closedAll;
766     FdHandle_t *fdP, *head, *tail, *next;
767
768     osi_Assert(ihP->ih_refcnt > 0);
769
770     closedAll = 1;
771     DLL_INIT_LIST(head, tail);
772     ihP->ih_flags &= ~IH_REALLY_CLOSED;
773
774     /*
775      * Remove the file descriptors for this Inode from the LRU queue
776      * and the IHandle queue and put them on a temporary queue so we
777      * can drop the lock before we close the files.
778      */
779     for (fdP = ihP->ih_fdhead; fdP != NULL; fdP = next) {
780         next = fdP->fd_ihnext;
781         osi_Assert(fdP->fd_ih == ihP);
782         osi_Assert(fdP->fd_status == FD_HANDLE_OPEN
783                || fdP->fd_status == FD_HANDLE_INUSE);
784         if (fdP->fd_status == FD_HANDLE_OPEN) {
785             DLL_DELETE(fdP, ihP->ih_fdhead, ihP->ih_fdtail, fd_ihnext,
786                        fd_ihprev);
787             DLL_DELETE(fdP, fdLruHead, fdLruTail, fd_next, fd_prev);
788             DLL_INSERT_TAIL(fdP, head, tail, fd_next, fd_prev);
789         } else {
790             closedAll = 0;
791             ihP->ih_flags |= IH_REALLY_CLOSED;
792         }
793     }
794
795     /* If the ihandle reference count is 1, we should have
796      * closed all file descriptors.
797      */
798     if (ihP->ih_refcnt == 1 || closedAll) {
799         osi_Assert(closedAll);
800         osi_Assert(!ihP->ih_fdhead);
801         osi_Assert(!ihP->ih_fdtail);
802     }
803
804     if (head == NULL) {
805         return 0;               /* No file descriptors closed */
806     }
807
808     IH_UNLOCK;
809     /*
810      * Close the file descriptors
811      */
812     closeCount = 0;
813     for (fdP = head; fdP != NULL; fdP = fdP->fd_next) {
814         OS_CLOSE(fdP->fd_fd);
815         fdP->fd_status = FD_HANDLE_AVAIL;
816         fdP->fd_refcnt = 0;
817         fdP->fd_fd = INVALID_FD;
818         fdP->fd_ih = NULL;
819         closeCount++;
820     }
821
822     IH_LOCK;
823     osi_Assert(fdInUseCount >= closeCount);
824     fdInUseCount -= closeCount;
825
826     /*
827      * Append the temporary queue to the list of available descriptors
828      */
829     if (fdAvailHead == NULL) {
830         fdAvailHead = head;
831         fdAvailTail = tail;
832     } else {
833         fdAvailTail->fd_next = head;
834         head->fd_prev = fdAvailTail;
835         fdAvailTail = tail;
836     }
837
838     return 0;
839 }
840
841 /* Close all cached file descriptors for this inode. */
842 int
843 ih_reallyclose(IHandle_t * ihP)
844 {
845     if (!ihP)
846         return 0;
847
848     IH_LOCK;
849     ihP->ih_refcnt++;   /* must not disappear over unlock */
850     if (ihP->ih_synced) {
851         FdHandle_t *fdP;
852         ihP->ih_synced = 0;
853         IH_UNLOCK;
854
855         fdP = IH_OPEN(ihP);
856         if (fdP) {
857             OS_SYNC(fdP->fd_fd);
858             FDH_CLOSE(fdP);
859         }
860
861         IH_LOCK;
862     }
863
864     osi_Assert(ihP->ih_refcnt > 0);
865
866     ih_fdclose(ihP);
867
868     if (ihP->ih_refcnt > 1)
869         ihP->ih_refcnt--;
870     else
871         _ih_release_r(ihP);
872
873     IH_UNLOCK;
874     return 0;
875 }
876
877 /* Release an Inode handle. All cached file descriptors for this
878  * inode are closed when the last reference to this handle is released
879  */
880 static int
881 _ih_release_r(IHandle_t * ihP)
882 {
883     int ihash;
884
885     if (!ihP)
886         return 0;
887
888     osi_Assert(ihP->ih_refcnt > 0);
889
890     if (ihP->ih_refcnt > 1) {
891         ihP->ih_refcnt--;
892         return 0;
893     }
894
895     ihash = IH_HASH(ihP->ih_dev, ihP->ih_vid, ihP->ih_ino);
896     DLL_DELETE(ihP, ihashTable[ihash].ihash_head,
897                ihashTable[ihash].ihash_tail, ih_next, ih_prev);
898
899     ih_fdclose(ihP);
900
901     ihP->ih_refcnt--;
902
903     DLL_INSERT_TAIL(ihP, ihAvailHead, ihAvailTail, ih_next, ih_prev);
904
905     return 0;
906 }
907
908 /* Release an Inode handle. All cached file descriptors for this
909  * inode are closed when the last reference to this handle is released
910  */
911 int
912 ih_release(IHandle_t * ihP)
913 {
914     int ret;
915
916     if (!ihP)
917         return 0;
918
919     IH_LOCK;
920     ret = _ih_release_r(ihP);
921     IH_UNLOCK;
922     return ret;
923 }
924
925 /* Sync an inode to disk if its handle isn't NULL */
926 int
927 ih_condsync(IHandle_t * ihP)
928 {
929     int code;
930     FdHandle_t *fdP;
931
932     if (!ihP)
933         return 0;
934
935     fdP = IH_OPEN(ihP);
936     if (fdP == NULL)
937         return -1;
938
939     code = FDH_SYNC(fdP);
940     FDH_CLOSE(fdP);
941
942     return code;
943 }
944
945 void
946 ih_sync_all(void) {
947
948     int ihash;
949
950     IH_LOCK;
951     for (ihash = 0; ihash < I_HANDLE_HASH_SIZE; ihash++) {
952         IHandle_t *ihP, *ihPnext;
953
954         ihP = ihashTable[ihash].ihash_head;
955         if (ihP)
956             ihP->ih_refcnt++;   /* must not disappear over unlock */
957         for (; ihP; ihP = ihPnext) {
958
959             if (ihP->ih_synced) {
960                 FdHandle_t *fdP;
961
962                 ihP->ih_synced = 0;
963                 IH_UNLOCK;
964
965                 fdP = IH_OPEN(ihP);
966                 if (fdP) {
967                     OS_SYNC(fdP->fd_fd);
968                     FDH_CLOSE(fdP);
969                 }
970
971                 IH_LOCK;
972             }
973
974             /* when decrementing the refcount, the ihandle might disappear
975                and we might not even be able to proceed to the next one.
976                Hence the gymnastics putting a hold on the next one already */
977             ihPnext = ihP->ih_next;
978             if (ihPnext) ihPnext->ih_refcnt++;
979
980             if (ihP->ih_refcnt > 1)
981                 ihP->ih_refcnt--;
982             else
983                 _ih_release_r(ihP);
984         }
985     }
986     IH_UNLOCK;
987 }
988
989 void *
990 ih_sync_thread(void *dummy) {
991     while(1) {
992
993 #ifdef AFS_PTHREAD_ENV
994         sleep(10);
995 #else /* AFS_PTHREAD_ENV */
996         IOMGR_Sleep(60);
997 #endif /* AFS_PTHREAD_ENV */
998
999         ih_sync_all();
1000     }
1001     return NULL;
1002 }
1003
1004
1005 /*************************************************************************
1006  * OS specific support routines.
1007  *************************************************************************/
1008 #ifndef AFS_NAMEI_ENV
1009 Inode
1010 ih_icreate(IHandle_t * ih, int dev, char *part, Inode nI, int p1, int p2,
1011            int p3, int p4)
1012 {
1013     Inode ino;
1014 #ifdef  AFS_3DISPARES
1015     /* See viceinode.h */
1016     if (p2 == INODESPECIAL) {
1017         int tp = p3;
1018         p3 = p4;
1019         p4 = tp;
1020     }
1021 #endif
1022     ino = ICREATE(dev, part, nI, p1, p2, p3, p4);
1023     return ino;
1024 }
1025 #endif /* AFS_NAMEI_ENV */
1026
1027 afs_sfsize_t
1028 ih_size(FD_t fd)
1029 {
1030 #ifdef AFS_NT40_ENV
1031     LARGE_INTEGER size;
1032     if (!GetFileSizeEx(fd, &size))
1033         return -1;
1034     return size.QuadPart;
1035 #else
1036     struct afs_stat_st status;
1037     if (afs_fstat(fd, &status) < 0)
1038         return -1;
1039     return status.st_size;
1040 #endif
1041 }
1042
1043 #ifndef HAVE_PIO
1044 ssize_t
1045 ih_pread(int fd, void * buf, size_t count, afs_foff_t offset)
1046 {
1047         afs_foff_t code;
1048         code = OS_SEEK(fd, offset, 0);
1049         if (code < 0)
1050             return code;
1051         return OS_READ(fd, buf, count);
1052 }
1053
1054 ssize_t
1055 ih_pwrite(int fd, const 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_WRITE(fd, buf, count);
1062 }
1063 #endif /* !HAVE_PIO */