fastio.h 14.9 KB
Newer Older
Berk Onat's avatar
Berk Onat committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/***************************************************************************
 *cr
 *cr            (C) Copyright 1995-2016 The Board of Trustees of the
 *cr                        University of Illinois
 *cr                         All Rights Reserved
 *cr
 ***************************************************************************/
/***************************************************************************
 * RCS INFORMATION:
 *
 *      $RCSfile: fastio.h,v $
 *      $Author: johns $       $Locker:  $             $State: Exp $
 *      $Revision: 1.34 $       $Date: 2016/11/28 05:01:53 $
 *
 ***************************************************************************
 * DESCRIPTION:
 *   This is a simple abstraction layer for system-dependent I/O calls
 * that allow plugins to do binary I/O using the fastest possible method.
 *
 * This code is intended for use by binary trajectory reader plugins that
 * work with multi-gigabyte data sets, reading only binary data.
 *
 ***************************************************************************/

#define FIO_READ    0x01
#define FIO_WRITE   0x02
#define FIO_DIRECT  0x04 /* emulate Unix O_DIRECT flag */
 
/* Compiling on windows */
#if defined(_MSC_VER) || defined(__MINGW32__)

#if 1 
/* use native Windows I/O calls */
#define FASTIO_NATIVEWIN32 1

#include <stdio.h>
#include <string.h>
#include <windows.h>

typedef HANDLE fio_fd;
typedef LONGLONG fio_size_t;
typedef void * fio_caddr_t;

typedef struct {
  fio_caddr_t iov_base;
  int iov_len;
} fio_iovec;


#define FIO_SEEK_CUR  FILE_CURRENT
#define FIO_SEEK_SET  FILE_BEGIN
#define FIO_SEEK_END  FILE_END

static int fio_win32convertfilename(const char *filename, char *newfilename, int maxlen) {
  int i;
  int len=strlen(filename);
 
  if ((len + 1) >= maxlen)
    return -1;
   
  for (i=0; i<len; i++) {
    if (filename[i] == '/')
      newfilename[i] = '\\';
    else
      newfilename[i] = filename[i];
  }
  newfilename[len] = '\0'; /* NUL terminate the string */

  return 0;
}

static int fio_open(const char *filename, int mode, fio_fd *fd) {
  HANDLE fp;
  char winfilename[8192];
  DWORD access;
  DWORD sharing;
  LPSECURITY_ATTRIBUTES security;
  DWORD createmode;
  DWORD flags;

  if (fio_win32convertfilename(filename, winfilename, sizeof(winfilename)))
    return -1;  

  access = 0;
  if (mode & FIO_READ)
    access |= GENERIC_READ;
  if (mode & FIO_WRITE)
    access |= GENERIC_WRITE;
#if 0
  access = FILE_ALL_ACCESS; /* XXX hack if above modes fail */
#endif
#if 1
  if (mode & FIO_DIRECT)
    flags = FILE_FLAG_NO_BUFFERING;
  else
    flags = FILE_ATTRIBUTE_NORMAL;
#else
  if (mode & FIO_DIRECT)
    return -1; /* not supported yet */
#endif

  sharing = 0;       /* disallow sharing with other processes  */
  security = NULL;   /* child processes don't inherit anything */

  /* since we never append, blow away anything that's already there */
  if (mode & FIO_WRITE)
    createmode = CREATE_ALWAYS;
  else 
    createmode = OPEN_EXISTING;

  fp = CreateFile(winfilename, access, sharing, security, 
                  createmode, flags, NULL);

  if (fp == NULL) {
    return -1;
  } else {
    *fd = fp;
    return 0;
  }
}


static int fio_fclose(fio_fd fd) {
  BOOL rc;
  rc = CloseHandle(fd);
  if (rc) 
    return 0;
  else 
    return -1;
}

static fio_size_t fio_fread(void *ptr, fio_size_t size, 
                            fio_size_t nitems, fio_fd fd) {
  BOOL rc;
  DWORD len;
  DWORD readlen;

  len = size * nitems;

  rc = ReadFile(fd, ptr, len, &readlen, NULL);
  if (rc) {
    if (readlen == len)
      return nitems;
    else 
      return 0;
  } else {
    return 0;
  }
}

static fio_size_t fio_readv(fio_fd fd, const fio_iovec * iov, int iovcnt) {
  int i;
  fio_size_t len = 0; 

  for (i=0; i<iovcnt; i++) {
    fio_size_t rc = fio_fread(iov[i].iov_base, iov[i].iov_len, 1, fd);
    if (rc != 1)
      break;
    len += iov[i].iov_len;
  }

  return len;
}

