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