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