static fio_size_t fio_fwrite(void *ptr, fio_size_t size, 
                             fio_size_t nitems, fio_fd fd) {
  BOOL rc;
  DWORD len;
  DWORD writelen;

  len = size * nitems; 
 
  rc = WriteFile(fd, ptr, len, &writelen, NULL);
  if (rc) {
    if (writelen == len)
      return nitems;
    else
      return 0;
  } else {
    return 0;
  }
}

static fio_size_t fio_fseek(fio_fd fd, fio_size_t offset, int whence) {
#if 1
  /* code that works with older MSVC6 compilers */
  LONGLONG finaloffset;
  LARGE_INTEGER bigint;
  LARGE_INTEGER finalint;

  bigint.QuadPart = offset;
  finalint = bigint;      /* set the high part, which will be overwritten */
  finalint.LowPart = SetFilePointer(fd, bigint.LowPart, &finalint.HighPart, whence);
  if (finalint.LowPart == -1) {
    /* if (finalint.LowPart == INVALID_SET_FILE_POINTER) { */
    /* INVALID_SET_FILE_POINTER is a possible "ok" low order result when */
    /* working with 64-bit offsets, so we have to also check the system  */
    /* error value for this thread to be sure */
    if (GetLastError() != ERROR_SUCCESS) {
      return -1;
    }
  } 

  finaloffset = finalint.QuadPart;
  return 0;
#else
  BOOL rc;
  LONGLONG finaloffset;

  /* SetFilePointerEx() only exists with new .NET compilers */
  rc = SetFilePointerEx(fd, offset, &finaloffset, whence);

  if (rc) 
    return 0;
  else
    return -1;
#endif
}

static fio_size_t fio_ftell(fio_fd fd) {
  /* code that works with older MSVC6 compilers */
  LONGLONG finaloffset;
  LARGE_INTEGER bigint;
  LARGE_INTEGER finalint;

  bigint.QuadPart = 0;
  finalint = bigint;      /* set the high part, which will be overwritten */

  finalint.LowPart = SetFilePointer(fd, bigint.LowPart, &finalint.HighPart, FILE_CURRENT);
  if (finalint.LowPart == -1) {
    /* if (finalint.LowPart == INVALID_SET_FILE_POINTER) { */
    /* INVALID_SET_FILE_POINTER is a possible "ok" low order result when */
    /* working with 64-bit offsets, so we have to also check the system  */
    /* error value for this thread to be sure */
    if (GetLastError() != ERROR_SUCCESS) {
      return -1;
    }
  }

  finaloffset = finalint.QuadPart;

  return finaloffset;
}


#else

/* Version for machines with plain old ANSI C  */

#include <stdio.h>
#include <string.h>

typedef FILE * fio_fd;
typedef size_t fio_size_t;  /* MSVC doesn't uinversally support ssize_t */
typedef void * fio_caddr_t; /* MSVC doesn't universally support caddr_t */

typedef struct {
  fio_caddr_t iov_base;
  int iov_len;
} fio_iovec;

#define FIO_SEEK_CUR SEEK_CUR
#define FIO_SEEK_SET SEEK_SET
#define FIO_SEEK_END SEEK_END

static int fio_open(const char *filename, int mode, fio_fd *fd) {
  char * modestr;
  FILE *fp;

  if (mode & FIO_READ) 
    modestr = "rb";

  if (mode & FIO_WRITE) 
    modestr = "wb";

  if (mode & FIO_DIRECT)
    return -1; /* not supported yet */
 
  fp = fopen(filename, modestr);
  if (fp == NULL) {
    return -1;
  } else {
    *fd = fp;
    return 0;
  }
}

static int fio_fclose(fio_fd fd) {
  return fclose(fd);
}

static fio_size_t fio_fread(void *ptr, fio_size_t size, 
                            fio_size_t nitems, fio_fd fd) {
  return fread(ptr, size, nitems, fd);
}

static fio_size_t fio_readv(fio_fd fd, const fio_iovec * iov, int iovcnt) {
  int i;
  fio_size_t len = 0; 

  for (i=0; i<iovcnt; i++) {
    fio_size_t rc = fread(iov[i].iov_base, iov[i].iov_len, 1, fd);
    if (rc != 1)
      break;
    len += iov[i].iov_len;
  }

  return len;
}

static fio_size_t fio_fwrite(void *ptr, fio_size_t size, 
                             fio_size_t nitems, fio_fd fd) {
  return fwrite(ptr, size, nitems, fd);
}

