file.c 32.6 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
2
3
4
#if defined (HAVE_CONFIG_H)
#  include "config.h"
#endif

5
#include <assert.h>
6
7
8
9
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
10
#include <stdarg.h>
11
#include <stdio.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
12
#include <string.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
13
14
15
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
16
#include <sys/time.h>  // gettimeofday()
17

Uwe Schulzweida's avatar
Uwe Schulzweida committed
18
19
20
21
#include "dmemory.h"
#include "error.h"
#include "file.h"

Deike Kleberg's avatar
Deike Kleberg committed
22
#include "namespace.h"
Deike Kleberg's avatar
Deike Kleberg committed
23

24
#if ! defined (O_BINARY)
25
26
#define O_BINARY 0
#endif
Uwe Schulzweida's avatar
Uwe Schulzweida committed
27
28

#ifndef strdupx
Uwe Schulzweida's avatar
Uwe Schulzweida committed
29
30
31
32
33
34
35
36
37
38
39
#ifndef strdup
char *strdup(const char *s);
#endif
#define strdupx  strdup
/*
#define strdupx(s)                                \
({                                                \
   const char *__old = (s);                       \
   size_t __len = strlen(__old) + 1;              \
   char *__new = (char *) malloc(__len);          \
   (char *) memcpy(__new, __old, __len);          \
Uwe Schulzweida's avatar
Uwe Schulzweida committed
40
})
Uwe Schulzweida's avatar
Uwe Schulzweida committed
41
*/
Uwe Schulzweida's avatar
Uwe Schulzweida committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#endif


#if defined (HAVE_MMAP)
#  include <sys/mman.h> /* mmap() is defined in this header */
#endif


#if ! defined   (FALSE)
#  define  FALSE  0
#endif

#if ! defined   (TRUE)
#  define  TRUE   1
#endif

/* #define  MAX_FILES  FOPEN_MAX */
#define  MAX_FILES  4096

static int _file_max = MAX_FILES;

static void file_initialize(void);

static int _file_init = FALSE;

#if  defined  (HAVE_LIBPTHREAD)
#include <pthread.h>

70
static pthread_once_t  _file_init_thread = PTHREAD_ONCE_INIT;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
71
72
static pthread_mutex_t _file_mutex;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
73
74
75
76
#  define FILE_LOCK()         pthread_mutex_lock(&_file_mutex)
#  define FILE_UNLOCK()       pthread_mutex_unlock(&_file_mutex)
#  define FILE_INIT()        \
   if ( _file_init == FALSE ) pthread_once(&_file_init_thread, file_initialize)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
77
78
79

#else

Uwe Schulzweida's avatar
Uwe Schulzweida committed
80
81
82
83
#  define FILE_LOCK()
#  define FILE_UNLOCK()
#  define FILE_INIT()        \
   if ( _file_init == FALSE ) file_initialize()
Uwe Schulzweida's avatar
Uwe Schulzweida committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

#endif


typedef struct
{
  int        self;
  int        flag;           /* access and error flag         */
  int        eof;            /* end of file flag              */
  int        fd;             /* file descriptor used for read */
  FILE      *fp;             /* FILE pointer used for write   */
  int        mode;           /* file access mode              */
  char      *name;           /* file name                     */
  off_t      size;           /* file size                     */
  off_t      position;       /* file position                 */
  long       access;         /* file access                   */
  off_t      byteTrans;      /*                               */
  size_t     blockSize;      /* file block size               */
102
  int        type;           /* file type ( 1:open 2:fopen )  */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
103
104
105
106
107
108
109
110
111
112
  int        bufferType;     /* buffer type ( 1:std 2:mmap )  */
  size_t     bufferSize;     /* file buffer size              */
  size_t     mappedSize;     /* mmap buffer size              */
  char      *buffer;         /* file buffer                   */
  long       bufferNumFill;  /* number of buffer fill         */
  char      *bufferPtr;      /* file buffer pointer           */
  off_t      bufferPos;
  off_t      bufferStart;
  off_t      bufferEnd;
  size_t     bufferCnt;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
113
  double     time_in_sec;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
114
}
115
bfile_t;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
116
117
118
119
120
121
122
123
124
125
126
127


