appveyor: minor refactoring, clarifications
[fio.git] / os / windows / posix.c
CommitLineData
9277ec14
BC
1/* This file contains functions which implement those POSIX and Linux functions
2 * that MinGW and Microsoft don't provide. The implementations contain just enough
3 * functionality to support fio.
4 */
5
6#include <arpa/inet.h>
7#include <netinet/in.h>
8#include <windows.h>
9#include <stddef.h>
ad9c0fbc 10#include <string.h>
9277ec14
BC
11#include <stdlib.h>
12#include <unistd.h>
13#include <dirent.h>
14#include <pthread.h>
f16b7405 15#include <time.h>
9277ec14
BC
16#include <semaphore.h>
17#include <sys/shm.h>
18#include <sys/mman.h>
19#include <sys/uio.h>
20#include <sys/resource.h>
21#include <sys/poll.h>
70a61165
BC
22#include <sys/wait.h>
23#include <setjmp.h>
9277ec14
BC
24
25#include "../os-windows.h"
671b0600 26#include "../../lib/hweight.h"
9277ec14 27
8b6a404c
VF
28extern unsigned long mtime_since_now(struct timespec *);
29extern void fio_gettime(struct timespec *, void *);
21c75387 30
ad9c0fbc
BC
31/* These aren't defined in the MinGW headers */
32HRESULT WINAPI StringCchCopyA(
33 char *pszDest,
34 size_t cchDest,
35 const char *pszSrc);
36
37HRESULT WINAPI StringCchPrintfA(
38 char *pszDest,
39 size_t cchDest,
40 const char *pszFormat,
41 ...);
42
10a6b3c6
BC
43int win_to_posix_error(DWORD winerr)
44{
45 switch (winerr)
46 {
47 case ERROR_FILE_NOT_FOUND: return ENOENT;
48 case ERROR_PATH_NOT_FOUND: return ENOENT;
49 case ERROR_ACCESS_DENIED: return EACCES;
50 case ERROR_INVALID_HANDLE: return EBADF;
51 case ERROR_NOT_ENOUGH_MEMORY: return ENOMEM;
52 case ERROR_INVALID_DATA: return EINVAL;
53 case ERROR_OUTOFMEMORY: return ENOMEM;
54 case ERROR_INVALID_DRIVE: return ENODEV;
55 case ERROR_NOT_SAME_DEVICE: return EXDEV;
56 case ERROR_WRITE_PROTECT: return EROFS;
57 case ERROR_BAD_UNIT: return ENODEV;
58 case ERROR_SHARING_VIOLATION: return EACCES;
59 case ERROR_LOCK_VIOLATION: return EACCES;
60 case ERROR_SHARING_BUFFER_EXCEEDED: return ENOLCK;
61 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
62 case ERROR_NOT_SUPPORTED: return ENOSYS;
63 case ERROR_FILE_EXISTS: return EEXIST;
64 case ERROR_CANNOT_MAKE: return EPERM;
65 case ERROR_INVALID_PARAMETER: return EINVAL;
66 case ERROR_NO_PROC_SLOTS: return EAGAIN;
67 case ERROR_BROKEN_PIPE: return EPIPE;
68 case ERROR_OPEN_FAILED: return EIO;
69 case ERROR_NO_MORE_SEARCH_HANDLES: return ENFILE;
70 case ERROR_CALL_NOT_IMPLEMENTED: return ENOSYS;
71 case ERROR_INVALID_NAME: return ENOENT;
72 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
73 case ERROR_CHILD_NOT_COMPLETE: return EBUSY;
74 case ERROR_DIR_NOT_EMPTY: return ENOTEMPTY;
75 case ERROR_SIGNAL_REFUSED: return EIO;
76 case ERROR_BAD_PATHNAME: return ENOENT;
77 case ERROR_SIGNAL_PENDING: return EBUSY;
78 case ERROR_MAX_THRDS_REACHED: return EAGAIN;
79 case ERROR_BUSY: return EBUSY;
80 case ERROR_ALREADY_EXISTS: return EEXIST;
81 case ERROR_NO_SIGNAL_SENT: return EIO;
82 case ERROR_FILENAME_EXCED_RANGE: return EINVAL;
83 case ERROR_META_EXPANSION_TOO_LONG: return EINVAL;
84 case ERROR_INVALID_SIGNAL_NUMBER: return EINVAL;
85 case ERROR_THREAD_1_INACTIVE: return EINVAL;
86 case ERROR_BAD_PIPE: return EINVAL;
87 case ERROR_PIPE_BUSY: return EBUSY;
88 case ERROR_NO_DATA: return EPIPE;
89 case ERROR_MORE_DATA: return EAGAIN;
90 case ERROR_DIRECTORY: return ENOTDIR;
91 case ERROR_PIPE_CONNECTED: return EBUSY;
92 case ERROR_NO_TOKEN: return EINVAL;
93 case ERROR_PROCESS_ABORTED: return EFAULT;
94 case ERROR_BAD_DEVICE: return ENODEV;
95 case ERROR_BAD_USERNAME: return EINVAL;
96 case ERROR_OPEN_FILES: return EAGAIN;
97 case ERROR_ACTIVE_CONNECTIONS: return EAGAIN;
98 case ERROR_DEVICE_IN_USE: return EAGAIN;
99 case ERROR_INVALID_AT_INTERRUPT_TIME: return EINTR;
100 case ERROR_IO_DEVICE: return EIO;
101 case ERROR_NOT_OWNER: return EPERM;
102 case ERROR_END_OF_MEDIA: return ENOSPC;
103 case ERROR_EOM_OVERFLOW: return ENOSPC;
104 case ERROR_BEGINNING_OF_MEDIA: return ESPIPE;
105 case ERROR_SETMARK_DETECTED: return ESPIPE;
106 case ERROR_NO_DATA_DETECTED: return ENOSPC;
107 case ERROR_POSSIBLE_DEADLOCK: return EDEADLOCK;
108 case ERROR_CRC: return EIO;
109 case ERROR_NEGATIVE_SEEK: return EINVAL;
110 case ERROR_DISK_FULL: return ENOSPC;
111 case ERROR_NOACCESS: return EFAULT;
112 case ERROR_FILE_INVALID: return ENXIO;
113 }
114
115 return winerr;
116}
117
671b0600
BC
118int GetNumLogicalProcessors(void)
119{
120 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *processor_info = NULL;
121 DWORD len = 0;
122 DWORD num_processors = 0;
123 DWORD error = 0;
124 DWORD i;
125
126 while (!GetLogicalProcessorInformation(processor_info, &len)) {
127 error = GetLastError();
128 if (error == ERROR_INSUFFICIENT_BUFFER)
129 processor_info = malloc(len);
130 else {
131 log_err("Error: GetLogicalProcessorInformation failed: %d\n", error);
132 return -1;
133 }
134
135 if (processor_info == NULL) {
136 log_err("Error: failed to allocate memory for GetLogicalProcessorInformation");
137 return -1;
138 }
139 }
140
141 for (i = 0; i < len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); i++)
142 {
143 if (processor_info[i].Relationship == RelationProcessorCore)
4ee47af0 144 num_processors += hweight64(processor_info[i].ProcessorMask);
671b0600
BC
145 }
146
147 free(processor_info);
148 return num_processors;
149}
150
9277ec14
BC
151long sysconf(int name)
152{
671b0600 153 long val = -1;
01d26955 154 long val2 = -1;
9277ec14
BC
155 SYSTEM_INFO sysInfo;
156 MEMORYSTATUSEX status;
157
158 switch (name)
159 {
160 case _SC_NPROCESSORS_ONLN:
671b0600
BC
161 val = GetNumLogicalProcessors();
162 if (val == -1)
01d26955 163 log_err("sysconf(_SC_NPROCESSORS_ONLN) failed\n");
671b0600 164
9277ec14
BC
165 break;
166
167 case _SC_PAGESIZE:
168 GetSystemInfo(&sysInfo);
169 val = sysInfo.dwPageSize;
170 break;
171
172 case _SC_PHYS_PAGES:
173 status.dwLength = sizeof(status);
01d26955
BC
174 val2 = sysconf(_SC_PAGESIZE);
175 if (GlobalMemoryStatusEx(&status) && val2 != -1)
176 val = status.ullTotalPhys / val2;
177 else
178 log_err("sysconf(_SC_PHYS_PAGES) failed\n");
9277ec14
BC
179 break;
180 default:
181 log_err("sysconf(%d) is not implemented\n", name);
182 break;
183 }
184
185 return val;
186}
187
188char *dl_error = NULL;
189
190int dlclose(void *handle)
191{
192 return !FreeLibrary((HMODULE)handle);
193}
194
195void *dlopen(const char *file, int mode)
196{
197 HMODULE hMod;
198
199 hMod = LoadLibrary(file);
200 if (hMod == INVALID_HANDLE_VALUE)
201 dl_error = (char*)"LoadLibrary failed";
202 else
203 dl_error = NULL;
204
205 return hMod;
206}
207
208void *dlsym(void *handle, const char *name)
209{
210 FARPROC fnPtr;
211
212 fnPtr = GetProcAddress((HMODULE)handle, name);
213 if (fnPtr == NULL)
214 dl_error = (char*)"GetProcAddress failed";
215 else
216 dl_error = NULL;
217
218 return fnPtr;
219}
220
221char *dlerror(void)
222{
223 return dl_error;
224}
225
ba55bfa9
BC
226/* Copied from http://blogs.msdn.com/b/joshpoley/archive/2007/12/19/date-time-formats-and-conversions.aspx */
227void Time_tToSystemTime(time_t dosTime, SYSTEMTIME *systemTime)
228{
5de1ade5
JS
229 FILETIME utcFT;
230 LONGLONG jan1970;
7ff0297f 231 SYSTEMTIME tempSystemTime;
5de1ade5
JS
232
233 jan1970 = Int32x32To64(dosTime, 10000000) + 116444736000000000;
234 utcFT.dwLowDateTime = (DWORD)jan1970;
235 utcFT.dwHighDateTime = jan1970 >> 32;
ba55bfa9 236
7ff0297f
JF
237 FileTimeToSystemTime((FILETIME*)&utcFT, &tempSystemTime);
238 SystemTimeToTzSpecificLocalTime(NULL, &tempSystemTime, systemTime);
ba55bfa9
BC
239}
240
241char* ctime_r(const time_t *t, char *buf)
242{
243 SYSTEMTIME systime;
15a0c8ee 244 const char * const dayOfWeek[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
ba55bfa9
BC
245 const char * const monthOfYear[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
246
247 Time_tToSystemTime(*t, &systime);
248 /* We don't know how long `buf` is, but assume it's rounded up from the minimum of 25 to 32 */
1f086b55 249 StringCchPrintfA(buf, 31, "%s %s %d %02d:%02d:%02d %04d\n", dayOfWeek[systime.wDayOfWeek % 7], monthOfYear[(systime.wMonth - 1) % 12],
ba55bfa9
BC
250 systime.wDay, systime.wHour, systime.wMinute, systime.wSecond, systime.wYear);
251 return buf;
252}
253
9277ec14
BC
254int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
255{
256 FILETIME fileTime;
9576f613
BC
257 uint64_t unix_time, windows_time;
258 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
9277ec14 259
fc0b830f 260 /* Ignore the timezone parameter */
9277ec14
BC
261 (void)tzp;
262
263 /*
264 * Windows time is stored as the number 100 ns intervals since January 1 1601.
265 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
266 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
267 */
268 GetSystemTimeAsFileTime(&fileTime);
9576f613 269 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
9277ec14
BC
270 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
271 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
272 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
273 tp->tv_sec = unix_time / 1000;
274 tp->tv_usec = (unix_time % 1000) * 1000;
275 return 0;
276}
277
9277ec14
BC
278int sigaction(int sig, const struct sigaction *act,
279 struct sigaction *oact)
280{
e5b8f91c
BC
281 int rc = 0;
282 void (*prev_handler)(int);
283
284 prev_handler = signal(sig, act->sa_handler);
285 if (oact != NULL)
286 oact->sa_handler = prev_handler;
287
288 if (prev_handler == SIG_ERR)
289 rc = -1;
290
291 return rc;
9277ec14
BC
292}
293
294int lstat(const char * path, struct stat * buf)
295{
296 return stat(path, buf);
297}
298
299void *mmap(void *addr, size_t len, int prot, int flags,
300 int fildes, off_t off)
301{
302 DWORD vaProt = 0;
06cbb3c7
RC
303 DWORD mapAccess = 0;
304 DWORD lenlow;
305 DWORD lenhigh;
306 HANDLE hMap;
9277ec14
BC
307 void* allocAddr = NULL;
308
309 if (prot & PROT_NONE)
310 vaProt |= PAGE_NOACCESS;
311
06cbb3c7 312 if ((prot & PROT_READ) && !(prot & PROT_WRITE)) {
9277ec14 313 vaProt |= PAGE_READONLY;
06cbb3c7
RC
314 mapAccess = FILE_MAP_READ;
315 }
9277ec14 316
06cbb3c7 317 if (prot & PROT_WRITE) {
9277ec14 318 vaProt |= PAGE_READWRITE;
06cbb3c7
RC
319 mapAccess |= FILE_MAP_WRITE;
320 }
321
322 lenlow = len & 0xFFFF;
323 lenhigh = len >> 16;
324 /* If the low DWORD is zero and the high DWORD is non-zero, `CreateFileMapping`
325 will return ERROR_INVALID_PARAMETER. To avoid this, set both to zero. */
326 if (lenlow == 0) {
327 lenhigh = 0;
328 }
9277ec14 329
06cbb3c7 330 if (flags & MAP_ANON || flags & MAP_ANONYMOUS)
9277ec14
BC
331 {
332 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
10a6b3c6
BC
333 if (allocAddr == NULL)
334 errno = win_to_posix_error(GetLastError());
9277ec14 335 }
06cbb3c7
RC
336 else
337 {
338 hMap = CreateFileMapping((HANDLE)_get_osfhandle(fildes), NULL, vaProt, lenhigh, lenlow, NULL);
339
340 if (hMap != NULL)
341 {
342 allocAddr = MapViewOfFile(hMap, mapAccess, off >> 16, off & 0xFFFF, len);
343 }
344
345 if (hMap == NULL || allocAddr == NULL)
346 errno = win_to_posix_error(GetLastError());
347
348 }
9277ec14
BC
349
350 return allocAddr;
351}
352
353int munmap(void *addr, size_t len)
354{
06cbb3c7
RC
355 BOOL success;
356
357 /* We may have allocated the memory with either MapViewOfFile or
358 VirtualAlloc. Therefore, try calling UnmapViewOfFile first, and if that
359 fails, call VirtualFree. */
360 success = UnmapViewOfFile(addr);
361
362 if (!success)
363 {
364 success = VirtualFree(addr, 0, MEM_RELEASE);
10a6b3c6
BC
365 }
366
06cbb3c7
RC
367 return !success;
368}
369
370int msync(void *addr, size_t len, int flags)
371{
372 return !FlushViewOfFile(addr, len);
9277ec14
BC
373}
374
375int fork(void)
376{
377 log_err("%s is not implemented\n", __func__);
378 errno = ENOSYS;
10a6b3c6 379 return -1;
9277ec14
BC
380}
381
382pid_t setsid(void)
383{
384 log_err("%s is not implemented\n", __func__);
385 errno = ENOSYS;
10a6b3c6 386 return -1;
9277ec14
BC
387}
388
ad9c0fbc
BC
389static HANDLE log_file = INVALID_HANDLE_VALUE;
390
9277ec14
BC
391void openlog(const char *ident, int logopt, int facility)
392{
ad9c0fbc
BC
393 if (log_file == INVALID_HANDLE_VALUE)
394 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
9277ec14
BC
395}
396
397void closelog(void)
398{
ad9c0fbc
BC
399 CloseHandle(log_file);
400 log_file = INVALID_HANDLE_VALUE;
401}
402
403void syslog(int priority, const char *message, ... /* argument */)
404{
405 va_list v;
406 int len;
407 char *output;
408 DWORD bytes_written;
409
410 if (log_file == INVALID_HANDLE_VALUE) {
411 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
412 }
413
414 if (log_file == INVALID_HANDLE_VALUE) {
415 log_err("syslog: failed to open log file\n");
416 return;
417 }
418
419 va_start(v, message);
420 len = _vscprintf(message, v);
421 output = malloc(len + sizeof(char));
98dc2db5 422 vsprintf(output, message, v);
ad9c0fbc
BC
423 WriteFile(log_file, output, len, &bytes_written, NULL);
424 va_end(v);
98dc2db5 425 free(output);
9277ec14
BC
426}
427
428int kill(pid_t pid, int sig)
429{
430 errno = ESRCH;
10a6b3c6 431 return -1;
9277ec14
BC
432}
433
fc0b830f
BC
434/*
435 * This is assumed to be used only by the network code,
436 * and so doesn't try and handle any of the other cases
437 */
9277ec14
BC
438int fcntl(int fildes, int cmd, ...)
439{
fc0b830f
BC
440 /*
441 * non-blocking mode doesn't work the same as in BSD sockets,
442 * so ignore it.
443 */
9277ec14
BC
444#if 0
445 va_list ap;
446 int val, opt, status;
447
448 if (cmd == F_GETFL)
449 return 0;
450 else if (cmd != F_SETFL) {
451 errno = EINVAL;
10a6b3c6 452 return -1;
9277ec14
BC
453 }
454
455 va_start(ap, 1);
456
457 opt = va_arg(ap, int);
458 if (opt & O_NONBLOCK)
459 val = 1;
460 else
461 val = 0;
462
463 status = ioctlsocket((SOCKET)fildes, opt, &val);
464
465 if (status == SOCKET_ERROR) {
466 errno = EINVAL;
467 val = -1;
468 }
469
470 va_end(ap);
471
472 return val;
473#endif
474return 0;
475}
476
477/*
478 * Get the value of a local clock source.
479 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
480 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
481 */
482int clock_gettime(clockid_t clock_id, struct timespec *tp)
483{
484 int rc = 0;
485
486 if (clock_id == CLOCK_MONOTONIC)
487 {
488 static LARGE_INTEGER freq = {{0,0}};
489 LARGE_INTEGER counts;
5aa23eb8 490 uint64_t t;
9277ec14
BC
491
492 QueryPerformanceCounter(&counts);
493 if (freq.QuadPart == 0)
494 QueryPerformanceFrequency(&freq);
495
496 tp->tv_sec = counts.QuadPart / freq.QuadPart;
497 /* Get the difference between the number of ns stored
498 * in 'tv_sec' and that stored in 'counts' */
5aa23eb8 499 t = tp->tv_sec * freq.QuadPart;
9277ec14
BC
500 t = counts.QuadPart - t;
501 /* 't' now contains the number of cycles since the last second.
502 * We want the number of nanoseconds, so multiply out by 1,000,000,000
503 * and then divide by the frequency. */
504 t *= 1000000000;
505 tp->tv_nsec = t / freq.QuadPart;
506 }
507 else if (clock_id == CLOCK_REALTIME)
508 {
509 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
510 * higher-precision field. */
511 struct timeval tv;
512 gettimeofday(&tv, NULL);
513 tp->tv_sec = tv.tv_sec;
514 tp->tv_nsec = tv.tv_usec * 1000;
515 } else {
516 errno = EINVAL;
517 rc = -1;
518 }
519
520 return rc;
521}
522
523int mlock(const void * addr, size_t len)
524{
10a6b3c6
BC
525 SIZE_T min, max;
526 BOOL success;
527 HANDLE process = GetCurrentProcess();
528
529 success = GetProcessWorkingSetSize(process, &min, &max);
530 if (!success) {
531 errno = win_to_posix_error(GetLastError());
532 return -1;
533 }
534
535 min += len;
536 max += len;
537 success = SetProcessWorkingSetSize(process, min, max);
538 if (!success) {
539 errno = win_to_posix_error(GetLastError());
540 return -1;
541 }
542
543 success = VirtualLock((LPVOID)addr, len);
544 if (!success) {
545 errno = win_to_posix_error(GetLastError());
546 return -1;
547 }
548
549 return 0;
9277ec14
BC
550}
551
552int munlock(const void * addr, size_t len)
553{
10a6b3c6
BC
554 BOOL success = VirtualUnlock((LPVOID)addr, len);
555 if (!success) {
556 errno = win_to_posix_error(GetLastError());
557 return -1;
558 }
559
560 return 0;
9277ec14
BC
561}
562
563pid_t waitpid(pid_t pid, int *stat_loc, int options)
564{
565 log_err("%s is not implemented\n", __func__);
566 errno = ENOSYS;
567 return -1;
568}
569
570int usleep(useconds_t useconds)
571{
572 Sleep(useconds / 1000);
573 return 0;
574}
575
576char *basename(char *path)
577{
578 static char name[MAX_PATH];
579 int i;
580
581 if (path == NULL || strlen(path) == 0)
582 return (char*)".";
583
584 i = strlen(path) - 1;
585
9576f613 586 while (path[i] != '\\' && path[i] != '/' && i >= 0)
9277ec14
BC
587 i--;
588
13a85be9
TK
589 name[MAX_PATH - 1] = '\0';
590 strncpy(name, path + i + 1, MAX_PATH - 1);
9277ec14
BC
591
592 return name;
593}
594
9277ec14
BC
595int fsync(int fildes)
596{
597 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
10a6b3c6
BC
598 if (!FlushFileBuffers(hFile)) {
599 errno = win_to_posix_error(GetLastError());
600 return -1;
601 }
602
603 return 0;
9277ec14
BC
604}
605
606int nFileMappings = 0;
607HANDLE fileMappings[1024];
608
609int shmget(key_t key, size_t size, int shmflg)
610{
611 int mapid = -1;
d3987946
BC
612 uint32_t size_low = size & 0xFFFFFFFF;
613 uint32_t size_high = ((uint64_t)size) >> 32;
614 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
9277ec14
BC
615 if (hMapping != NULL) {
616 fileMappings[nFileMappings] = hMapping;
617 mapid = nFileMappings;
618 nFileMappings++;
619 } else {
620 errno = ENOSYS;
621 }
622
623 return mapid;
624}
625
626void *shmat(int shmid, const void *shmaddr, int shmflg)
627{
628 void* mapAddr;
629 MEMORY_BASIC_INFORMATION memInfo;
630 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
10a6b3c6
BC
631 if (mapAddr == NULL) {
632 errno = win_to_posix_error(GetLastError());
633 return (void*)-1;
634 }
635
636 if (VirtualQuery(mapAddr, &memInfo, sizeof(memInfo)) == 0) {
637 errno = win_to_posix_error(GetLastError());
638 return (void*)-1;
639 }
640
9277ec14 641 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
10a6b3c6
BC
642 if (mapAddr == NULL) {
643 errno = win_to_posix_error(GetLastError());
644 return (void*)-1;
645 }
646
9277ec14
BC
647 return mapAddr;
648}
649
650int shmdt(const void *shmaddr)
651{
10a6b3c6
BC
652 if (!UnmapViewOfFile(shmaddr)) {
653 errno = win_to_posix_error(GetLastError());
654 return -1;
655 }
656
657 return 0;
9277ec14
BC
658}
659
660int shmctl(int shmid, int cmd, struct shmid_ds *buf)
661{
662 if (cmd == IPC_RMID) {
663 fileMappings[shmid] = INVALID_HANDLE_VALUE;
664 return 0;
665 } else {
666 log_err("%s is not implemented\n", __func__);
667 }
10a6b3c6
BC
668 errno = ENOSYS;
669 return -1;
9277ec14
BC
670}
671
672int setuid(uid_t uid)
673{
674 log_err("%s is not implemented\n", __func__);
675 errno = ENOSYS;
10a6b3c6 676 return -1;
9277ec14
BC
677}
678
679int setgid(gid_t gid)
680{
681 log_err("%s is not implemented\n", __func__);
682 errno = ENOSYS;
10a6b3c6 683 return -1;
9277ec14
BC
684}
685
686int nice(int incr)
687{
24a2bb13
BC
688 DWORD prioclass = NORMAL_PRIORITY_CLASS;
689
690 if (incr < -15)
691 prioclass = HIGH_PRIORITY_CLASS;
692 else if (incr < 0)
693 prioclass = ABOVE_NORMAL_PRIORITY_CLASS;
694 else if (incr > 15)
695 prioclass = IDLE_PRIORITY_CLASS;
696 else if (incr > 0)
697 prioclass = BELOW_NORMAL_PRIORITY_CLASS;
698
699 if (!SetPriorityClass(GetCurrentProcess(), prioclass))
700 log_err("fio: SetPriorityClass failed\n");
9277ec14
BC
701
702 return 0;
703}
704
705int getrusage(int who, struct rusage *r_usage)
706{
9576f613 707 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
9277ec14
BC
708 FILETIME cTime, eTime, kTime, uTime;
709 time_t time;
7732a09b 710 HANDLE h;
9277ec14
BC
711
712 memset(r_usage, 0, sizeof(*r_usage));
713
7732a09b
HL
714 if (who == RUSAGE_SELF) {
715 h = GetCurrentProcess();
716 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
717 } else if (who == RUSAGE_THREAD) {
718 h = GetCurrentThread();
719 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
720 } else {
721 log_err("fio: getrusage %d is not implemented\n", who);
722 return -1;
723 }
724
9576f613 725 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
9277ec14
BC
726 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
727 * 1601 to 1970 */
728 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
729 r_usage->ru_utime.tv_sec = time;
730 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
731 r_usage->ru_utime.tv_usec = 0;
9576f613 732 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
9277ec14
BC
733 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
734 * 1601 to 1970 */
735 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
736 r_usage->ru_stime.tv_sec = time;
737 r_usage->ru_stime.tv_usec = 0;
738 return 0;
739}
740
741int posix_madvise(void *addr, size_t len, int advice)
742{
9277ec14
BC
743 return ENOSYS;
744}
745
9277ec14
BC
746int fdatasync(int fildes)
747{
748 return fsync(fildes);
749}
750
751ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
752 off_t offset)
753{
9576f613
BC
754 int64_t pos = _telli64(fildes);
755 ssize_t len = _write(fildes, buf, nbyte);
756 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
757 return len;
758}
759
760ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
761{
9576f613 762 int64_t pos = _telli64(fildes);
9277ec14 763 ssize_t len = read(fildes, buf, nbyte);
9576f613 764 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
765 return len;
766}
767
768ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
769{
770 log_err("%s is not implemented\n", __func__);
771 errno = ENOSYS;
10a6b3c6 772 return -1;
9277ec14
BC
773}
774
775ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
776{
70a61165
BC
777 int i;
778 DWORD bytes_written = 0;
779 for (i = 0; i < iovcnt; i++)
780 {
781 int len = send((SOCKET)fildes, iov[i].iov_base, iov[i].iov_len, 0);
782 if (len == SOCKET_ERROR)
783 {
784 DWORD err = GetLastError();
785 errno = win_to_posix_error(err);
786 bytes_written = -1;
787 break;
788 }
789 bytes_written += len;
790 }
791
792 return bytes_written;
9277ec14
BC
793}
794
795long long strtoll(const char *restrict str, char **restrict endptr,
796 int base)
797{
798 return _strtoi64(str, endptr, base);
799}
800
9277ec14
BC
801int poll(struct pollfd fds[], nfds_t nfds, int timeout)
802{
803 struct timeval tv;
804 struct timeval *to = NULL;
805 fd_set readfds, writefds, exceptfds;
806 int i;
807 int rc;
808
3f457bea 809 if (timeout != -1) {
f9a58c2a 810 to = &tv;
3f457bea
BC
811 to->tv_sec = timeout / 1000;
812 to->tv_usec = (timeout % 1000) * 1000;
813 }
9277ec14
BC
814
815 FD_ZERO(&readfds);
816 FD_ZERO(&writefds);
817 FD_ZERO(&exceptfds);
818
819 for (i = 0; i < nfds; i++)
820 {
821 if (fds[i].fd < 0) {
822 fds[i].revents = 0;
823 continue;
824 }
825
826 if (fds[i].events & POLLIN)
827 FD_SET(fds[i].fd, &readfds);
828
829 if (fds[i].events & POLLOUT)
830 FD_SET(fds[i].fd, &writefds);
831
f9a58c2a 832 FD_SET(fds[i].fd, &exceptfds);
9277ec14 833 }
9277ec14
BC
834 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
835
836 if (rc != SOCKET_ERROR) {
837 for (i = 0; i < nfds; i++)
838 {
839 if (fds[i].fd < 0) {
840 continue;
841 }
842
843 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
844 fds[i].revents |= POLLIN;
845
846 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
847 fds[i].revents |= POLLOUT;
848
849 if (FD_ISSET(fds[i].fd, &exceptfds))
850 fds[i].revents |= POLLHUP;
851 }
852 }
9277ec14
BC
853 return rc;
854}
855
856int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
857{
8b6a404c 858 struct timespec tv;
21c75387
BC
859 DWORD ms_remaining;
860 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
861
862 if (ms_total == 0)
863 ms_total = 1;
864
865 ms_remaining = ms_total;
866
867 /* Since Sleep() can sleep for less than the requested time, add a loop to
868 ensure we only return after the requested length of time has elapsed */
869 do {
870 fio_gettime(&tv, NULL);
871 Sleep(ms_remaining);
872 ms_remaining = ms_total - mtime_since_now(&tv);
873 } while (ms_remaining > 0 && ms_remaining < ms_total);
874
875 /* this implementation will never sleep for less than the requested time */
876 if (rmtp != NULL) {
877 rmtp->tv_sec = 0;
878 rmtp->tv_nsec = 0;
879 }
880
881 return 0;
9277ec14
BC
882}
883
884DIR *opendir(const char *dirname)
885{
01d26955
BC
886 struct dirent_ctx *dc = NULL;
887
888 /* See if we can open it. If not, we'll return an error here */
889 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
890 if (file != INVALID_HANDLE_VALUE) {
891 CloseHandle(file);
892 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
893 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
894 dc->find_handle = INVALID_HANDLE_VALUE;
895 } else {
896 DWORD error = GetLastError();
897 if (error == ERROR_FILE_NOT_FOUND)
898 errno = ENOENT;
899
900 else if (error == ERROR_PATH_NOT_FOUND)
901 errno = ENOTDIR;
902 else if (error == ERROR_TOO_MANY_OPEN_FILES)
903 errno = ENFILE;
904 else if (error == ERROR_ACCESS_DENIED)
905 errno = EACCES;
906 else
907 errno = error;
908 }
909
910 return dc;
9277ec14
BC
911}
912
913int closedir(DIR *dirp)
914{
01d26955
BC
915 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
916 FindClose(dirp->find_handle);
ad9c0fbc 917
01d26955
BC
918 free(dirp);
919 return 0;
9277ec14
BC
920}
921
922struct dirent *readdir(DIR *dirp)
923{
ad9c0fbc
BC
924 static struct dirent de;
925 WIN32_FIND_DATA find_data;
926
927 if (dirp == NULL)
928 return NULL;
929
930 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
931 char search_pattern[MAX_PATH];
15a0c8ee 932 StringCchPrintfA(search_pattern, MAX_PATH-1, "%s\\*", dirp->dirname);
ad9c0fbc
BC
933 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
934 if (dirp->find_handle == INVALID_HANDLE_VALUE)
935 return NULL;
936 } else {
937 if (!FindNextFile(dirp->find_handle, &find_data))
938 return NULL;
939 }
940
941 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
942 de.d_ino = 0;
943
944 return &de;
9277ec14
BC
945}
946
947uid_t geteuid(void)
948{
949 log_err("%s is not implemented\n", __func__);
950 errno = ENOSYS;
951 return -1;
952}
953
f16b7405
BC
954in_addr_t inet_network(const char *cp)
955{
956 in_addr_t hbo;
957 in_addr_t nbo = inet_addr(cp);
958 hbo = ((nbo & 0xFF) << 24) + ((nbo & 0xFF00) << 8) + ((nbo & 0xFF0000) >> 8) + ((nbo & 0xFF000000) >> 24);
959 return hbo;
960}
961
9277ec14
BC
962const char* inet_ntop(int af, const void *restrict src,
963 char *restrict dst, socklen_t size)
964{
965 INT status = SOCKET_ERROR;
966 WSADATA wsd;
967 char *ret = NULL;
968
969 if (af != AF_INET && af != AF_INET6) {
970 errno = EAFNOSUPPORT;
971 return NULL;
972 }
973
974 WSAStartup(MAKEWORD(2,2), &wsd);
975
976 if (af == AF_INET) {
977 struct sockaddr_in si;
978 DWORD len = size;
979 memset(&si, 0, sizeof(si));
980 si.sin_family = af;
981 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
982 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
983 } else if (af == AF_INET6) {
984 struct sockaddr_in6 si6;
985 DWORD len = size;
986 memset(&si6, 0, sizeof(si6));
987 si6.sin6_family = af;
988 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
989 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
990 }
991
992 if (status != SOCKET_ERROR)
993 ret = dst;
994 else
995 errno = ENOSPC;
996
997 WSACleanup();
3f457bea 998
9277ec14
BC
999 return ret;
1000}
1001
1002int inet_pton(int af, const char *restrict src, void *restrict dst)
1003{
1004 INT status = SOCKET_ERROR;
1005 WSADATA wsd;
1006 int ret = 1;
1007
1008 if (af != AF_INET && af != AF_INET6) {
1009 errno = EAFNOSUPPORT;
1010 return -1;
1011 }
1012
1013 WSAStartup(MAKEWORD(2,2), &wsd);
1014
1015 if (af == AF_INET) {
1016 struct sockaddr_in si;
1017 INT len = sizeof(si);
1018 memset(&si, 0, sizeof(si));
1019 si.sin_family = af;
1020 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
1021 if (status != SOCKET_ERROR)
1022 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
1023 } else if (af == AF_INET6) {
1024 struct sockaddr_in6 si6;
1025 INT len = sizeof(si6);
1026 memset(&si6, 0, sizeof(si6));
1027 si6.sin6_family = af;
1028 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
1029 if (status != SOCKET_ERROR)
1030 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
1031 }
1032
1033 if (status == SOCKET_ERROR) {
1034 errno = ENOSPC;
1035 ret = 0;
1036 }
1037
1038 WSACleanup();
1039
1040 return ret;
1041}