Spelling and grammar fixes
[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 170 default:
4937100f 171 log_err("fio: windows error %lu not handled\n", winerr);
749dff99 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 {
4937100f
SW
191 log_err("Error: GetLogicalProcessorInformation failed: %lu\n",
192 error);
671b0600
BC
193 return -1;
194 }
195
196 if (processor_info == NULL) {
197 log_err("Error: failed to allocate memory for GetLogicalProcessorInformation");
198 return -1;
199 }
200 }
201
e8ed50bc 202 for (i = 0; i < len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); i++) {
671b0600 203 if (processor_info[i].Relationship == RelationProcessorCore)
4ee47af0 204 num_processors += hweight64(processor_info[i].ProcessorMask);
671b0600
BC
205 }
206
207 free(processor_info);
208 return num_processors;
209}
210
9277ec14
BC
211long sysconf(int name)
212{
671b0600 213 long val = -1;
01d26955 214 long val2 = -1;
9277ec14
BC
215 SYSTEM_INFO sysInfo;
216 MEMORYSTATUSEX status;
217
e8ed50bc 218 switch (name) {
9277ec14 219 case _SC_NPROCESSORS_ONLN:
671b0600
BC
220 val = GetNumLogicalProcessors();
221 if (val == -1)
01d26955 222 log_err("sysconf(_SC_NPROCESSORS_ONLN) failed\n");
671b0600 223
9277ec14
BC
224 break;
225
226 case _SC_PAGESIZE:
227 GetSystemInfo(&sysInfo);
228 val = sysInfo.dwPageSize;
229 break;
230
231 case _SC_PHYS_PAGES:
232 status.dwLength = sizeof(status);
01d26955
BC
233 val2 = sysconf(_SC_PAGESIZE);
234 if (GlobalMemoryStatusEx(&status) && val2 != -1)
235 val = status.ullTotalPhys / val2;
236 else
237 log_err("sysconf(_SC_PHYS_PAGES) failed\n");
9277ec14
BC
238 break;
239 default:
240 log_err("sysconf(%d) is not implemented\n", name);
241 break;
242 }
243
244 return val;
245}
246
247char *dl_error = NULL;
248
249int dlclose(void *handle)
250{
251 return !FreeLibrary((HMODULE)handle);
252}
253
254void *dlopen(const char *file, int mode)
255{
256 HMODULE hMod;
257
258 hMod = LoadLibrary(file);
259 if (hMod == INVALID_HANDLE_VALUE)
260 dl_error = (char*)"LoadLibrary failed";
261 else
262 dl_error = NULL;
263
264 return hMod;
265}
266
267void *dlsym(void *handle, const char *name)
268{
269 FARPROC fnPtr;
270
271 fnPtr = GetProcAddress((HMODULE)handle, name);
272 if (fnPtr == NULL)
273 dl_error = (char*)"GetProcAddress failed";
274 else
275 dl_error = NULL;
276
277 return fnPtr;
278}
279
280char *dlerror(void)
281{
282 return dl_error;
283}
284
ba55bfa9
BC
285/* Copied from http://blogs.msdn.com/b/joshpoley/archive/2007/12/19/date-time-formats-and-conversions.aspx */
286void Time_tToSystemTime(time_t dosTime, SYSTEMTIME *systemTime)
287{
e8ed50bc
JA
288 FILETIME utcFT;
289 LONGLONG jan1970;
7ff0297f 290 SYSTEMTIME tempSystemTime;
5de1ade5 291
e8ed50bc
JA
292 jan1970 = Int32x32To64(dosTime, 10000000) + 116444736000000000;
293 utcFT.dwLowDateTime = (DWORD)jan1970;
294 utcFT.dwHighDateTime = jan1970 >> 32;
ba55bfa9 295
e8ed50bc 296 FileTimeToSystemTime((FILETIME*)&utcFT, &tempSystemTime);
7ff0297f 297 SystemTimeToTzSpecificLocalTime(NULL, &tempSystemTime, systemTime);
ba55bfa9
BC
298}
299
e8ed50bc 300char *ctime_r(const time_t *t, char *buf)
ba55bfa9 301{
e8ed50bc
JA
302 SYSTEMTIME systime;
303 const char * const dayOfWeek[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
304 const char * const monthOfYear[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
305
306 Time_tToSystemTime(*t, &systime);
307
308 /*
309 * We don't know how long `buf` is, but assume it's rounded up from
310 * the minimum of 25 to 32
311 */
a4820445
BVA
312 snprintf(buf, 32, "%s %s %d %02d:%02d:%02d %04d\n",
313 dayOfWeek[systime.wDayOfWeek % 7],
314 monthOfYear[(systime.wMonth - 1) % 12],
315 systime.wDay, systime.wHour, systime.wMinute,
316 systime.wSecond, systime.wYear);
e8ed50bc 317 return buf;
ba55bfa9
BC
318}
319
9277ec14
BC
320int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
321{
322 FILETIME fileTime;
9576f613
BC
323 uint64_t unix_time, windows_time;
324 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
9277ec14 325
fc0b830f 326 /* Ignore the timezone parameter */
9277ec14
BC
327 (void)tzp;
328
329 /*
330 * Windows time is stored as the number 100 ns intervals since January 1 1601.
331 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
332 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
333 */
334 GetSystemTimeAsFileTime(&fileTime);
9576f613 335 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
9277ec14
BC
336 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
337 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
338 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
339 tp->tv_sec = unix_time / 1000;
340 tp->tv_usec = (unix_time % 1000) * 1000;
341 return 0;
342}
343
e8ed50bc 344int sigaction(int sig, const struct sigaction *act, struct sigaction *oact)
9277ec14 345{
e5b8f91c
BC
346 int rc = 0;
347 void (*prev_handler)(int);
348
349 prev_handler = signal(sig, act->sa_handler);
350 if (oact != NULL)
351 oact->sa_handler = prev_handler;
352
353 if (prev_handler == SIG_ERR)
354 rc = -1;
355
356 return rc;
9277ec14
BC
357}
358
e8ed50bc 359int lstat(const char *path, struct stat *buf)
9277ec14
BC
360{
361 return stat(path, buf);
362}
363
e8ed50bc 364void *mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
9277ec14
BC
365{
366 DWORD vaProt = 0;
06cbb3c7
RC
367 DWORD mapAccess = 0;
368 DWORD lenlow;
369 DWORD lenhigh;
370 HANDLE hMap;
9277ec14
BC
371 void* allocAddr = NULL;
372
373 if (prot & PROT_NONE)
374 vaProt |= PAGE_NOACCESS;
375
06cbb3c7 376 if ((prot & PROT_READ) && !(prot & PROT_WRITE)) {
9277ec14 377 vaProt |= PAGE_READONLY;
06cbb3c7
RC
378 mapAccess = FILE_MAP_READ;
379 }
9277ec14 380
06cbb3c7 381 if (prot & PROT_WRITE) {
9277ec14 382 vaProt |= PAGE_READWRITE;
06cbb3c7
RC
383 mapAccess |= FILE_MAP_WRITE;
384 }
385
386 lenlow = len & 0xFFFF;
387 lenhigh = len >> 16;
388 /* If the low DWORD is zero and the high DWORD is non-zero, `CreateFileMapping`
389 will return ERROR_INVALID_PARAMETER. To avoid this, set both to zero. */
e8ed50bc 390 if (lenlow == 0)
06cbb3c7 391 lenhigh = 0;
9277ec14 392
e8ed50bc 393 if (flags & MAP_ANON || flags & MAP_ANONYMOUS) {
9277ec14 394 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
10a6b3c6
BC
395 if (allocAddr == NULL)
396 errno = win_to_posix_error(GetLastError());
e8ed50bc
JA
397 } else {
398 hMap = CreateFileMapping((HANDLE)_get_osfhandle(fildes), NULL,
399 vaProt, lenhigh, lenlow, NULL);
06cbb3c7
RC
400
401 if (hMap != NULL)
e8ed50bc
JA
402 allocAddr = MapViewOfFile(hMap, mapAccess, off >> 16,
403 off & 0xFFFF, len);
06cbb3c7
RC
404 if (hMap == NULL || allocAddr == NULL)
405 errno = win_to_posix_error(GetLastError());
406
407 }
9277ec14
BC
408
409 return allocAddr;
410}
411
412int munmap(void *addr, size_t len)
413{
06cbb3c7
RC
414 BOOL success;
415
416 /* We may have allocated the memory with either MapViewOfFile or
417 VirtualAlloc. Therefore, try calling UnmapViewOfFile first, and if that
418 fails, call VirtualFree. */
419 success = UnmapViewOfFile(addr);
420
421 if (!success)
06cbb3c7 422 success = VirtualFree(addr, 0, MEM_RELEASE);
10a6b3c6 423
06cbb3c7
RC
424 return !success;
425}
426
427int msync(void *addr, size_t len, int flags)
428{
429 return !FlushViewOfFile(addr, len);
9277ec14
BC
430}
431
432int fork(void)
433{
434 log_err("%s is not implemented\n", __func__);
435 errno = ENOSYS;
10a6b3c6 436 return -1;
9277ec14
BC
437}
438
439pid_t setsid(void)
440{
441 log_err("%s is not implemented\n", __func__);
442 errno = ENOSYS;
10a6b3c6 443 return -1;
9277ec14
BC
444}
445
ad9c0fbc
BC
446static HANDLE log_file = INVALID_HANDLE_VALUE;
447
9277ec14
BC
448void openlog(const char *ident, int logopt, int facility)
449{
e8ed50bc
JA
450 if (log_file != INVALID_HANDLE_VALUE)
451 return;
452
453 log_file = CreateFileA("syslog.txt", GENERIC_WRITE,
454 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
455 OPEN_ALWAYS, 0, NULL);
9277ec14
BC
456}
457
458void closelog(void)
459{
ad9c0fbc
BC
460 CloseHandle(log_file);
461 log_file = INVALID_HANDLE_VALUE;
462}
463
464void syslog(int priority, const char *message, ... /* argument */)
465{
466 va_list v;
467 int len;
468 char *output;
469 DWORD bytes_written;
470
471 if (log_file == INVALID_HANDLE_VALUE) {
e8ed50bc
JA
472 log_file = CreateFileA("syslog.txt", GENERIC_WRITE,
473 FILE_SHARE_READ | FILE_SHARE_WRITE,
474 NULL, OPEN_ALWAYS, 0, NULL);
ad9c0fbc
BC
475 }
476
477 if (log_file == INVALID_HANDLE_VALUE) {
478 log_err("syslog: failed to open log file\n");
479 return;
480 }
481
482 va_start(v, message);
483 len = _vscprintf(message, v);
484 output = malloc(len + sizeof(char));
98dc2db5 485 vsprintf(output, message, v);
ad9c0fbc
BC
486 WriteFile(log_file, output, len, &bytes_written, NULL);
487 va_end(v);
98dc2db5 488 free(output);
9277ec14
BC
489}
490
491int kill(pid_t pid, int sig)
492{
493 errno = ESRCH;
10a6b3c6 494 return -1;
9277ec14
BC
495}
496
fc0b830f
BC
497/*
498 * This is assumed to be used only by the network code,
499 * and so doesn't try and handle any of the other cases
500 */
9277ec14
BC
501int fcntl(int fildes, int cmd, ...)
502{
fc0b830f
BC
503 /*
504 * non-blocking mode doesn't work the same as in BSD sockets,
505 * so ignore it.
506 */
9277ec14
BC
507#if 0
508 va_list ap;
509 int val, opt, status;
510
511 if (cmd == F_GETFL)
512 return 0;
513 else if (cmd != F_SETFL) {
514 errno = EINVAL;
10a6b3c6 515 return -1;
9277ec14
BC
516 }
517
518 va_start(ap, 1);
519
520 opt = va_arg(ap, int);
521 if (opt & O_NONBLOCK)
522 val = 1;
523 else
524 val = 0;
525
526 status = ioctlsocket((SOCKET)fildes, opt, &val);
527
528 if (status == SOCKET_ERROR) {
529 errno = EINVAL;
530 val = -1;
531 }
532
533 va_end(ap);
534
535 return val;
536#endif
537return 0;
538}
539
d5b3cfd4 540#ifndef CLOCK_MONOTONIC_RAW
541#define CLOCK_MONOTONIC_RAW 4
542#endif
543
9277ec14
BC
544/*
545 * Get the value of a local clock source.
d5b3cfd4 546 * This implementation supports 3 clocks: CLOCK_MONOTONIC/CLOCK_MONOTONIC_RAW
547 * provide high-accuracy relative time, while CLOCK_REALTIME provides a
548 * low-accuracy wall time.
9277ec14
BC
549 */
550int clock_gettime(clockid_t clock_id, struct timespec *tp)
551{
552 int rc = 0;
553
d5b3cfd4 554 if (clock_id == CLOCK_MONOTONIC || clock_id == CLOCK_MONOTONIC_RAW) {
9277ec14
BC
555 static LARGE_INTEGER freq = {{0,0}};
556 LARGE_INTEGER counts;
5aa23eb8 557 uint64_t t;
9277ec14
BC
558
559 QueryPerformanceCounter(&counts);
560 if (freq.QuadPart == 0)
561 QueryPerformanceFrequency(&freq);
562
563 tp->tv_sec = counts.QuadPart / freq.QuadPart;
564 /* Get the difference between the number of ns stored
565 * in 'tv_sec' and that stored in 'counts' */
5aa23eb8 566 t = tp->tv_sec * freq.QuadPart;
9277ec14
BC
567 t = counts.QuadPart - t;
568 /* 't' now contains the number of cycles since the last second.
569 * We want the number of nanoseconds, so multiply out by 1,000,000,000
570 * and then divide by the frequency. */
571 t *= 1000000000;
572 tp->tv_nsec = t / freq.QuadPart;
e8ed50bc 573 } else if (clock_id == CLOCK_REALTIME) {
9277ec14
BC
574 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
575 * higher-precision field. */
576 struct timeval tv;
577 gettimeofday(&tv, NULL);
578 tp->tv_sec = tv.tv_sec;
579 tp->tv_nsec = tv.tv_usec * 1000;
580 } else {
581 errno = EINVAL;
582 rc = -1;
583 }
584
585 return rc;
586}
587
588int mlock(const void * addr, size_t len)
589{
10a6b3c6
BC
590 SIZE_T min, max;
591 BOOL success;
592 HANDLE process = GetCurrentProcess();
593
594 success = GetProcessWorkingSetSize(process, &min, &max);
595 if (!success) {
596 errno = win_to_posix_error(GetLastError());
597 return -1;
598 }
599
600 min += len;
601 max += len;
602 success = SetProcessWorkingSetSize(process, min, max);
603 if (!success) {
604 errno = win_to_posix_error(GetLastError());
605 return -1;
606 }
607
608 success = VirtualLock((LPVOID)addr, len);
609 if (!success) {
610 errno = win_to_posix_error(GetLastError());
611 return -1;
612 }
613
614 return 0;
9277ec14
BC
615}
616
617int munlock(const void * addr, size_t len)
618{
10a6b3c6 619 BOOL success = VirtualUnlock((LPVOID)addr, len);
e8ed50bc 620
10a6b3c6
BC
621 if (!success) {
622 errno = win_to_posix_error(GetLastError());
623 return -1;
624 }
625
626 return 0;
9277ec14
BC
627}
628
629pid_t waitpid(pid_t pid, int *stat_loc, int options)
630{
631 log_err("%s is not implemented\n", __func__);
632 errno = ENOSYS;
633 return -1;
634}
635
636int usleep(useconds_t useconds)
637{
638 Sleep(useconds / 1000);
639 return 0;
640}
641
642char *basename(char *path)
643{
644 static char name[MAX_PATH];
645 int i;
646
647 if (path == NULL || strlen(path) == 0)
648 return (char*)".";
649
650 i = strlen(path) - 1;
651
9576f613 652 while (path[i] != '\\' && path[i] != '/' && i >= 0)
9277ec14
BC
653 i--;
654
13a85be9
TK
655 name[MAX_PATH - 1] = '\0';
656 strncpy(name, path + i + 1, MAX_PATH - 1);
9277ec14
BC
657
658 return name;
659}
660
9277ec14
BC
661int fsync(int fildes)
662{
663 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
10a6b3c6
BC
664 if (!FlushFileBuffers(hFile)) {
665 errno = win_to_posix_error(GetLastError());
666 return -1;
667 }
668
669 return 0;
9277ec14
BC
670}
671
672int nFileMappings = 0;
673HANDLE fileMappings[1024];
674
675int shmget(key_t key, size_t size, int shmflg)
676{
677 int mapid = -1;
d3987946
BC
678 uint32_t size_low = size & 0xFFFFFFFF;
679 uint32_t size_high = ((uint64_t)size) >> 32;
e8ed50bc
JA
680 HANDLE hMapping;
681
682 hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
683 PAGE_EXECUTE_READWRITE | SEC_RESERVE,
684 size_high, size_low, NULL);
9277ec14
BC
685 if (hMapping != NULL) {
686 fileMappings[nFileMappings] = hMapping;
687 mapid = nFileMappings;
688 nFileMappings++;
e8ed50bc 689 } else
9277ec14 690 errno = ENOSYS;
9277ec14
BC
691
692 return mapid;
693}
694
695void *shmat(int shmid, const void *shmaddr, int shmflg)
696{
e8ed50bc 697 void *mapAddr;
9277ec14 698 MEMORY_BASIC_INFORMATION memInfo;
e8ed50bc 699
9277ec14 700 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
10a6b3c6
BC
701 if (mapAddr == NULL) {
702 errno = win_to_posix_error(GetLastError());
703 return (void*)-1;
704 }
705
706 if (VirtualQuery(mapAddr, &memInfo, sizeof(memInfo)) == 0) {
707 errno = win_to_posix_error(GetLastError());
708 return (void*)-1;
709 }
710
9277ec14 711 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
10a6b3c6
BC
712 if (mapAddr == NULL) {
713 errno = win_to_posix_error(GetLastError());
714 return (void*)-1;
715 }
716
9277ec14
BC
717 return mapAddr;
718}
719
720int shmdt(const void *shmaddr)
721{
10a6b3c6
BC
722 if (!UnmapViewOfFile(shmaddr)) {
723 errno = win_to_posix_error(GetLastError());
724 return -1;
725 }
726
727 return 0;
9277ec14
BC
728}
729
730int shmctl(int shmid, int cmd, struct shmid_ds *buf)
731{
732 if (cmd == IPC_RMID) {
733 fileMappings[shmid] = INVALID_HANDLE_VALUE;
734 return 0;
9277ec14 735 }
e8ed50bc
JA
736
737 log_err("%s is not implemented\n", __func__);
10a6b3c6
BC
738 errno = ENOSYS;
739 return -1;
9277ec14
BC
740}
741
742int setuid(uid_t uid)
743{
744 log_err("%s is not implemented\n", __func__);
745 errno = ENOSYS;
10a6b3c6 746 return -1;
9277ec14
BC
747}
748
749int setgid(gid_t gid)
750{
751 log_err("%s is not implemented\n", __func__);
752 errno = ENOSYS;
10a6b3c6 753 return -1;
9277ec14
BC
754}
755
756int nice(int incr)
757{
24a2bb13 758 DWORD prioclass = NORMAL_PRIORITY_CLASS;
1e7fa601 759
24a2bb13
BC
760 if (incr < -15)
761 prioclass = HIGH_PRIORITY_CLASS;
762 else if (incr < 0)
763 prioclass = ABOVE_NORMAL_PRIORITY_CLASS;
764 else if (incr > 15)
765 prioclass = IDLE_PRIORITY_CLASS;
766 else if (incr > 0)
767 prioclass = BELOW_NORMAL_PRIORITY_CLASS;
1e7fa601 768
24a2bb13
BC
769 if (!SetPriorityClass(GetCurrentProcess(), prioclass))
770 log_err("fio: SetPriorityClass failed\n");
9277ec14
BC
771
772 return 0;
773}
774
775int getrusage(int who, struct rusage *r_usage)
776{
9576f613 777 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
9277ec14
BC
778 FILETIME cTime, eTime, kTime, uTime;
779 time_t time;
7732a09b 780 HANDLE h;
9277ec14
BC
781
782 memset(r_usage, 0, sizeof(*r_usage));
783
7732a09b
HL
784 if (who == RUSAGE_SELF) {
785 h = GetCurrentProcess();
786 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
787 } else if (who == RUSAGE_THREAD) {
788 h = GetCurrentThread();
789 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
790 } else {
791 log_err("fio: getrusage %d is not implemented\n", who);
792 return -1;
793 }
794
9576f613 795 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
9277ec14
BC
796 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
797 * 1601 to 1970 */
798 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
799 r_usage->ru_utime.tv_sec = time;
800 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
801 r_usage->ru_utime.tv_usec = 0;
9576f613 802 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
9277ec14
BC
803 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
804 * 1601 to 1970 */
805 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
806 r_usage->ru_stime.tv_sec = time;
807 r_usage->ru_stime.tv_usec = 0;
808 return 0;
809}
810
811int posix_madvise(void *addr, size_t len, int advice)
812{
9277ec14
BC
813 return ENOSYS;
814}
815
9277ec14
BC
816int fdatasync(int fildes)
817{
818 return fsync(fildes);
819}
820
821ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
822 off_t offset)
823{
9576f613
BC
824 int64_t pos = _telli64(fildes);
825 ssize_t len = _write(fildes, buf, nbyte);
e8ed50bc 826
9576f613 827 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
828 return len;
829}
830
831ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
832{
9576f613 833 int64_t pos = _telli64(fildes);
9277ec14 834 ssize_t len = read(fildes, buf, nbyte);
e8ed50bc 835
9576f613 836 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
837 return len;
838}
839
840ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
841{
842 log_err("%s is not implemented\n", __func__);
843 errno = ENOSYS;
10a6b3c6 844 return -1;
9277ec14
BC
845}
846
847ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
848{
70a61165
BC
849 int i;
850 DWORD bytes_written = 0;
e8ed50bc
JA
851
852 for (i = 0; i < iovcnt; i++) {
853 int len;
854
855 len = send((SOCKET)fildes, iov[i].iov_base, iov[i].iov_len, 0);
856 if (len == SOCKET_ERROR) {
70a61165
BC
857 DWORD err = GetLastError();
858 errno = win_to_posix_error(err);
859 bytes_written = -1;
860 break;
861 }
862 bytes_written += len;
863 }
864
865 return bytes_written;
9277ec14
BC
866}
867
e8ed50bc 868long long strtoll(const char *restrict str, char **restrict endptr, int base)
9277ec14
BC
869{
870 return _strtoi64(str, endptr, base);
871}
872
9277ec14
BC
873int poll(struct pollfd fds[], nfds_t nfds, int timeout)
874{
875 struct timeval tv;
876 struct timeval *to = NULL;
877 fd_set readfds, writefds, exceptfds;
878 int i;
879 int rc;
880
3f457bea 881 if (timeout != -1) {
f9a58c2a 882 to = &tv;
3f457bea
BC
883 to->tv_sec = timeout / 1000;
884 to->tv_usec = (timeout % 1000) * 1000;
885 }
9277ec14
BC
886
887 FD_ZERO(&readfds);
888 FD_ZERO(&writefds);
889 FD_ZERO(&exceptfds);
890
e8ed50bc 891 for (i = 0; i < nfds; i++) {
2ec7cd03 892 if (fds[i].fd == INVALID_SOCKET) {
9277ec14
BC
893 fds[i].revents = 0;
894 continue;
895 }
896
897 if (fds[i].events & POLLIN)
898 FD_SET(fds[i].fd, &readfds);
899
900 if (fds[i].events & POLLOUT)
901 FD_SET(fds[i].fd, &writefds);
902
f9a58c2a 903 FD_SET(fds[i].fd, &exceptfds);
9277ec14 904 }
9277ec14
BC
905 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
906
907 if (rc != SOCKET_ERROR) {
e8ed50bc 908 for (i = 0; i < nfds; i++) {
2ec7cd03 909 if (fds[i].fd == INVALID_SOCKET)
9277ec14 910 continue;
9277ec14
BC
911
912 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
913 fds[i].revents |= POLLIN;
914
915 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
916 fds[i].revents |= POLLOUT;
917
918 if (FD_ISSET(fds[i].fd, &exceptfds))
919 fds[i].revents |= POLLHUP;
920 }
921 }
9277ec14
BC
922 return rc;
923}
924
925int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
926{
8b6a404c 927 struct timespec tv;
21c75387
BC
928 DWORD ms_remaining;
929 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
930
931 if (ms_total == 0)
932 ms_total = 1;
933
934 ms_remaining = ms_total;
935
936 /* Since Sleep() can sleep for less than the requested time, add a loop to
937 ensure we only return after the requested length of time has elapsed */
938 do {
939 fio_gettime(&tv, NULL);
940 Sleep(ms_remaining);
941 ms_remaining = ms_total - mtime_since_now(&tv);
942 } while (ms_remaining > 0 && ms_remaining < ms_total);
943
944 /* this implementation will never sleep for less than the requested time */
945 if (rmtp != NULL) {
946 rmtp->tv_sec = 0;
947 rmtp->tv_nsec = 0;
948 }
949
950 return 0;
9277ec14
BC
951}
952
953DIR *opendir(const char *dirname)
954{
01d26955 955 struct dirent_ctx *dc = NULL;
e8ed50bc 956 HANDLE file;
01d26955
BC
957
958 /* See if we can open it. If not, we'll return an error here */
e8ed50bc
JA
959 file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
960 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
01d26955
BC
961 if (file != INVALID_HANDLE_VALUE) {
962 CloseHandle(file);
a4820445
BVA
963 dc = malloc(sizeof(struct dirent_ctx));
964 snprintf(dc->dirname, sizeof(dc->dirname), "%s", dirname);
01d26955
BC
965 dc->find_handle = INVALID_HANDLE_VALUE;
966 } else {
967 DWORD error = GetLastError();
968 if (error == ERROR_FILE_NOT_FOUND)
969 errno = ENOENT;
970
971 else if (error == ERROR_PATH_NOT_FOUND)
972 errno = ENOTDIR;
973 else if (error == ERROR_TOO_MANY_OPEN_FILES)
974 errno = ENFILE;
975 else if (error == ERROR_ACCESS_DENIED)
976 errno = EACCES;
977 else
978 errno = error;
979 }
980
981 return dc;
9277ec14
BC
982}
983
984int closedir(DIR *dirp)
985{
01d26955
BC
986 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
987 FindClose(dirp->find_handle);
ad9c0fbc 988
01d26955
BC
989 free(dirp);
990 return 0;
9277ec14
BC
991}
992
993struct dirent *readdir(DIR *dirp)
994{
ad9c0fbc
BC
995 static struct dirent de;
996 WIN32_FIND_DATA find_data;
997
998 if (dirp == NULL)
999 return NULL;
1000
1001 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
1002 char search_pattern[MAX_PATH];
e8ed50bc 1003
a4820445
BVA
1004 snprintf(search_pattern, sizeof(search_pattern), "%s\\*",
1005 dirp->dirname);
ad9c0fbc
BC
1006 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
1007 if (dirp->find_handle == INVALID_HANDLE_VALUE)
1008 return NULL;
1009 } else {
1010 if (!FindNextFile(dirp->find_handle, &find_data))
1011 return NULL;
1012 }
1013
a4820445 1014 snprintf(de.d_name, sizeof(de.d_name), find_data.cFileName);
ad9c0fbc
BC
1015 de.d_ino = 0;
1016
1017 return &de;
9277ec14
BC
1018}
1019
1020uid_t geteuid(void)
1021{
1022 log_err("%s is not implemented\n", __func__);
1023 errno = ENOSYS;
1024 return -1;
1025}
1026
f16b7405
BC
1027in_addr_t inet_network(const char *cp)
1028{
1029 in_addr_t hbo;
1030 in_addr_t nbo = inet_addr(cp);
1031 hbo = ((nbo & 0xFF) << 24) + ((nbo & 0xFF00) << 8) + ((nbo & 0xFF0000) >> 8) + ((nbo & 0xFF000000) >> 24);
1032 return hbo;
1033}
f8fef4c6 1034
1035static HANDLE create_named_pipe(char *pipe_name, int wait_connect_time)
1036{
1037 HANDLE hpipe;
1038
1039 hpipe = CreateNamedPipe (
1040 pipe_name,
1041 PIPE_ACCESS_DUPLEX,
1042 PIPE_WAIT | PIPE_TYPE_BYTE,
1043 1, 0, 0, wait_connect_time, NULL);
1044
1045 if (hpipe == INVALID_HANDLE_VALUE) {
1046 log_err("ConnectNamedPipe failed (%lu).\n", GetLastError());
1047 return INVALID_HANDLE_VALUE;
1048 }
1049
1050 if (!ConnectNamedPipe(hpipe, NULL)) {
1051 log_err("ConnectNamedPipe failed (%lu).\n", GetLastError());
1052 CloseHandle(hpipe);
1053 return INVALID_HANDLE_VALUE;
1054 }
1055
1056 return hpipe;
1057}
1058
1059static BOOL windows_create_process(PROCESS_INFORMATION *pi, const char *args, HANDLE *hjob)
1060{
1061 LPSTR this_cmd_line = GetCommandLine();
1062 LPSTR new_process_cmd_line = malloc((strlen(this_cmd_line)+strlen(args)) * sizeof(char *));
1063 STARTUPINFO si = {0};
1064 DWORD flags = 0;
1065
1066 strcpy(new_process_cmd_line, this_cmd_line);
1067 strcat(new_process_cmd_line, args);
1068
1069 si.cb = sizeof(si);
1070 memset(pi, 0, sizeof(*pi));
1071
1072 if ((hjob != NULL) && (*hjob != INVALID_HANDLE_VALUE))
1073 flags = CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB;
1074
1075 flags |= CREATE_NEW_CONSOLE;
1076
1077 if( !CreateProcess( NULL,
1078 new_process_cmd_line,
1079 NULL, /* Process handle not inherited */
1080 NULL, /* Thread handle not inherited */
1081 TRUE, /* no handle inheritance */
1082 flags,
1083 NULL, /* Use parent's environment block */
1084 NULL, /* Use parent's starting directory */
1085 &si,
1086 pi )
1087 )
1088 {
1089 log_err("CreateProcess failed (%lu).\n", GetLastError() );
1090 free(new_process_cmd_line);
1091 return 1;
1092 }
1093 if ((hjob != NULL) && (*hjob != INVALID_HANDLE_VALUE)) {
1094 BOOL ret = AssignProcessToJobObject(*hjob, pi->hProcess);
1095 if (!ret) {
1096 log_err("AssignProcessToJobObject failed (%lu).\n", GetLastError() );
1097 return 1;
1098 }
1099
1100 ResumeThread(pi->hThread);
1101 }
1102
1103 free(new_process_cmd_line);
1104 return 0;
1105}
1106
1107HANDLE windows_create_job(void)
1108{
1109 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
1110 BOOL success;
1111 HANDLE hjob = CreateJobObject(NULL, NULL);
1112
1113 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
1114 success = SetInformationJobObject(hjob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
1115 if ( success == 0 ) {
1116 log_err( "SetInformationJobObject failed: error %lu\n", GetLastError() );
1117 return INVALID_HANDLE_VALUE;
1118 }
1119 return hjob;
1120}
1121
1122/* wait for a child process to either exit or connect to a child */
1123static bool monitor_process_till_connect(PROCESS_INFORMATION *pi, HANDLE *hpipe)
1124{
1125 bool connected = FALSE;
1126 bool process_alive = TRUE;
1127 char buffer[32] = {0};
1128 DWORD bytes_read;
1129
1130 do {
1131 DWORD exit_code;
1132 GetExitCodeProcess(pi->hProcess, &exit_code);
1133 if (exit_code != STILL_ACTIVE) {
1134 dprint(FD_PROCESS, "process %u exited %d\n", GetProcessId(pi->hProcess), exit_code);
1135 break;
1136 }
1137
1138 memset(buffer, 0, sizeof(buffer));
1139 ReadFile(*hpipe, &buffer, sizeof(buffer) - 1, &bytes_read, NULL);
1140 if (bytes_read && strstr(buffer, "connected")) {
1141 dprint(FD_PROCESS, "process %u connected to client\n", GetProcessId(pi->hProcess));
1142 connected = TRUE;
1143 }
1144 usleep(10*1000);
1145 } while (process_alive && !connected);
1146 return connected;
1147}
1148
1149/*create a process with --server-internal to emulate fork() */
1150HANDLE windows_handle_connection(HANDLE hjob, int sk)
1151{
1152 char pipe_name[64] = "\\\\.\\pipe\\fiointernal-";
1153 char args[128] = " --server-internal=";
1154 PROCESS_INFORMATION pi;
1155 HANDLE hpipe = INVALID_HANDLE_VALUE;
1156 WSAPROTOCOL_INFO protocol_info;
1157 HANDLE ret;
1158
1159 sprintf(pipe_name+strlen(pipe_name), "%d", GetCurrentProcessId());
1160 sprintf(args+strlen(args), "%s", pipe_name);
1161
1162 if (windows_create_process(&pi, args, &hjob) != 0)
1163 return INVALID_HANDLE_VALUE;
1164 else
1165 ret = pi.hProcess;
1166
1167 /* duplicate socket and write the protocol_info to pipe so child can
fc002f14 1168 * duplicate the communication socket */
f8fef4c6 1169 if (WSADuplicateSocket(sk, GetProcessId(pi.hProcess), &protocol_info)) {
1170 log_err("WSADuplicateSocket failed (%lu).\n", GetLastError());
1171 ret = INVALID_HANDLE_VALUE;
1172 goto cleanup;
1173 }
1174
1175 /* make a pipe with a unique name based upon processid */
1176 hpipe = create_named_pipe(pipe_name, 1000);
1177 if (hpipe == INVALID_HANDLE_VALUE) {
1178 ret = INVALID_HANDLE_VALUE;
1179 goto cleanup;
1180 }
1181
1182 if (!WriteFile(hpipe, &protocol_info, sizeof(protocol_info), NULL, NULL)) {
1183 log_err("WriteFile failed (%lu).\n", GetLastError());
1184 ret = INVALID_HANDLE_VALUE;
1185 goto cleanup;
1186 }
1187
1188 dprint(FD_PROCESS, "process %d created child process %u\n", GetCurrentProcessId(), GetProcessId(pi.hProcess));
1189
1190 /* monitor the process until it either exits or connects. This level
1191 * doesnt care which of those occurs because the result is that it
1192 * needs to loop around and create another child process to monitor */
1193 if (!monitor_process_till_connect(&pi, &hpipe))
1194 ret = INVALID_HANDLE_VALUE;
1195
1196cleanup:
1197 /* close the handles and pipes because this thread is done monitoring them */
1198 if (ret == INVALID_HANDLE_VALUE)
1199 CloseHandle(pi.hProcess);
1200 CloseHandle(pi.hThread);
1201 DisconnectNamedPipe(hpipe);
1202 CloseHandle(hpipe);
1203 return ret;
1204}