enum F_I_L_E_Flags
  {
    FILE_READ  =  01,
    FILE_WRITE =  02,
    FILE_UNBUF =  04,
    FILE_EOF   = 010,
    FILE_ERROR = 020
  };


Uwe Schulzweida's avatar
Uwe Schulzweida committed
128
static int FileInfo  = FALSE;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
129
130
131
132
133
134
135
136
137
138
139


#if ! defined (MIN_BUF_SIZE)
#  define  MIN_BUF_SIZE  131072L
#endif


static size_t FileBufferSizeMin = MIN_BUF_SIZE;
static long   FileBufferSizeEnv = -1;
static int    FileBufferTypeEnv =  0;

140
141
142
static int    FileTypeRead  = FILE_TYPE_OPEN;
static int    FileTypeWrite = FILE_TYPE_FOPEN;
static int    FileFlagWrite = 0;
143
144

static int    FILE_Debug = 0;   /* If set to 1, debugging */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
145
146
147
148
149
150
151
152


static void file_table_print(void);

/*
 * A version string.
 */
#undef   LIBVERSION
153
#define  LIBVERSION      1.8.2
Uwe Schulzweida's avatar
Uwe Schulzweida committed
154
155
156
157
158
159
160
161
162
163
164
165
#define  XSTRING(x)	 #x
#define  STRING(x) 	 XSTRING(x)
const char file_libvers[] = STRING(LIBVERSION) " of "__DATE__" "__TIME__;

/*
  21/05/2004  1.3.2 set min I/O Buffersize to 128k
  31/05/2005  1.4.0 replace fileTable by _fileList
  26/08/2005  1.4.1 fileClose with return value
                    checks for all fileptr
  01/09/2005  1.5.0 thread safe version
  06/11/2005  1.5.1 add filePtrEOF, filePtr, filePtrGetc
  03/02/2006  1.5.2 ansi C: define getpagesize and strdupx
166
  27/12/2007  1.6.0 add FILE_TYPE_FOPEN
167
168
169
  24/03/2008  1.6.1 add O_BINARY if available
                    remove default HAVE_MMAP
                    use HAVE_STRUCT_STAT_ST_BLKSIZE
170
171
  22/08/2010  1.7.0 refactor
  11/11/2010  1.7.1 update for changed interface of error.h
Uwe Schulzweida's avatar
Uwe Schulzweida committed
172
  02/02/2012  1.8.0 cleanup
173
  16/11/2012  1.8.1 added support for unbuffered write
174
  27/06/2013  1.8.2 added env. var. FILE_TYPE_WRITE (1:open; 2:fopen)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
175
176
177
178
179
 */


typedef struct _filePtrToIdx {
  int idx;
180
  bfile_t *ptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
181
182
183
184
  struct _filePtrToIdx *next;
} filePtrToIdx;


Uwe Schulzweida's avatar
Uwe Schulzweida committed
185
186
static filePtrToIdx *_fileList  = NULL;
static filePtrToIdx *_fileAvail = NULL;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
187

