file.c 32.3 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
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
9
#include <stdint.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
#ifndef strdup
char *strdup(const char *s);
#endif
#define strdupx  strdup
/*
#define strdupx(s)                                \
({                                                \
   const char *__old = (s);                       \
   size_t __len = strlen(__old) + 1;              \
38
   char *__new = (char *) Malloc(__len);          \
Uwe Schulzweida's avatar
Uwe Schulzweida committed
39
   (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

#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   */
  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               */
101
102
103
  int        mode;           /* file access mode              */
  short      type;           /* file type ( 1:open 2:fopen )  */
  short      bufferType;     /* buffer type ( 1:std 2:mmap )  */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
104
105
106
107
108
109
110
111
112
  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


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


static size_t FileBufferSizeMin = MIN_BUF_SIZE;
static long   FileBufferSizeEnv = -1;
138
static short  FileBufferTypeEnv =  0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
139

140
141
static short  FileTypeRead  = FILE_TYPE_OPEN;
static short  FileTypeWrite = FILE_TYPE_FOPEN;
142
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
#define  XSTRING(x)	 #x
#define  STRING(x) 	 XSTRING(x)
Thomas Jahns's avatar
Thomas Jahns committed
156
static const char file_libvers[] = STRING(LIBVERSION) " of " __DATE__ " " __TIME__;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
157
158
159
160
161
162
163
164
165

