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