188
189
static
void file_list_new(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
190
{
191
  assert(_fileList == NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
192

Uwe Schulzweida's avatar
Uwe Schulzweida committed
193
194
195
  _fileList = (filePtrToIdx *) malloc(_file_max*sizeof(filePtrToIdx));
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
196
static
197
void file_list_delete(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
198
{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
199
200
201
202
203
  if ( _fileList )
    {
      free(_fileList);
      _fileList = NULL;
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
204
205
}

206
207
static
void file_init_pointer(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
208
209
{
  int  i;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
210

Uwe Schulzweida's avatar
Uwe Schulzweida committed
211
212
213
214
215
216
217
218
219
220
221
222
  for ( i = 0; i < _file_max; i++ )
    {
      _fileList[i].next = _fileList + i + 1;
      _fileList[i].idx  = i;
      _fileList[i].ptr  = 0;
    }

  _fileList[_file_max-1].next = 0;

  _fileAvail = _fileList;
}

223
224
static
bfile_t *file_to_pointer(int idx)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
225
{
226
  bfile_t *fileptr = NULL;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
227

Uwe Schulzweida's avatar
Uwe Schulzweida committed
228
  FILE_INIT();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
229
230
231

  if ( idx >= 0 && idx < _file_max )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
232
      FILE_LOCK();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
233
234
235

      fileptr = _fileList[idx].ptr;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
236
      FILE_UNLOCK();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
237
238
    }
  else
239
    Error("file index %d undefined!", idx);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
240
241
242
243
244

  return (fileptr);
}

/* Create an index from a pointer */
245
246
static
int file_from_pointer(bfile_t *ptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
247
248
249
250
251
252
{
  int      idx = -1;
  filePtrToIdx *newptr;

  if ( ptr )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
253
      FILE_LOCK();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
254
255
256
257
258
259
260
261

      if ( _fileAvail )
	{
	  newptr       = _fileAvail;
	  _fileAvail   = _fileAvail->next;
	  newptr->next = 0;
	  idx	       = newptr->idx;
	  newptr->ptr  = ptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
262

Uwe Schulzweida's avatar
Uwe Schulzweida committed
263
	  if ( FILE_Debug )
264
	    Message("Pointer %p has idx %d from file list", ptr, idx);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
265
266
	}
      else
267
	Warning("Too many open files (limit is %d)!", _file_max);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
268

Uwe Schulzweida's avatar
Uwe Schulzweida committed
269
      FILE_UNLOCK();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
270
271
    }
  else
272
    Error("Internal problem (pointer %p undefined)", ptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
273
274
275
276

  return (idx);
}

277
278
static
void file_init_entry(bfile_t *fileptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
279
280
281
282
283
284
285
286
287
288
289
290
{
  fileptr->self          = file_from_pointer(fileptr);

  fileptr->flag          = 0;
  fileptr->fd            = -1;
  fileptr->fp            = NULL;
  fileptr->mode          = 0;
  fileptr->size          = 0;
  fileptr->name          = NULL;
  fileptr->access        = 0;
  fileptr->position      = 0;
  fileptr->byteTrans     = 0;
291
  fileptr->type          = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
292
293
294
295
296
297
298
299
300
301
  fileptr->bufferType    = 0;
  fileptr->bufferSize    = 0;
  fileptr->mappedSize    = 0;
  fileptr->buffer        = NULL;
  fileptr->bufferNumFill = 0;
  fileptr->bufferStart   = 0;
  fileptr->bufferEnd     = -1;
  fileptr->bufferPos     = 0;
  fileptr->bufferCnt     = 0;
  fileptr->bufferPtr     = NULL;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
302
  fileptr->time_in_sec   = 0.0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
303
304
}

305
306
static
bfile_t *file_new_entry(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
307
{
308
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
309

310
  fileptr = (bfile_t *) malloc(sizeof(bfile_t));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
311
312
313
314
315
316

  if ( fileptr ) file_init_entry(fileptr);

  return (fileptr);
}

317
318
static
void file_delete_entry(bfile_t *fileptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
319
320
321
322
323
{
  int idx;

  idx = fileptr->self;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
324
  FILE_LOCK();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
325
326
327
328
329
330
331

  free(fileptr);

  _fileList[idx].next = _fileAvail;
  _fileList[idx].ptr  = 0;
  _fileAvail   	      = &_fileList[idx];

Uwe Schulzweida's avatar
Uwe Schulzweida committed
332
  FILE_UNLOCK();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
333
334

  if ( FILE_Debug )
335
    Message("Removed idx %d from file list", idx);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
336
337
338
339
340
341
342
343
344
345
346
347
348
}


const char *fileLibraryVersion(void)
{
  return (file_libvers);
}


#ifndef POSIXIO_DEFAULT_PAGESIZE
#define POSIXIO_DEFAULT_PAGESIZE 4096
#endif

349
350
static
int pagesize(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
351
{
352
353
#if defined(_SC_PAGESIZE)
  return ((int) sysconf(_SC_PAGESIZE));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
354
355
356
357
358
#else
  return ((int) POSIXIO_DEFAULT_PAGESIZE);
#endif
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
359
360
361
362
363
364
365
366
367
static
double file_time()
{
  double tseconds = 0.0;
  struct timeval mytime;
  gettimeofday(&mytime, NULL);
  tseconds = (double) mytime.tv_sec + (double) mytime.tv_usec*1.0e-6;
  return (tseconds);
}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
368
369
370
371
372
373

void fileDebug(int debug)
{
  FILE_Debug = debug;

  if ( FILE_Debug )
374
    Message("Debug level %d", debug);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
375
376
377
378
379
}


void *filePtr(int fileID)
{
380
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
381
382
383
384
385
386

  fileptr = file_to_pointer(fileID);

  return (fileptr);
}

387
388
static
void file_pointer_info(const char *caller, int fileID)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
389
{
390
391
392
393
394
395
  if ( FILE_Debug )
    {
      fprintf(stdout, "%-18s : ", caller);
      fprintf(stdout, "The fileID %d underlying pointer is not valid!", fileID);
      fprintf(stdout, "\n");
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
396
397
398
399
400
401
}


int fileSetBufferType(int fileID, int type)
{
  int ret = 0;
402
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
403
404
405
406
407
408
409

  fileptr = file_to_pointer(fileID);

  if ( fileptr )
    {
      switch (type)
	{
410
411
	case FILE_BUFTYPE_STD:
	case FILE_BUFTYPE_MMAP:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
412
413
414
	  fileptr->bufferType = type;
	  break;
	default:
415
	  Error("File type %d not implemented!", type);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
416
417
418
419
	}
    }

#if ! defined (HAVE_MMAP)
420
  if ( type == FILE_BUFTYPE_MMAP ) ret = 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
421
422
423
424
425
426
427
428
#endif

  return (ret);
}


int fileGetBufferType(int fileID)
{
429
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
430
431
432
433
434
435
436
437
438
439
440
441
  int bufferType = 0;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) bufferType = fileptr->bufferType;

  return (bufferType);
}


int fileFlush(int fileID)
{
442
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
443
444
445
446
447
448
449
450
451
452
453
454
  int retval = 0;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) retval = fflush(fileptr->fp);

  return (retval);
}


void fileClearerr(int fileID)
{
455
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
456
457
458
459
460
461
462
463
464
465
466
467
468

  fileptr = file_to_pointer(fileID);

  if ( fileptr )
    {
      if ( fileptr->mode != 'r' )
	clearerr(fileptr->fp);
    }
}


int filePtrEOF(void *vfileptr)
{
469
  bfile_t *fileptr = (bfile_t *) vfileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
470
471
472
473
474
475
476
477
478
479
  int retval = 0;

  if ( fileptr ) retval = (fileptr->flag & FILE_EOF) != 0;

  return (retval);
}


int fileEOF(int fileID)
{
480
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
481
482
483
484
485
486
487
488
489
490
491
492
  int retval = 0;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) retval = (fileptr->flag & FILE_EOF) != 0;

  return (retval);
}


int fileError(int fileID)
{
493
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
  int retval = 0;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) retval = (fileptr->flag & FILE_ERROR) != 0;

  return (retval);
}


void fileRewind(int fileID)
{
  fileSetPos(fileID, (off_t) 0, SEEK_SET);
  fileClearerr(fileID);
}


off_t fileGetPos(int fileID)
{
  off_t filepos = 0;
514
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
515
516
517
518
519

  fileptr = file_to_pointer(fileID);

  if ( fileptr )
    {
520
      if ( fileptr->mode == 'r' && fileptr->type == FILE_TYPE_OPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
521
522
523
524
525
	filepos = fileptr->position;
      else
	filepos = ftell(fileptr->fp);
    }

526
  if ( FILE_Debug ) Message("Position %ld", filepos);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
527
528
529
530
531
532
533
534

  return (filepos);
}


int fileSetPos(int fileID, off_t offset, int whence)
{
  int status = 0;
535
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
536
537
538

  fileptr = file_to_pointer(fileID);

539
  if ( FILE_Debug ) Message("Offset %8ld  Whence %3d", (long) offset, whence);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
540
541
542

  if ( fileptr == 0 )
    {
543
      file_pointer_info(__func__, fileID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
544
545
546
547
548
549
      return (1);
    }

  switch (whence)
    {
    case SEEK_SET:
550
      if ( fileptr->mode == 'r' && fileptr->type == FILE_TYPE_OPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
551
	{
552
	  off_t position = offset;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
553
554
555
	  fileptr->position = position;
	  if ( position < fileptr->bufferStart || position > fileptr->bufferEnd )
	    {
556
	      if ( fileptr->bufferType == FILE_BUFTYPE_STD )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
557
558
559
560
561
562
563
564
565
566
567
568
		fileptr->bufferPos = position;
	      else
		fileptr->bufferPos = position - position % pagesize();

	      fileptr->bufferCnt = 0;
	      fileptr->bufferPtr = NULL;
	    }
	  else
	    {
	      if ( fileptr->bufferPos != fileptr->bufferEnd + 1 )
		{
		  if ( FILE_Debug )
569
		    Message("Reset buffer pos from %ld to %ld",
Uwe Schulzweida's avatar
Uwe Schulzweida committed
570
			    fileptr->bufferPos, fileptr->bufferEnd + 1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
571

Uwe Schulzweida's avatar
Uwe Schulzweida committed
572
573
		  fileptr->bufferPos = fileptr->bufferEnd + 1;
		}
574
	      fileptr->bufferCnt = (size_t)(fileptr->bufferEnd - position) + 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
575
576
577
578
579
580
581
582
583
	      fileptr->bufferPtr = fileptr->buffer + position - fileptr->bufferStart;
	    }
	}
      else
	{
	  status = fseek(fileptr->fp, offset, whence);
	}
      break;
    case SEEK_CUR:
584
      if ( fileptr->mode == 'r' && fileptr->type == FILE_TYPE_OPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
585
586
	{
	  fileptr->position += offset;
587
	  off_t position = fileptr->position;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
588
589
	  if ( position < fileptr->bufferStart || position > fileptr->bufferEnd )
	    {
590
	      if ( fileptr->bufferType == FILE_BUFTYPE_STD )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
591
592
593
594
595
596
597
598
599
600
601
602
		fileptr->bufferPos = position;
	      else
		fileptr->bufferPos = position - position % pagesize();

	      fileptr->bufferCnt = 0;
	      fileptr->bufferPtr = NULL;
	    }
	  else
	    {
	      if ( fileptr->bufferPos != fileptr->bufferEnd + 1 )
		{
		  if ( FILE_Debug )
603
		    Message("Reset buffer pos from %ld to %ld",
Uwe Schulzweida's avatar
Uwe Schulzweida committed
604
			    fileptr->bufferPos, fileptr->bufferEnd + 1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
605

Uwe Schulzweida's avatar
Uwe Schulzweida committed
606
607
		  fileptr->bufferPos = fileptr->bufferEnd + 1;
		}
608
	      fileptr->bufferCnt -= (size_t)offset;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
609
610
611
612
613
614
615
616
617
	      fileptr->bufferPtr += offset;
	    }
	}
      else
	{
	  status = fseek(fileptr->fp, offset, whence);
	}
      break;
    default:
618
      Error("Whence = %d not implemented", whence);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
619
620
621
622
623
624
625
626
627
    }

  if ( fileptr->position < fileptr->size )
    if ( (fileptr->flag & FILE_EOF) != 0 )
      fileptr->flag -= FILE_EOF;

  return (status);
}

628
629
static
void file_table_print(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
630
631
632
{
  int fileID;
  int lprintHeader = 1;
633
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683

  for ( fileID = 0; fileID < _file_max; fileID++ )
    {
      fileptr = file_to_pointer(fileID);

      if ( fileptr )
	{
	  if ( lprintHeader )
	    {
	      fprintf(stderr, "\nFile table:\n");
	      fprintf(stderr, "+-----+---------+");
	      fprintf(stderr, "----------------------------------------------------+\n");
	      fprintf(stderr, "|  ID |  Mode   |");
	      fprintf(stderr, "  Name                                              |\n");
	      fprintf(stderr, "+-----+---------+");
	      fprintf(stderr, "----------------------------------------------------+\n");
	      lprintHeader = 0;
	    }

	  fprintf(stderr, "| %3d | ", fileID);

	  switch ( fileptr->mode )
	    {
	    case 'r':
	      fprintf(stderr, "read   ");
	      break;
	    case 'w':
	      fprintf(stderr, "write  ");
	      break;
	    case 'a':
	      fprintf(stderr, "append ");
	      break;
	    default:
	      fprintf(stderr, "unknown");
	    }

          fprintf(stderr, " | %-51s|\n", fileptr->name);
	}
    }

  if ( lprintHeader == 0 )
    {
      fprintf(stderr, "+-----+---------+");
      fprintf(stderr, "----------------------------------------------------+\n");
    }
}


char *fileInqName(int fileID)
{
684
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
685
686
687
688
689
690
691
692
693
694
695
696
  char *name = NULL;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) name = fileptr->name;

  return (name);
}


int fileInqMode(int fileID)
{
697
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
698
699
700
701
702
703
704
705
706
  int mode = 0;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) mode = fileptr->mode;

  return (mode);
}

707
708
static
long file_getenv(const char *envName)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
{
  char *envString;
  long envValue = -1;
  long fact = 1;

  envString = getenv(envName);

  if ( envString )
    {
      int loop;

      for ( loop = 0; loop < (int) strlen(envString); loop++ )
	{
	  if ( ! isdigit((int) envString[loop]) )
	    {
	      switch ( tolower((int) envString[loop]) )
		{
		case 'k':  fact =       1024;  break;
		case 'm':  fact =    1048576;  break;
		case 'g':  fact = 1073741824;  break;
		default:
		  fact = 0;
731
732
		  Message("Invalid number string in %s: %s", envName, envString);
		  Warning("%s must comprise only digits [0-9].",envName);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
733
734
735
736
737
738
739
		}
	      break;
	    }
	}

      if ( fact ) envValue = fact*atol(envString);

740
      if ( FILE_Debug ) Message("Set %s to %ld", envName, envValue);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
741
742
743
744
745
    }

  return (envValue);
}

746
747
static
void file_initialize(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
748
749
{
  long value;
750
  char *envString;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
751
752
753
754
755
756
757
758
759
760
761
762
763

#if  defined  (HAVE_LIBPTHREAD)
  /* initialize global API mutex lock */
  pthread_mutex_init(&_file_mutex, NULL);
#endif

  value = file_getenv("FILE_DEBUG");
  if ( value >= 0 ) FILE_Debug = (int) value;

  value = file_getenv("FILE_MAX");
  if ( value >= 0 ) _file_max = (int) value;

  if ( FILE_Debug )
764
    Message("FILE_MAX = %d", _file_max);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
765

Uwe Schulzweida's avatar
Uwe Schulzweida committed
766
  FileInfo  = (int) file_getenv("FILE_INFO");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
767
768
769

  value  = file_getenv("FILE_BUFSIZE");
  if ( value >= 0 ) FileBufferSizeEnv = value;
770
771
772
773
774
  else
    {
      value  = file_getenv("GRIB_API_IO_BUFFER_SIZE");
      if ( value >= 0 ) FileBufferSizeEnv = value;
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
775

776
  value = file_getenv("FILE_TYPE_READ");
777
778
779
780
781
782
  if ( value > 0 )
    {
      switch (value)
	{
	case FILE_TYPE_OPEN:
	case FILE_TYPE_FOPEN:
783
	  FileTypeRead = (int)value;
784
785
	  break;
	default:
786
	  Warning("File type %d not implemented!", value);
787
788
789
	}
    }

790
791
792
793
794
795
796
  value = file_getenv("FILE_TYPE_WRITE");
  if ( value > 0 )
    {
      switch (value)
	{
	case FILE_TYPE_OPEN:
	case FILE_TYPE_FOPEN:
797
	  FileTypeWrite = (int)value;
798
799
800
801
802
803
	  break;
	default:
	  Warning("File type %d not implemented!", value);
	}
    }

804
805
806
#if defined (O_NONBLOCK)
  FileFlagWrite = O_NONBLOCK;
#endif
807
808
809
810
811
812
813
814
  envString = getenv("FILE_FLAG_WRITE");
  if ( envString )
    {
#if defined (O_NONBLOCK)
      if ( strcmp(envString, "NONBLOCK") == 0 ) FileFlagWrite = O_NONBLOCK;
#endif
    }

815
  value = file_getenv("FILE_BUFTYPE");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
816
#if ! defined (HAVE_MMAP)
817
  if ( value == FILE_BUFTYPE_MMAP )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
818
    {
819
      Warning("MMAP not available!");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
820
821
822
823
824
825
826
      value = 0;
    }
#endif
  if ( value > 0 )
    {
      switch (value)
	{
827
828
	case FILE_BUFTYPE_STD:
	case FILE_BUFTYPE_MMAP:
829
	  FileBufferTypeEnv = (int)value;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
830
831
	  break;
	default:
832
	  Warning("File buffer type %d not implemented!", value);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
833
834
835
836
	}
    }

  file_list_new();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
837
  atexit(file_list_delete);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
838

Uwe Schulzweida's avatar
Uwe Schulzweida committed
839
  FILE_LOCK();
840

Uwe Schulzweida's avatar
Uwe Schulzweida committed
841
842
  file_init_pointer();

Uwe Schulzweida's avatar
Uwe Schulzweida committed
843
  FILE_UNLOCK();
844

Uwe Schulzweida's avatar
Uwe Schulzweida committed
845
846
847
848
849
  if ( FILE_Debug ) atexit(file_table_print);

  _file_init = TRUE;
}

850
851
static
void file_set_buffer(bfile_t *fileptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
852
853
854
855
856
857
858
859
{
  size_t buffersize = 0;

  if ( fileptr->mode == 'r' )
    {
      if ( FileBufferTypeEnv )
	fileptr->bufferType = FileBufferTypeEnv;
      else if ( fileptr->bufferType == 0 )
860
	fileptr->bufferType = FILE_BUFTYPE_STD;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
861
862

      if ( FileBufferSizeEnv >= 0 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
863
	buffersize = (size_t) FileBufferSizeEnv;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
864
865
866
867
868
869
870
871
872
      else if ( fileptr->bufferSize > 0 )
	buffersize = fileptr->bufferSize;
      else
	{
	  buffersize = fileptr->blockSize * 4;
	  if ( buffersize < FileBufferSizeMin ) buffersize = FileBufferSizeMin;
	}

      if ( (size_t) fileptr->size < buffersize )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
873
	buffersize = (size_t) fileptr->size;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
874

875
      if ( fileptr->bufferType == FILE_BUFTYPE_MMAP )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
876
	{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
877
	  size_t blocksize = (size_t) pagesize();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
878
879
880
881
882
883
	  size_t minblocksize = 4 * blocksize;
	  buffersize = buffersize - buffersize % minblocksize;

	  if ( buffersize < (size_t) fileptr->size && buffersize < minblocksize )
	    buffersize = minblocksize;
	}
884
885

      if ( buffersize == 0 ) buffersize = 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
886
887
888
    }
  else
    {
889
      fileptr->bufferType = FILE_BUFTYPE_STD;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
890
891

      if ( FileBufferSizeEnv >= 0 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
892
	buffersize = (size_t) FileBufferSizeEnv;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
893
894
895
896
897
898
899
900
901
      else if ( fileptr->bufferSize > 0 )
	buffersize = fileptr->bufferSize;
      else
	{
	  buffersize = fileptr->blockSize * 4;
	  if ( buffersize < FileBufferSizeMin ) buffersize = FileBufferSizeMin;
	}
    }

902
  if ( fileptr->bufferType == FILE_BUFTYPE_STD || fileptr->type == FILE_TYPE_FOPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
903
    {
904
905
906
907
908
909
      if ( buffersize > 0 )
        {
          fileptr->buffer = (char *) malloc(buffersize);
          if ( fileptr->buffer == NULL )
            SysError("Allocation of file buffer failed!");
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
910
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
911

912
  if ( fileptr->type == FILE_TYPE_FOPEN )
913
    if ( setvbuf(fileptr->fp, fileptr->buffer, fileptr->buffer ? _IOFBF : _IONBF, buffersize) )
914
      SysError("setvbuf failed!");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
915
916
917
918

  fileptr->bufferSize = buffersize;
}

919
920
static
int file_fill_buffer(bfile_t *fileptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
921
{
922
  ssize_t nread;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
923
924
925
  int fd;
  long offset = 0;
  off_t retseek;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
926

Uwe Schulzweida's avatar
Uwe Schulzweida committed
927
  if ( FILE_Debug )
928
    Message("file ptr = %p  Cnt = %ld", fileptr, fileptr->bufferCnt);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
929
930
931
932

  if ( (fileptr->flag & FILE_EOF) != 0 ) return (EOF);

  if ( fileptr->buffer == NULL ) file_set_buffer(fileptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
933

Uwe Schulzweida's avatar
Uwe Schulzweida committed
934
935
936
937
938
  if ( fileptr->bufferSize == 0 ) return (EOF);

  fd = fileptr->fd;

#if defined (HAVE_MMAP)
939
  if ( fileptr->bufferType == FILE_BUFTYPE_MMAP )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
940
941
942
943
944
945
946
    {
      if ( fileptr->bufferPos >= fileptr->size )
	{
	  nread = 0;
	}
      else
	{
947
948
          xassert(fileptr->bufferSize <= SSIZE_MAX);
	  nread = (ssize_t)fileptr->bufferSize;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
949
950
951
952
953
	  if ( (nread + fileptr->bufferPos) > fileptr->size )
	    nread = fileptr->size - fileptr->bufferPos;

	  if ( fileptr->buffer )
	    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
954
              int ret;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
955
	      ret = munmap(fileptr->buffer, fileptr->mappedSize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
956
	      if ( ret == -1 ) SysError("munmap error for read %s", fileptr->name);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
957
958
959
	      fileptr->buffer = NULL;
	    }

960
	  fileptr->mappedSize = (size_t)nread;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
961

Uwe Schulzweida's avatar
Uwe Schulzweida committed
962
	  fileptr->buffer = (char*) mmap(NULL, (size_t) nread, PROT_READ, MAP_PRIVATE, fd, fileptr->bufferPos);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
963

Uwe Schulzweida's avatar
Uwe Schulzweida committed
964
	  if ( fileptr->buffer == MAP_FAILED ) SysError("mmap error for read %s", fileptr->name);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
965
966
967
968
969
970
971
972
973

	  offset = fileptr->position - fileptr->bufferPos;
	}
    }
  else
#endif
    {
      retseek = lseek(fileptr->fd, fileptr->bufferPos, SEEK_SET);
      if ( retseek == (off_t)-1 )
974
	SysError("lseek error at pos %ld file %s", (long) fileptr->bufferPos, fileptr->name);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
975

976
      nread = read(fd, fileptr->buffer, fileptr->bufferSize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
    }

  if ( nread <= 0 )
    {
      if ( nread == 0 )
	fileptr->flag |= FILE_EOF;
      else
	fileptr->flag |= FILE_ERROR;

      fileptr->bufferCnt = 0;
      return (EOF);
    }

  fileptr->bufferPtr = fileptr->buffer;
991
  fileptr->bufferCnt = (size_t)nread;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
992
993
994
995
996
997
998

  fileptr->bufferStart = fileptr->bufferPos;
  fileptr->bufferPos  += nread;
  fileptr->bufferEnd   = fileptr->bufferPos - 1;

  if ( FILE_Debug )
    {
999
1000
      Message("fileID = %d  Val     = %d",  fileptr->self, (int) fileptr->buffer[0]);
      Message("fileID = %d  Start   = %ld", fileptr->self, fileptr->bufferStart);