/*
  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

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

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
  if ( _fileList )
    {
201
      Free(_fileList);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
202
203
      _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
  Free(fileptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
327
328
329
330
331

  _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
}


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


345
346
static
int pagesize(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
347
{
348
349
#if defined(_SC_PAGESIZE)
  return ((int) sysconf(_SC_PAGESIZE));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
350
#else
Thomas Jahns's avatar
Thomas Jahns committed
351
352
353
#ifndef POSIXIO_DEFAULT_PAGESIZE
#define POSIXIO_DEFAULT_PAGESIZE 4096
#endif
Uwe Schulzweida's avatar
Uwe Schulzweida committed
354
355
356
357
  return ((int) POSIXIO_DEFAULT_PAGESIZE);
#endif
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
358
359
360
361
362
363
364
365
366
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
367
368
369
370
371
372

void fileDebug(int debug)
{
  FILE_Debug = debug;

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


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

  fileptr = file_to_pointer(fileID);

  return (fileptr);
}

386
387
static
void file_pointer_info(const char *caller, int fileID)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
388
{
389
390
391
392
393
394
  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
395
396
397
398
399
400
}


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

  fileptr = file_to_pointer(fileID);

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

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

  return (ret);
}

int fileFlush(int fileID)
{
427
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
428
429
430
431
432
433
434
435
436
437
438
439
  int retval = 0;

  fileptr = file_to_pointer(fileID);

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

  return (retval);
}


void fileClearerr(int fileID)
{
440
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
441
442
443
444
445
446
447
448
449
450
451
452
453

  fileptr = file_to_pointer(fileID);

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


int filePtrEOF(void *vfileptr)
{
454
  bfile_t *fileptr = (bfile_t *) vfileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
455
456
457
458
459
460
461
462
463
464
  int retval = 0;

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

  return (retval);
}


int fileEOF(int fileID)
{
465
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
  int retval = 0;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) retval = (fileptr->flag & FILE_EOF) != 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;
485
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
486
487
488
489
490

  fileptr = file_to_pointer(fileID);

  if ( fileptr )
    {
491
      if ( fileptr->mode == 'r' && fileptr->type == FILE_TYPE_OPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
492
493
494
495
496
	filepos = fileptr->position;
      else
	filepos = ftell(fileptr->fp);
    }

497
  if ( FILE_Debug ) Message("Position %ld", filepos);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
498
499
500
501
502
503
504
505

  return (filepos);
}


int fileSetPos(int fileID, off_t offset, int whence)
{
  int status = 0;
506
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
507
508
509

  fileptr = file_to_pointer(fileID);

510
  if ( FILE_Debug ) Message("Offset %8ld  Whence %3d", (long) offset, whence);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
511
512
513

  if ( fileptr == 0 )
    {
514
      file_pointer_info(__func__, fileID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
515
516
517
518
519
520
      return (1);
    }

  switch (whence)
    {
    case SEEK_SET:
521
      if ( fileptr->mode == 'r' && fileptr->type == FILE_TYPE_OPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
522
	{
523
	  off_t position = offset;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
524
525
526
	  fileptr->position = position;
	  if ( position < fileptr->bufferStart || position > fileptr->bufferEnd )
	    {
527
	      if ( fileptr->bufferType == FILE_BUFTYPE_STD )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
528
529
530
531
532
533
534
535
536
537
538
539
		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 )
540
		    Message("Reset buffer pos from %ld to %ld",
Uwe Schulzweida's avatar
Uwe Schulzweida committed
541
			    fileptr->bufferPos, fileptr->bufferEnd + 1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
542

Uwe Schulzweida's avatar
Uwe Schulzweida committed
543
544
		  fileptr->bufferPos = fileptr->bufferEnd + 1;
		}
545
	      fileptr->bufferCnt = (size_t)(fileptr->bufferEnd - position) + 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
546
547
548
549
550
551
552
553
554
	      fileptr->bufferPtr = fileptr->buffer + position - fileptr->bufferStart;
	    }
	}
      else
	{
	  status = fseek(fileptr->fp, offset, whence);
	}
      break;
    case SEEK_CUR:
555
      if ( fileptr->mode == 'r' && fileptr->type == FILE_TYPE_OPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
556
557
	{
	  fileptr->position += offset;
558
	  off_t position = fileptr->position;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
559
560
	  if ( position < fileptr->bufferStart || position > fileptr->bufferEnd )
	    {
561
	      if ( fileptr->bufferType == FILE_BUFTYPE_STD )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
562
563
564
565
566
567
568
569
570
571
572
573
		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 )
574
		    Message("Reset buffer pos from %ld to %ld",
Uwe Schulzweida's avatar
Uwe Schulzweida committed
575
			    fileptr->bufferPos, fileptr->bufferEnd + 1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
576

Uwe Schulzweida's avatar
Uwe Schulzweida committed
577
578
		  fileptr->bufferPos = fileptr->bufferEnd + 1;
		}
579
	      fileptr->bufferCnt -= (size_t)offset;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
580
581
582
583
584
585
586
587
588
	      fileptr->bufferPtr += offset;
	    }
	}
      else
	{
	  status = fseek(fileptr->fp, offset, whence);
	}
      break;
    default:
589
      Error("Whence = %d not implemented", whence);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
590
591
592
593
594
595
596
597
598
    }

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

  return (status);
}

599
600
static
void file_table_print(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
601
602
603
{
  int fileID;
  int lprintHeader = 1;
604
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654

  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)
{
655
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
656
657
658
659
660
661
662
663
664
665
666
667
  char *name = NULL;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) name = fileptr->name;

  return (name);
}


int fileInqMode(int fileID)
{
668
  bfile_t *fileptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
669
670
671
672
673
674
675
676
677
  int mode = 0;

  fileptr = file_to_pointer(fileID);

  if ( fileptr ) mode = fileptr->mode;

  return (mode);
}

678
679
static
long file_getenv(const char *envName)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
{
  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;
702
703
		  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
704
705
706
707
708
709
710
		}
	      break;
	    }
	}

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

711
      if ( FILE_Debug ) Message("Set %s to %ld", envName, envValue);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
712
713
714
715
716
    }

  return (envValue);
}

717
718
static
void file_initialize(void)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
719
720
{
  long value;
721
  char *envString;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
722
723
724
725
726
727
728
729
730
731
732
733
734

#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 )
735
    Message("FILE_MAX = %d", _file_max);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
736

Uwe Schulzweida's avatar
Uwe Schulzweida committed
737
  FileInfo  = (int) file_getenv("FILE_INFO");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
738
739
740

  value  = file_getenv("FILE_BUFSIZE");
  if ( value >= 0 ) FileBufferSizeEnv = value;
741
742
743
744
745
  else
    {
      value  = file_getenv("GRIB_API_IO_BUFFER_SIZE");
      if ( value >= 0 ) FileBufferSizeEnv = value;
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
746

747
  value = file_getenv("FILE_TYPE_READ");
748
749
750
751
752
753
  if ( value > 0 )
    {
      switch (value)
	{
	case FILE_TYPE_OPEN:
	case FILE_TYPE_FOPEN:
754
	  FileTypeRead = (short)value;
755
756
	  break;
	default:
757
	  Warning("File type %d not implemented!", value);
758
759
760
	}
    }

761
762
763
764
765
766
767
  value = file_getenv("FILE_TYPE_WRITE");
  if ( value > 0 )
    {
      switch (value)
	{
	case FILE_TYPE_OPEN:
	case FILE_TYPE_FOPEN:
768
	  FileTypeWrite = (short)value;
769
770
771
772
773
774
	  break;
	default:
	  Warning("File type %d not implemented!", value);
	}
    }

775
776
777
#if defined (O_NONBLOCK)
  FileFlagWrite = O_NONBLOCK;
#endif
778
779
780
781
782
783
784
785
  envString = getenv("FILE_FLAG_WRITE");
  if ( envString )
    {
#if defined (O_NONBLOCK)
      if ( strcmp(envString, "NONBLOCK") == 0 ) FileFlagWrite = O_NONBLOCK;
#endif
    }

786
  value = file_getenv("FILE_BUFTYPE");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
787
#if ! defined (HAVE_MMAP)
788
  if ( value == FILE_BUFTYPE_MMAP )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
789
    {
790
      Warning("MMAP not available!");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
791
792
793
794
795
796
797
      value = 0;
    }
#endif
  if ( value > 0 )
    {
      switch (value)
	{
798
799
	case FILE_BUFTYPE_STD:
	case FILE_BUFTYPE_MMAP:
800
	  FileBufferTypeEnv = (short)value;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
801
802
	  break;
	default:
803
	  Warning("File buffer type %d not implemented!", value);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
804
805
806
807
	}
    }

  file_list_new();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
808
  atexit(file_list_delete);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
809

Uwe Schulzweida's avatar
Uwe Schulzweida committed
810
  FILE_LOCK();
811

Uwe Schulzweida's avatar
Uwe Schulzweida committed
812
813
  file_init_pointer();

Uwe Schulzweida's avatar
Uwe Schulzweida committed
814
  FILE_UNLOCK();
815

Uwe Schulzweida's avatar
Uwe Schulzweida committed
816
817
818
819
820
  if ( FILE_Debug ) atexit(file_table_print);

  _file_init = TRUE;
}

821
822
static
void file_set_buffer(bfile_t *fileptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
823
824
825
826
827
828
829
830
{
  size_t buffersize = 0;

  if ( fileptr->mode == 'r' )
    {
      if ( FileBufferTypeEnv )
	fileptr->bufferType = FileBufferTypeEnv;
      else if ( fileptr->bufferType == 0 )
831
	fileptr->bufferType = FILE_BUFTYPE_STD;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
832
833

      if ( FileBufferSizeEnv >= 0 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
834
	buffersize = (size_t) FileBufferSizeEnv;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
835
836
837
838
839
840
841
842
843
      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
844
	buffersize = (size_t) fileptr->size;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
845

846
      if ( fileptr->bufferType == FILE_BUFTYPE_MMAP )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
847
	{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
848
	  size_t blocksize = (size_t) pagesize();
Uwe Schulzweida's avatar
Uwe Schulzweida committed
849
850
851
852
853
854
	  size_t minblocksize = 4 * blocksize;
	  buffersize = buffersize - buffersize % minblocksize;

	  if ( buffersize < (size_t) fileptr->size && buffersize < minblocksize )
	    buffersize = minblocksize;
	}
855
856

      if ( buffersize == 0 ) buffersize = 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
857
858
859
    }
  else
    {
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;
	}
    }

873
  if ( fileptr->bufferType == FILE_BUFTYPE_STD || fileptr->type == FILE_TYPE_FOPEN )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
874
    {
875
876
      if ( buffersize > 0 )
        {
877
          fileptr->buffer = (char *) Malloc(buffersize);
878
879
880
          if ( fileptr->buffer == NULL )
            SysError("Allocation of file buffer failed!");
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
881
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
882

883
  if ( fileptr->type == FILE_TYPE_FOPEN )
884
    if ( setvbuf(fileptr->fp, fileptr->buffer, fileptr->buffer ? _IOFBF : _IONBF, buffersize) )
885
      SysError("setvbuf failed!");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
886
887
888
889

  fileptr->bufferSize = buffersize;
}

890
891
static
int file_fill_buffer(bfile_t *fileptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
892
{
893
  ssize_t nread;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
894
895
896
  int fd;
  long offset = 0;
  off_t retseek;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
897

Uwe Schulzweida's avatar
Uwe Schulzweida committed
898
  if ( FILE_Debug )
899
    Message("file ptr = %p  Cnt = %ld", fileptr, fileptr->bufferCnt);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
900
901
902
903

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

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

Uwe Schulzweida's avatar
Uwe Schulzweida committed
905
906
907
908
909
  if ( fileptr->bufferSize == 0 ) return (EOF);

  fd = fileptr->fd;

#if defined (HAVE_MMAP)
910
  if ( fileptr->bufferType == FILE_BUFTYPE_MMAP )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
911
912
913
914
915
916
917
    {
      if ( fileptr->bufferPos >= fileptr->size )
	{
	  nread = 0;
	}
      else
	{
918
          xassert(fileptr->bufferSize <= SIZE_MAX);
919
	  nread = (ssize_t)fileptr->bufferSize;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
920
921
922
923
924
	  if ( (nread + fileptr->bufferPos) > fileptr->size )
	    nread = fileptr->size - fileptr->bufferPos;

	  if ( fileptr->buffer )
	    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
925
              int ret;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
926
	      ret = munmap(fileptr->buffer, fileptr->mappedSize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
927
	      if ( ret == -1 ) SysError("munmap error for read %s", fileptr->name);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
928
929
930
	      fileptr->buffer = NULL;
	    }

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

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

Uwe Schulzweida's avatar
Uwe Schulzweida committed
935
	  if ( fileptr->buffer == MAP_FAILED ) SysError("mmap error for read %s", fileptr->name);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
936
937
938
939
940
941
942
943
944

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

947
      nread = read(fd, fileptr->buffer, fileptr->bufferSize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
948
949
950
951
952
953
954
955
956
957
958
959
960
961
    }

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

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

  fileptr->bufferPtr = fileptr->buffer;
962
  fileptr->bufferCnt = (size_t)nread;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
963
964
965
966
967
968
969

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

  if ( FILE_Debug )
    {
970
971
972
973
974
975
976
      Message("fileID = %d  Val     = %d",  fileptr->self, (int) fileptr->buffer[0]);
      Message("fileID = %d  Start   = %ld", fileptr->self, fileptr->bufferStart);
      Message("fileID = %d  End     = %ld", fileptr->self, fileptr->bufferEnd);
      Message("fileID = %d  nread   = %ld", fileptr->self, nread);
      Message("fileID = %d  offset  = %ld", fileptr->self, offset);
      Message("fileID = %d  Pos     = %ld", fileptr->self, fileptr->bufferPos);
      Message("fileID = %d  postion = %ld", fileptr->self, fileptr->position);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
977
978
979
980
981
    }

  if ( offset > 0 )
    {
      if ( offset > nread )
982
	Error("Internal problem with buffer handling. nread = %d offset = %d", nread, offset);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
983
984

      fileptr->bufferPtr += offset;
985
      fileptr->bufferCnt -= (size_t)offset;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
986
987
988
989
990
991
992
    }

  fileptr->bufferNumFill++;

  return ((unsigned char) *fileptr->bufferPtr);
}

993
994
static
void file_copy_from_buffer(bfile_t *fileptr, void *ptr, size_t size)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
995
996
{
  if ( FILE_Debug )
997
    Message("size = %ld  Cnt = %ld", size, fileptr->bufferCnt);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
998
999

  if ( fileptr->bufferCnt < size )
1000
    Error("Buffer too small. bufferCnt = %d", fileptr->bufferCnt);
For faster browsing, not all history is shown. View entire blame