static fio_size_t fio_fseek(fio_fd fd, fio_size_t offset, int whence) {
  return fseek(fd, offset, whence);
}

static fio_size_t fio_ftell(fio_fd fd) {
  return ftell(fd);
}
#endif /* plain ANSI C */

#else 

/* Version for UNIX machines */
#if defined(__linux)
#ifndef _GNU_SOURCE
#define _GNU_SOURCE            /* required for O_DIRECT */
#endif
#endif
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

typedef int fio_fd;
typedef off_t fio_size_t;      /* off_t is 64-bits with LFS builds */

/*
 * Enable use of kernel readv() if available and reliable
 *
 * Note: Some Linux implementations incorporate readv() code in libc 
 * that does userspace copying of I/O vectors to internal temporary
 * buffers in order to meet the atomicity requirements of the POSIX standard.
 * Such copies make the use of vectorized I/O APIs much less useful for
 * large trajectory files because the internal buffer allocations can fail
 * badly when performing large aggregate I/O operations.  It may be that
 * other implementations of vector I/O have similar problems, and in these
 * cases it is probably best not to use it at all, and to fall back to 
 * non-vectorized I/O APIs to avoid such extra copies.
 */
#if defined(__sun) || defined(__APPLE_CC__) || defined(__linux)
#define USE_KERNEL_READV 1
#endif

typedef void * fio_caddr_t;

#if defined(USE_KERNEL_READV)
#include <errno.h>
#include <sys/uio.h>
typedef struct iovec fio_iovec;
#else

typedef struct {
  fio_caddr_t iov_base;
  int iov_len;
} fio_iovec;
#endif

#define FIO_SEEK_CUR SEEK_CUR
#define FIO_SEEK_SET SEEK_SET
#define FIO_SEEK_END SEEK_END

static int fio_open(const char *filename, int mode, fio_fd *fd) {
  int nfd;
  int oflag = 0;
  
  if (mode & FIO_READ) 
    oflag = O_RDONLY;

  if (mode & FIO_WRITE) 
    oflag = O_WRONLY | O_CREAT | O_TRUNC;

#if defined(__linux)
  /* enable direct I/O, requires block-aligned buffers and I/O sizes */
  if (mode & FIO_DIRECT)
    oflag |= O_DIRECT;
#else
  if (mode & FIO_DIRECT)
    return -1; /* not supported yet */
#endif

  nfd = open(filename, oflag, 0666);
  if (nfd < 0) {
    return -1;
  } else {
    *fd = nfd;
    return 0;
  }
}

static int fio_fclose(fio_fd fd) {
  return close(fd);
}

static fio_size_t fio_fread(void *ptr, fio_size_t size, 
                            fio_size_t nitems, fio_fd fd) {
  fio_size_t i;
  fio_size_t len = 0; 
  fio_size_t cnt = 0;

#if 1
  /*
   * On Linux individual calls to read() can end up doing short reads when
   * reading more than 2GB in a single read call, even on 64-bit machines.  
   * For large structures, e.g. 240M-atoms or larger, we have to use a loop
   * to continue reading into the memory buffer until completion.
   */ 
  for (i=0; i<nitems; i++) {
    fio_size_t szleft = size;
    fio_size_t rc = 0;
    for (szleft=size; szleft > 0; szleft -= rc) {
      rc = read(fd, ((char*) ptr) + (cnt*size) + (size-szleft), szleft);
       if (rc == 0) {
          return cnt;  /* end of file scenario */
       }
//      if (rc != szleft) {
//        printf("fio_fread(): rc %ld  sz: %ld\n", rc, szleft);
//      }
      if (rc < 0) {
        printf("fio_fread(): rc %ld  sz: %ld\n", rc, size);
        perror("  perror fio_fread(): ");
        break;
      }
    }
    len += rc;
    cnt++;
  }
#else
  for (i=0; i<nitems; i++) {
    fio_size_t rc = read(fd, (void*) (((char *) ptr) + (cnt * size)), size);
    if (rc != size) {
//      printf("fio_fread(): rc %ld  sz: %ld\n", rc, size);
//      perror("  perror fio_fread(): ");
      break;
    }
    len += rc;
    cnt++;
  }
#endif

  return cnt;
}

