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