-
Notifications
You must be signed in to change notification settings - Fork 66
/
Compat.cpp
1855 lines (1597 loc) · 45 KB
/
Compat.cpp
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
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
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Module Name:
compat.cpp
Abstract:
Functions that provide compatibility between the Windows and Linux versions,
and mostly that serve to keep #ifdef's out of the main code in order to
improve readibility.
Authors:
Bill Bolosky, November, 2011
Environment:
User mode service.
Revision History:
--*/
#include "stdafx.h"
#include "Compat.h"
#include "BigAlloc.h"
#ifndef _MSC_VER
#include <fcntl.h>
#include <aio.h>
#include <err.h>
#include <unistd.h>
#endif
#include "exit.h"
#ifdef PROFILE_WAIT
#include <map>
#endif
#include "DataWriter.h"
#include "Error.h"
using std::min;
using std::max;
#ifdef PROFILE_WAIT
#undef AcquireExclusiveLock
#undef WaitForSingleWaiterObject
#undef WaitForEvent
void AcquireUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock);
bool WaitForSingleWaiterObject(SingleWaiterObject *singleWaiterObject);
void WaitForEvent(EventObject *eventObject);
using std::map;
using std::string;
static map<string,_int64> times;
void addTime(const char* fn, int line, _int64 time)
{
if (time > 0) {
char s[20];
sprintf(s, ":%d", line);
string key = string(fn) + string(s);
times[key] += time;
}
}
void AcquireExclusiveLockProfile(ExclusiveLock *lock, const char* fn, int line)
{
_int64 start = timeInMillis();
AcquireExclusiveLock(lock);
addTime(fn, line, timeInMillis() - start);
}
bool WaitForSingleWaiterObjectProfile(SingleWaiterObject *singleWaiterObject, const char* fn, int line)
{
_int64 start = timeInMillis();
bool result = WaitForSingleWaiterObject(singleWaiterObject);
addTime(fn, line, timeInMillis() - start);
return result;
}
void WaitForEventProfile(EventObject *eventObject, const char* fn, int line)
{
_int64 start = timeInMillis();
WaitForEvent(eventObject);
addTime(fn, line, timeInMillis() - start);
}
#endif
void PrintWaitProfile()
{
#ifdef PROFILE_WAIT
printf("function:line wait_time (s)\n");
for (map<string,_int64>::iterator lt = times.begin(); lt != times.end(); lt++) {
printf("%s %.3f\n", lt->first.data(), lt->second * 0.0001);
}
#endif
}
#ifdef _MSC_VER
const void* memmem(const void* data, const size_t dataLength, const void* pattern, const size_t patternLength)
{
if (dataLength < patternLength) {
return NULL;
}
const void* p = data;
const char first = *(char*)pattern;
size_t count = dataLength - patternLength + 1;
while (count > 0) {
const void* q = memchr(p, first, count);
if (q == NULL) {
return NULL;
}
if (0 == memcmp(q, pattern, patternLength)) {
return q;
}
count -= ((char*)q - (char*)p) + 1;
p = (char*)q + 1;
}
return NULL;
}
_int64 timeInMillis()
/**
* Get the current time in milliseconds since some arbitrary starting point
* (e.g. system boot or epoch)
*/
{
return GetTickCount64();
}
_int64 timeInNanos()
{
static _int64 performanceFrequency = 0;
if (0 == performanceFrequency) {
QueryPerformanceFrequency((PLARGE_INTEGER)&performanceFrequency);
}
LARGE_INTEGER perfCount;
QueryPerformanceCounter(&perfCount);
return perfCount.QuadPart * 1000000000 / performanceFrequency;
}
void AcquireUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
EnterCriticalSection(lock);
}
void ReleaseUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
LeaveCriticalSection(lock);
}
bool InitializeUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
InitializeCriticalSection(lock);
return true;
}
bool DestroyUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
DeleteCriticalSection(lock);
return true;
}
bool CreateSingleWaiterObject(SingleWaiterObject *newWaiter)
{
*newWaiter = CreateEvent(NULL,TRUE,FALSE,NULL);
if (NULL == *newWaiter) {
return false;
}
return true;
}
void DestroySingleWaiterObject(SingleWaiterObject *waiter)
{
CloseHandle(*waiter);
}
void SignalSingleWaiterObject(SingleWaiterObject *singleWaiterObject) {
SetEvent(*singleWaiterObject);
}
bool WaitForSingleWaiterObject(SingleWaiterObject *singleWaiterObject) {
DWORD retVal = WaitForSingleObject(*singleWaiterObject,INFINITE);
if (WAIT_OBJECT_0 != retVal) {
return false;
}
return true;
}
void ResetSingleWaiterObject(SingleWaiterObject *singleWaiterObject) {
ResetEvent(*singleWaiterObject);
}
//
// In Windows, the single waiter objects are already implemented using events.
//
void CreateEventObject(EventObject *newEvent) {CreateSingleWaiterObject(newEvent);}
void DestroyEventObject(EventObject *eventObject) {DestroySingleWaiterObject(eventObject);}
void AllowEventWaitersToProceed(EventObject *eventObject) {SignalSingleWaiterObject(eventObject);}
void PreventEventWaitersFromProceeding(EventObject *eventObject) {ResetSingleWaiterObject(eventObject);}
void WaitForEvent(EventObject *eventObject) {WaitForSingleWaiterObject(eventObject);}
bool WaitForEventWithTimeout(EventObject *eventObject, _int64 timeoutInMillis)
{
DWORD retVal = WaitForSingleObjectEx(*eventObject, (unsigned)timeoutInMillis, FALSE);
if (retVal == WAIT_OBJECT_0) {
return true;
} else if (retVal == WAIT_TIMEOUT) {
return false;
}
WriteErrorMessage("WaitForSingleObject returned unexpected result %d (error %d)\n", retVal, GetLastError());
soft_exit(1);
return false; // NOTREACHED: Just to avoid the compiler complaining.
}
void BindThreadToProcessor(unsigned processorNumber) // This hard binds a thread to a processor. You can no-op it at some perf hit.
{
if (!SetThreadAffinityMask(GetCurrentThread(),((unsigned _int64)1) << processorNumber)) {
WriteErrorMessage("Binding thread to processor %d failed, %d\n",processorNumber,GetLastError());
}
}
int InterlockedIncrementAndReturnNewValue(volatile int *valueToIncrement)
{
return InterlockedIncrement((volatile long *)valueToIncrement);
}
int InterlockedDecrementAndReturnNewValue(volatile int *valueToDecrement)
{
return InterlockedDecrement((volatile long *)valueToDecrement);
}
_uint32 InterlockedCompareExchange32AndReturnOldValue(volatile _uint32 *valueToUpdate, _uint32 replacementValue, _uint32 desiredPreviousValue)
{
return (_uint32) InterlockedCompareExchange(valueToUpdate, replacementValue, desiredPreviousValue);
}
_uint64 InterlockedCompareExchange64AndReturnOldValue(volatile _uint64 *valueToUpdate, _uint64 replacementValue, _uint64 desiredPreviousValue)
{
return (_uint64) InterlockedCompareExchange(valueToUpdate, replacementValue, desiredPreviousValue);
}
void* InterlockedCompareExchangePointerAndReturnOldValue(void * volatile *valueToUpdate, void* replacementValue, void* desiredPreviousValue)
{
return InterlockedCompareExchangePointer(valueToUpdate, replacementValue, desiredPreviousValue);
}
struct WrapperThreadContext {
ThreadMainFunction mainFunction;
void *mainFunctionParameter;
};
DWORD WINAPI
WrapperThreadMain(PVOID Context)
{
WrapperThreadContext *context = (WrapperThreadContext *)Context;
(*context->mainFunction)(context->mainFunctionParameter);
delete context;
context = NULL;
return 0;
}
bool StartNewThread(ThreadMainFunction threadMainFunction, void *threadMainFunctionParameter)
{
WrapperThreadContext *context = new WrapperThreadContext;
if (NULL == context) {
return false;
}
context->mainFunction = threadMainFunction;
context->mainFunctionParameter = threadMainFunctionParameter;
HANDLE hThread;
DWORD threadId;
hThread = CreateThread(NULL,0,WrapperThreadMain,context,0,&threadId);
if (NULL == hThread) {
WriteErrorMessage("Create thread failed, %d\n",GetLastError());
delete context;
context = NULL;
return false;
}
CloseHandle(hThread);
hThread = NULL;
return true;
}
void SleepForMillis(unsigned millis)
{
Sleep(millis);
}
unsigned GetNumberOfProcessors()
{
SYSTEM_INFO systemInfo[1];
GetSystemInfo(systemInfo);
return systemInfo->dwNumberOfProcessors;
}
_int64 QueryFileSize(const char *fileName) {
HANDLE hFile = CreateFile(fileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (INVALID_HANDLE_VALUE == hFile) {
WriteErrorMessage("Unable to open file '%s' for QueryFileSize, %d\n", fileName, GetLastError());
soft_exit(1);
}
LARGE_INTEGER fileSize;
if (!GetFileSizeEx(hFile,&fileSize)) {
WriteErrorMessage("GetFileSize failed, %d\n",GetLastError());
soft_exit(1);
}
CloseHandle(hFile);
return fileSize.QuadPart;
}
bool
DeleteSingleFile(
const char* filename)
{
return DeleteFile(filename) ? true : false;
}
bool
MoveSingleFile(
const char* oldFileName,
const char* newFileName)
{
return MoveFile(oldFileName, newFileName) ? true : false;
}
class LargeFileHandle
{
public:
HANDLE handle;
};
LargeFileHandle*
OpenLargeFile(
const char* filename,
const char* mode)
{
_ASSERT(strlen(mode) == 1 && (*mode == 'r' || *mode == 'w' || *mode == 'a'));
LargeFileHandle* result = new LargeFileHandle();
result->handle = CreateFile(filename,
*mode == 'r' ? GENERIC_READ :
*mode == 'a' ? FILE_APPEND_DATA
: GENERIC_WRITE,
0 /* exclusive */,
NULL,
*mode == 'w' ? CREATE_ALWAYS : OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (result->handle == NULL) {
WriteErrorMessage("open large file %s failed with 0x%x\n", filename, GetLastError());
delete (void*) result;
return NULL;
}
return result;
}
size_t
WriteLargeFile(
LargeFileHandle* file,
void* buffer,
size_t bytes)
{
size_t count = bytes;
while (count > 0) {
DWORD step = 0;
if ((! WriteFile(file->handle, buffer, (DWORD) min(count, (size_t) 0x2000000), &step, NULL)) || step == 0) {
WriteErrorMessage("WriteLargeFile failed at %lu of %lu bytes with 0x%x\n", bytes - count, bytes, GetLastError());
return bytes - count;
}
count -= step;
buffer = ((char*) buffer) + step;
}
return bytes;
}
size_t
ReadLargeFile(
LargeFileHandle* file,
void* buffer,
size_t bytes)
{
size_t count = bytes;
while (count > 0) {
DWORD step = 0;
if ((! ReadFile(file->handle, buffer, (DWORD) min(count, (size_t) 0x1000000), &step, NULL)) || step == 0) {
WriteErrorMessage("ReadLargeFile failed at %lu of %lu bytes with 0x%x\n", bytes - count, bytes, GetLastError());
return bytes - count;
}
count -= step;
buffer = ((char*) buffer) + step;
}
return bytes;
}
void
CloseLargeFile(
LargeFileHandle* file)
{
if (CloseHandle(file->handle)) {
delete (void*) file;
}
}
class MemoryMappedFile
{
public:
HANDLE fileHandle;
HANDLE fileMapping;
void* mappedAddress;
};
MemoryMappedFile*
OpenMemoryMappedFile(
const char* filename,
size_t offset,
size_t length,
void** o_contents,
bool write,
bool sequential)
{
MemoryMappedFile* result = new MemoryMappedFile();
result->fileHandle = CreateFile(filename, (write ? GENERIC_WRITE : 0) | GENERIC_READ, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | (sequential ? FILE_FLAG_SEQUENTIAL_SCAN : FILE_FLAG_RANDOM_ACCESS), NULL);
if (result->fileHandle == NULL) {
WriteErrorMessage("unable to open mapped file %s error 0x%x\n", filename, GetLastError());
delete result;
return NULL;
}
result->fileMapping = CreateFileMapping(result->fileHandle, NULL, write ? PAGE_READWRITE : PAGE_READONLY, 0, 0, NULL);
if (result->fileMapping == NULL) {
WriteErrorMessage("unable to create file mapping %s error 0x%x\n", filename, GetLastError());
delete result;
return NULL;
}
*o_contents = result->mappedAddress = MapViewOfFile(result->fileMapping,
write ? FILE_MAP_WRITE : FILE_MAP_READ,
(DWORD) (offset >> (8 * sizeof(DWORD))),
(DWORD) offset,
length);
if (*o_contents == NULL) {
WriteErrorMessage("unable to map file %s error 0x%x\n", filename, GetLastError());
delete result;
return NULL;
}
return result;
}
void
CloseMemoryMappedFile(
MemoryMappedFile* mappedFile)
{
bool ok = UnmapViewOfFile(mappedFile->mappedAddress) &&
CloseHandle(mappedFile->fileMapping) &&
CloseHandle(mappedFile->fileHandle);
if (ok) {
delete (void*) mappedFile;
} else {
WriteErrorMessage("unable to close memory mapped file, error 0x%x\n", GetLastError());
}
}
class WindowsAsyncFile : public AsyncFile
{
public:
static WindowsAsyncFile* open(const char* filename, bool write);
WindowsAsyncFile(HANDLE i_hFile);
virtual bool close();
class Writer : public AsyncFile::Writer
{
public:
Writer(WindowsAsyncFile* i_file);
virtual bool close();
virtual bool beginWrite(void* buffer, size_t length, size_t offset, size_t *bytesWritten);
virtual bool waitForCompletion();
private:
WindowsAsyncFile* file;
bool writing;
OVERLAPPED lap;
};
virtual AsyncFile::Writer* getWriter();
class Reader : public AsyncFile::Reader
{
public:
Reader(WindowsAsyncFile* i_file);
virtual bool close();
virtual bool beginRead(void* buffer, size_t length, size_t offset, size_t *bytesRead);
virtual bool waitForCompletion();
private:
WindowsAsyncFile* file;
bool reading;
OVERLAPPED lap;
};
virtual AsyncFile::Reader* getReader();
private:
HANDLE hFile;
};
WindowsAsyncFile*
WindowsAsyncFile::open(
const char* filename,
bool write)
{
HANDLE hFile = CreateFile(filename,
GENERIC_READ | (write ? GENERIC_WRITE : 0),
write ? 0 : FILE_SHARE_READ,
NULL,
write ? CREATE_ALWAYS : OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (INVALID_HANDLE_VALUE == hFile) {
WriteErrorMessage("Unable to create SAM file '%s', %d\n",filename,GetLastError());
return NULL;
}
return new WindowsAsyncFile(hFile);
}
WindowsAsyncFile::WindowsAsyncFile(
HANDLE i_hFile)
: hFile(i_hFile)
{
}
bool
WindowsAsyncFile::close()
{
return CloseHandle(hFile) ? true : false;
}
AsyncFile::Writer*
WindowsAsyncFile::getWriter()
{
return new Writer(this);
}
WindowsAsyncFile::Writer::Writer(WindowsAsyncFile* i_file)
: file(i_file), writing(false)
{
lap.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
}
bool
WindowsAsyncFile::Writer::close()
{
waitForCompletion();
return CloseHandle(lap.hEvent) ? true : false;
}
bool
WindowsAsyncFile::Writer::beginWrite(
void* buffer,
size_t length,
size_t offset,
size_t *bytesWritten)
{
if (! waitForCompletion()) {
return false;
}
lap.OffsetHigh = (DWORD) (offset >> (8 * sizeof(DWORD)));
lap.Offset = (DWORD) offset;
if (!WriteFile(file->hFile,buffer, (DWORD) length, (LPDWORD) bytesWritten, &lap)) {
if (ERROR_IO_PENDING != GetLastError()) {
WriteErrorMessage("WindowsAsyncFile: WriteFile failed, %d\n",GetLastError());
return false;
}
}
writing = true;
return true;
}
bool
WindowsAsyncFile::Writer::waitForCompletion()
{
if (writing) {
DWORD nBytesTransferred;
if (!GetOverlappedResult(file->hFile,&lap,&nBytesTransferred,TRUE)) {
return false;
}
writing = false;
}
return true;
}
AsyncFile::Reader*
WindowsAsyncFile::getReader()
{
return new Reader(this);
}
WindowsAsyncFile::Reader::Reader(
WindowsAsyncFile* i_file)
: file(i_file), reading(false)
{
lap.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
}
bool
WindowsAsyncFile::Reader::close()
{
return CloseHandle(lap.hEvent) ? true : false;
}
bool
WindowsAsyncFile::Reader::beginRead(
void* buffer,
size_t length,
size_t offset,
size_t* bytesRead)
{
if (! waitForCompletion()) {
return false;
}
lap.OffsetHigh = (DWORD) (offset >> (8 * sizeof(DWORD)));
lap.Offset = (DWORD) offset;
if (!ReadFile(file->hFile, buffer,(DWORD) length, (LPDWORD) bytesRead, &lap)) {
if (ERROR_IO_PENDING != GetLastError()) {
WriteErrorMessage("WindowsSAMWriter: WriteFile failed, %d\n",GetLastError());
return false;
}
}
reading = true;
return true;
}
bool
WindowsAsyncFile::Reader::waitForCompletion()
{
if (reading) {
DWORD nBytesTransferred;
if (!GetOverlappedResult(file->hFile,&lap,&nBytesTransferred,TRUE)) {
return false;
}
reading = false;
}
return true;
}
_int64 InterlockedAdd64AndReturnNewValue(volatile _int64 *valueToWhichToAdd, _int64 amountToAdd)
{
return InterlockedAdd64((volatile LONGLONG *)valueToWhichToAdd,(LONGLONG)amountToAdd);
}
int _fseek64bit(FILE *stream, _int64 offset, int origin)
{
return _fseeki64(stream,offset,origin);
}
int getpagesize()
{
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
return systemInfo.dwAllocationGranularity;
}
FileMapper::FileMapper()
{
hFile = INVALID_HANDLE_VALUE;
hMapping = NULL;
initialized = false;
pagesize = getpagesize();
mapCount = 0;
#if 0
hFilePrefetch = INVALID_HANDLE_VALUE;
lap->hEvent = NULL;
prefetchBuffer = BigAlloc(prefetchBufferSize);
isPrefetchOutstanding = false;
lastPrefetch = 0;
#endif
millisSpentInReadFile = 0;
countOfImmediateCompletions = 0;
countOfDelayedCompletions = 0;
countOfFailures = 0;
}
bool
FileMapper::init(const char *i_fileName)
{
if (initialized) {
if (strcmp(fileName, i_fileName)) {
WriteErrorMessage("FileMapper already initialized with %s, cannot init with %s\n", fileName, i_fileName);
return false;
}
return true;
}
fileName = i_fileName;
hFile = CreateFile(fileName, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
if (INVALID_HANDLE_VALUE == hFile) {
WriteErrorMessage("Failed to open '%s', error %d\n",fileName, GetLastError());
return false;
}
#if 0
hFilePrefetch = CreateFile(fileName, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
if (INVALID_HANDLE_VALUE == hFilePrefetch) {
WriteErrorMessage("Failed to open '%s' for prefetch, error %d\n",fileName, GetLastError());
CloseHandle(hFile);
return false;
}
#endif
BY_HANDLE_FILE_INFORMATION fileInfo;
if (!GetFileInformationByHandle(hFile,&fileInfo)) {
WriteErrorMessage("Unable to get file information for '%s', error %d\n", fileName, GetLastError());
CloseHandle(hFile);
#if 0
CloseHandle(hFilePrefetch);
#endif
return false;
}
LARGE_INTEGER liFileSize;
liFileSize.HighPart = fileInfo.nFileSizeHigh;
liFileSize.LowPart = fileInfo.nFileSizeLow;
fileSize = liFileSize.QuadPart;
hMapping = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL);
if (NULL == hMapping) {
WriteErrorMessage("Unable to create mapping to file '%s', %d\n", fileName, GetLastError());
CloseHandle(hFile);
#if 0
CloseHandle(hFilePrefetch);
#endif
return false;
}
#if 0
lap->hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
#endif
initialized = true;
return true;
}
char *
FileMapper::createMapping(size_t offset, size_t amountToMap, void** o_mappedBase)
{
size_t beginRounding = offset % pagesize;
LARGE_INTEGER liStartingOffset;
liStartingOffset.QuadPart = offset - beginRounding;
size_t endRounding = 0;
if ((amountToMap + beginRounding) % pagesize != 0) {
endRounding = pagesize - (amountToMap + beginRounding) % pagesize;
}
size_t mapRequestSize = beginRounding + amountToMap + endRounding;
_ASSERT(mapRequestSize % pagesize == 0);
if (mapRequestSize + liStartingOffset.QuadPart >= fileSize) {
mapRequestSize = 0; // Says to just map the whole thing.
}
char* mappedBase = (char *)MapViewOfFile(hMapping,FILE_MAP_READ,liStartingOffset.HighPart,liStartingOffset.LowPart, mapRequestSize);
if (NULL == mappedBase) {
WriteErrorMessage("Unable to map file, %d\n", GetLastError());
return NULL;
}
char* mappedRegion = mappedBase + beginRounding;
#if 0
prefetch(0);
#endif
InterlockedIncrementAndReturnNewValue(&mapCount);
*o_mappedBase = mappedBase;
return mappedRegion;
}
void
FileMapper::unmap(void* mappedBase)
{
_ASSERT(mapCount > 0);
if (mapCount > 0) {
int n = InterlockedDecrementAndReturnNewValue(&mapCount);
_ASSERT(n >= 0);
if (!UnmapViewOfFile(mappedBase)) {
WriteErrorMessage("Unmap of file failed, %d\n", GetLastError());
}
}
}
FileMapper::~FileMapper()
{
_ASSERT(mapCount == 0);
#if 0
if (isPrefetchOutstanding) {
DWORD numberOfBytesTransferred;
GetOverlappedResult(hFile,lap,&numberOfBytesTransferred,TRUE);
}
BigDealloc(prefetchBuffer);
prefetchBuffer = NULL;
CloseHandle(hFilePrefetch);
CloseHandle(lap->hEvent);
#endif
CloseHandle(hMapping);
CloseHandle(hFile);
WriteErrorMessage("FileMapper: %lld immediate completions, %lld delayed completions, %lld failures, %lld ms in readfile (%lld ms/call)\n",countOfImmediateCompletions, countOfDelayedCompletions, countOfFailures, millisSpentInReadFile,
millisSpentInReadFile/max(1, countOfImmediateCompletions + countOfDelayedCompletions + countOfFailures));
}
#if 0
void
FileMapper::prefetch(size_t currentRead)
{
if (currentRead + prefetchBufferSize / 2 <= lastPrefetch || lastPrefetch + prefetchBufferSize >= amountMapped) {
//
// Nothing to do; we're either not ready for more prefetching or we're at the end of our region.
//
return;
}
if (isPrefetchOutstanding) {
//
// See if the last prefetch is done.
//
DWORD numberOfBytesTransferred;
if (GetOverlappedResult(hFile,lap,&numberOfBytesTransferred,FALSE)) {
isPrefetchOutstanding = false;
} else {
#if DBG
if (GetLastError() != ERROR_IO_PENDING) {
WriteErrorMessage("mapped file prefetcher: GetOverlappedResult failed, %d\n", GetLastError());
}
#endif // DBG
return; // There's still IO on outstanding, we can't start more.
}
}
DWORD amountToRead = (DWORD)__min(prefetchBufferSize, amountMapped - lastPrefetch);
_ASSERT(amountToRead > 0); // Else we should have failed the initial check and returned
LARGE_INTEGER liReadOffset;
lastPrefetch += prefetchBufferSize;
liReadOffset.QuadPart = lastPrefetch;
lap->OffsetHigh = liReadOffset.HighPart;
lap->Offset = liReadOffset.LowPart;
DWORD nBytesRead;
_int64 start = timeInMillis();
if (!ReadFile(hFilePrefetch,prefetchBuffer,amountToRead,&nBytesRead,lap)) {
if (GetLastError() == ERROR_IO_PENDING) {
InterlockedAdd64AndReturnNewValue(&countOfDelayedCompletions,1);
isPrefetchOutstanding = true;
} else {
InterlockedAdd64AndReturnNewValue(&countOfFailures,1);
#if DBG
if (GetLastError() != ERROR_IO_PENDING) {
WriteErrorMessage("mapped file prefetcher: ReadFile failed, %d\n", GetLastError());
}
#endif // DBG
isPrefetchOutstanding = false; // Just ignore it
}
} else {
InterlockedAdd64AndReturnNewValue(&countOfImmediateCompletions,1);
isPrefetchOutstanding = false;
}
InterlockedAdd64AndReturnNewValue(&millisSpentInReadFile,timeInMillis() - start);
}
#endif
void PreventMachineHibernationWhileThisThreadIsAlive()
{
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
}
#else // _MSC_VER
#if defined(__MACH__)
#include <mach/clock.h>
#include <mach/mach.h>
#endif
_int64 timeInMillis()
/**
* Get the current time in milliseconds since some arbitrary starting point
* (e.g. system boot or epoch)
*/
{
timeval t;
gettimeofday(&t, NULL);
return ((_int64) t.tv_sec) * 1000 + ((_int64) t.tv_usec) / 1000;
}
_int64 timeInNanos()
{
timespec ts;
#if defined(__linux__)
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
#elif defined(__MACH__)
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
#else
#error "Don't know how to get time in nanos on your platform"
#endif
return ((_int64) ts.tv_sec) * 1000000000 + (_int64) ts.tv_nsec;
}
void AcquireUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
pthread_mutex_lock(lock);
}
void ReleaseUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
pthread_mutex_unlock(lock);
}
bool InitializeUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
return pthread_mutex_init(lock, NULL) == 0;
}
bool DestroyUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
return pthread_mutex_destroy(lock) == 0;
}
class SingleWaiterObjectImpl {
protected:
pthread_mutex_t lock;
pthread_cond_t cond;
bool set;
public:
bool init() {
if (pthread_mutex_init(&lock, NULL) != 0) {
return false;
}
if (pthread_cond_init(&cond, NULL) != 0) {
pthread_mutex_destroy(&lock);
return false;
}
set = false;
return true;
}
void signal() {
pthread_mutex_lock(&lock);
set = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
void wait() {
pthread_mutex_lock(&lock);
while (!set) {
pthread_cond_wait(&cond, &lock);
}
pthread_mutex_unlock(&lock);
}
bool waitWithTimeout(_int64 timeoutInMillis) {
struct timespec wakeTime;
#ifdef __LINUX__
clock_gettime(CLOCK_REALTIME, &wakeTime);
wakeTime.tv_nsec += timeoutInMillis * 1000000;
#elif defined(__MACH__)
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
wakeTime.tv_nsec = mts.tv_nsec + timeoutInMillis * 1000000;
wakeTime.tv_sec = mts.tv_sec;
#endif
wakeTime.tv_sec += wakeTime.tv_nsec / 1000000000;
wakeTime.tv_nsec = wakeTime.tv_nsec % 1000000000;
bool timedOut = false;
pthread_mutex_lock(&lock);
while (!set) {
int retVal = pthread_cond_timedwait(&cond, &lock, &wakeTime);