static fio_size_t fio_readv(fio_fd fd, const fio_iovec * iov, int iovcnt) {
  fio_size_t len;
  int i;

#if 0
  fio_size_t tlen;
  for (tlen=0,i=0; i<iovcnt; i++) {
    tlen += iov[i].iov_len;
  }

#if defined(USE_KERNEL_READV)
  len = readv(fd, iov, iovcnt);
  if (len != tlen) {
    printf("fio_readv(): readv() rc: %ld  sz: %ld\n", len, tlen);
    printf("fio_readv(): readv() errno %d\n", errno);
  }

  if ((len < 0 && errno == ENOSYS) ||
      (len != tlen && errno == EINVAL)) 
#endif
  {
    /* XXX this loop doesn't meet the atomicity requirements of
     *     real POSIX readv(), since we don't need that feature 
     */
    len = 0; 
    for (i=0; i<iovcnt; i++) {
      void *ptr = iov[i].iov_base;
      fio_size_t sz = iov[i].iov_len;
      fio_size_t szleft = sz;
      fio_size_t rc=0;

      for (szleft=sz; szleft > 0; szleft -= rc) {
        rc = read(fd, ((char*) ptr)+(sz-szleft), szleft);
        if (rc == 0) {
          return len;  /* end of file scenario */
        }
        if (rc != szleft) {
          printf("fio_readv(): read() rc %ld  sz: %ld\n", rc, szleft);
        }
        if (rc < 0) {
          printf("fio_readv(): read() rc %ld  sz: %ld\n", rc, szleft);
          perror("  perror fio_readv(): ");
          break;
        }
      }
      len += iov[i].iov_len;
    }
  }
#else
#if defined(USE_KERNEL_READV)
  len = readv(fd, iov, iovcnt);
  if (len < 0 && errno == ENOSYS)
#endif
  {
    /* XXX this loop doesn't meet the atomicity requirements of
     *     real POSIX readv(), since we don't need that feature 
     */
    len = 0; 
    for (i=0; i<iovcnt; i++) {
      fio_size_t rc = read(fd, iov[i].iov_base, iov[i].iov_len);
      if (rc != iov[i].iov_len)
        break;
      len += iov[i].iov_len;
    }
  }
#endif

  return len;
}

static fio_size_t fio_fwrite(void *ptr, fio_size_t size, 
                             fio_size_t nitems, fio_fd fd) {
  fio_size_t i;
  fio_size_t len = 0; 
  fio_size_t cnt = 0;

#if 1
  /*
   * On Linux individual calls to write() can end up doing short writes when
   * writing more than 2GB in a single write call, even on 64-bit machines.  
   * For large structures, e.g. 240M-atoms or larger, we have to use a loop
   * to continue writing the memory buffer until completion.
   */ 
  int writecalls=0;
  for (i=0; i<nitems; i++) {
    fio_size_t szleft = size;
    fio_size_t rc = 0;
    for (szleft=size; szleft > 0; szleft -= rc) {
      fio_size_t writesz = szleft;

#if 0
      /* On some kernel versions write calls beyond 2GB may not do */
      /* a partial write and may just return an error immediately. */
      /* Clamp maximum write size to 1GB per write call.           */
      if (writesz > (1024L * 1024L * 1024L))
        writesz = (1024L * 1024L * 1024L);
#endif

      writecalls++;
      rc = write(fd, ((char*) ptr)+(size-szleft), writesz);
      if (rc < 0) {
        printf("fio_fwrite(): rc %ld  sz: %ld  szleft: %ld  calls: %d\n", 
               rc, size, szleft, writecalls);
        perror("  perror fio_fwrite(): ");
        return cnt;
      }
    }
    len += rc;
    cnt++;
  }
#else
  for (i=0; i<nitems; i++) {
    fio_size_t rc = write(fd, ptr, size);
    if (rc != size) {
      printf("fio_fwrite(): rc %ld  sz: %ld\n", rc, size);
      perror("  perror fio_fwrite(): ");
      break;
    }
    len += rc;
    cnt++;
  }
#endif

  return cnt;
}

static fio_size_t fio_fseek(fio_fd fd, fio_size_t offset, int whence) {
 if (lseek(fd, offset, whence) >= 0)
   return 0;  /* success (emulate behavior of fseek) */
 else 
   return -1; /* failure (emulate behavior of fseek) */
}

static fio_size_t fio_ftell(fio_fd fd) {
  return lseek(fd, 0, SEEK_CUR);
}

#endif


/* higher level routines that are OS independent */

static int fio_write_int32(fio_fd fd, int i) {
  return (fio_fwrite(&i, 4, 1, fd) != 1);
}

static int fio_read_int32(fio_fd fd, int *i) {
  return (fio_fread(i, 4, 1, fd) != 1);
}

static int fio_write_str(fio_fd fd, const char *str) {
  int len = strlen(str);
  return (fio_fwrite((void *) str, len, 1, fd) != 1);
}