Windows fio 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>
10#include <stdlib.h>
11#include <unistd.h>
12#include <dirent.h>
13#include <pthread.h>
14#include <semaphore.h>
15#include <sys/shm.h>
16#include <sys/mman.h>
17#include <sys/uio.h>
18#include <sys/resource.h>
19#include <sys/poll.h>
20
21#include "../os-windows.h"
22
21c75387
BC
23extern unsigned long mtime_since_now(struct timeval *);
24extern void fio_gettime(struct timeval *, void *);
25
9277ec14
BC
26long sysconf(int name)
27{
28 long long val = -1;
29 DWORD len;
30 SYSTEM_LOGICAL_PROCESSOR_INFORMATION processorInfo;
31 SYSTEM_INFO sysInfo;
32 MEMORYSTATUSEX status;
33
34 switch (name)
35 {
36 case _SC_NPROCESSORS_ONLN:
37 len = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
38 GetLogicalProcessorInformation(&processorInfo, &len);
39 val = len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
40 break;
41
42 case _SC_PAGESIZE:
43 GetSystemInfo(&sysInfo);
44 val = sysInfo.dwPageSize;
45 break;
46
47 case _SC_PHYS_PAGES:
48 status.dwLength = sizeof(status);
49 GlobalMemoryStatusEx(&status);
50 val = status.ullTotalPhys;
51 break;
52 default:
53 log_err("sysconf(%d) is not implemented\n", name);
54 break;
55 }
56
57 return val;
58}
59
60char *dl_error = NULL;
61
62int dlclose(void *handle)
63{
64 return !FreeLibrary((HMODULE)handle);
65}
66
67void *dlopen(const char *file, int mode)
68{
69 HMODULE hMod;
70
71 hMod = LoadLibrary(file);
72 if (hMod == INVALID_HANDLE_VALUE)
73 dl_error = (char*)"LoadLibrary failed";
74 else
75 dl_error = NULL;
76
77 return hMod;
78}
79
80void *dlsym(void *handle, const char *name)
81{
82 FARPROC fnPtr;
83
84 fnPtr = GetProcAddress((HMODULE)handle, name);
85 if (fnPtr == NULL)
86 dl_error = (char*)"GetProcAddress failed";
87 else
88 dl_error = NULL;
89
90 return fnPtr;
91}
92
93char *dlerror(void)
94{
95 return dl_error;
96}
97
98int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
99{
100 FILETIME fileTime;
9576f613
BC
101 uint64_t unix_time, windows_time;
102 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
9277ec14 103
fc0b830f 104 /* Ignore the timezone parameter */
9277ec14
BC
105 (void)tzp;
106
107 /*
108 * Windows time is stored as the number 100 ns intervals since January 1 1601.
109 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
110 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
111 */
112 GetSystemTimeAsFileTime(&fileTime);
9576f613 113 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
9277ec14
BC
114 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
115 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
116 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
117 tp->tv_sec = unix_time / 1000;
118 tp->tv_usec = (unix_time % 1000) * 1000;
119 return 0;
120}
121
122void syslog(int priority, const char *message, ... /* argument */)
123{
124 log_err("%s is not implemented\n", __func__);
125}
126
127int sigaction(int sig, const struct sigaction *act,
128 struct sigaction *oact)
129{
e5b8f91c
BC
130 int rc = 0;
131 void (*prev_handler)(int);
132
133 prev_handler = signal(sig, act->sa_handler);
134 if (oact != NULL)
135 oact->sa_handler = prev_handler;
136
137 if (prev_handler == SIG_ERR)
138 rc = -1;
139
140 return rc;
9277ec14
BC
141}
142
143int lstat(const char * path, struct stat * buf)
144{
145 return stat(path, buf);
146}
147
148void *mmap(void *addr, size_t len, int prot, int flags,
149 int fildes, off_t off)
150{
151 DWORD vaProt = 0;
152 void* allocAddr = NULL;
153
154 if (prot & PROT_NONE)
155 vaProt |= PAGE_NOACCESS;
156
157 if ((prot & PROT_READ) && !(prot & PROT_WRITE))
158 vaProt |= PAGE_READONLY;
159
160 if (prot & PROT_WRITE)
161 vaProt |= PAGE_READWRITE;
162
163 if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
164 {
165 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
166 }
167
168 return allocAddr;
169}
170
171int munmap(void *addr, size_t len)
172{
173 return !VirtualFree(addr, 0, MEM_RELEASE);
174}
175
176int fork(void)
177{
178 log_err("%s is not implemented\n", __func__);
179 errno = ENOSYS;
180 return (-1);
181}
182
183pid_t setsid(void)
184{
185 log_err("%s is not implemented\n", __func__);
186 errno = ENOSYS;
187 return (-1);
188}
189
190void openlog(const char *ident, int logopt, int facility)
191{
192 log_err("%s is not implemented\n", __func__);
193}
194
195void closelog(void)
196{
197 log_err("%s is not implemented\n", __func__);
198}
199
200int kill(pid_t pid, int sig)
201{
202 errno = ESRCH;
203 return (-1);
204}
205
fc0b830f
BC
206/*
207 * This is assumed to be used only by the network code,
208 * and so doesn't try and handle any of the other cases
209 */
9277ec14
BC
210int fcntl(int fildes, int cmd, ...)
211{
fc0b830f
BC
212 /*
213 * non-blocking mode doesn't work the same as in BSD sockets,
214 * so ignore it.
215 */
9277ec14
BC
216#if 0
217 va_list ap;
218 int val, opt, status;
219
220 if (cmd == F_GETFL)
221 return 0;
222 else if (cmd != F_SETFL) {
223 errno = EINVAL;
224 return (-1);
225 }
226
227 va_start(ap, 1);
228
229 opt = va_arg(ap, int);
230 if (opt & O_NONBLOCK)
231 val = 1;
232 else
233 val = 0;
234
235 status = ioctlsocket((SOCKET)fildes, opt, &val);
236
237 if (status == SOCKET_ERROR) {
238 errno = EINVAL;
239 val = -1;
240 }
241
242 va_end(ap);
243
244 return val;
245#endif
246return 0;
247}
248
249/*
250 * Get the value of a local clock source.
251 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
252 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
253 */
254int clock_gettime(clockid_t clock_id, struct timespec *tp)
255{
256 int rc = 0;
257
258 if (clock_id == CLOCK_MONOTONIC)
259 {
260 static LARGE_INTEGER freq = {{0,0}};
261 LARGE_INTEGER counts;
262
263 QueryPerformanceCounter(&counts);
264 if (freq.QuadPart == 0)
265 QueryPerformanceFrequency(&freq);
266
267 tp->tv_sec = counts.QuadPart / freq.QuadPart;
268 /* Get the difference between the number of ns stored
269 * in 'tv_sec' and that stored in 'counts' */
9576f613 270 uint64_t t = tp->tv_sec * freq.QuadPart;
9277ec14
BC
271 t = counts.QuadPart - t;
272 /* 't' now contains the number of cycles since the last second.
273 * We want the number of nanoseconds, so multiply out by 1,000,000,000
274 * and then divide by the frequency. */
275 t *= 1000000000;
276 tp->tv_nsec = t / freq.QuadPart;
277 }
278 else if (clock_id == CLOCK_REALTIME)
279 {
280 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
281 * higher-precision field. */
282 struct timeval tv;
283 gettimeofday(&tv, NULL);
284 tp->tv_sec = tv.tv_sec;
285 tp->tv_nsec = tv.tv_usec * 1000;
286 } else {
287 errno = EINVAL;
288 rc = -1;
289 }
290
291 return rc;
292}
293
294int mlock(const void * addr, size_t len)
295{
296 return !VirtualLock((LPVOID)addr, len);
297}
298
299int munlock(const void * addr, size_t len)
300{
301 return !VirtualUnlock((LPVOID)addr, len);
302}
303
304pid_t waitpid(pid_t pid, int *stat_loc, int options)
305{
306 log_err("%s is not implemented\n", __func__);
307 errno = ENOSYS;
308 return -1;
309}
310
311int usleep(useconds_t useconds)
312{
313 Sleep(useconds / 1000);
314 return 0;
315}
316
317char *basename(char *path)
318{
319 static char name[MAX_PATH];
320 int i;
321
322 if (path == NULL || strlen(path) == 0)
323 return (char*)".";
324
325 i = strlen(path) - 1;
326
9576f613 327 while (path[i] != '\\' && path[i] != '/' && i >= 0)
9277ec14
BC
328 i--;
329
9576f613 330 strncpy(name, path + i + 1, MAX_PATH);
9277ec14
BC
331
332 return name;
333}
334
335int posix_fallocate(int fd, off_t offset, off_t len)
336{
9576f613 337 const int BUFFER_SIZE = 64 * 1024 * 1024;
f9a58c2a
BC
338 int rc = 0;
339 char *buf;
340 unsigned int write_len;
341 unsigned int bytes_written;
342 off_t bytes_remaining = len;
343
344 if (len == 0 || offset < 0)
345 return EINVAL;
346
347 buf = malloc(BUFFER_SIZE);
348
349 if (buf == NULL)
350 return ENOMEM;
351
352 memset(buf, 0, BUFFER_SIZE);
353
9576f613
BC
354 int64_t prev_pos = _telli64(fd);
355
356 if (_lseeki64(fd, offset, SEEK_SET) == -1)
f9a58c2a
BC
357 return errno;
358
359 while (bytes_remaining > 0) {
360 if (bytes_remaining < BUFFER_SIZE)
361 write_len = (unsigned int)bytes_remaining;
362 else
363 write_len = BUFFER_SIZE;
364
365 bytes_written = _write(fd, buf, write_len);
366 if (bytes_written == -1) {
367 rc = errno;
368 break;
369 }
370
371 bytes_remaining -= bytes_written;
372 }
373
374 free(buf);
9576f613 375 _lseeki64(fd, prev_pos, SEEK_SET);
f9a58c2a 376 return rc;
9277ec14
BC
377}
378
379int ftruncate(int fildes, off_t length)
380{
381 BOOL bSuccess;
9576f613
BC
382 int64_t prev_pos = _telli64(fildes);
383 _lseeki64(fildes, length, SEEK_SET);
9277ec14
BC
384 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
385 bSuccess = SetEndOfFile(hFile);
9576f613 386 _lseeki64(fildes, prev_pos, SEEK_SET);
9277ec14
BC
387 return !bSuccess;
388}
389
390int fsync(int fildes)
391{
392 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
393 return !FlushFileBuffers(hFile);
394}
395
396int nFileMappings = 0;
397HANDLE fileMappings[1024];
398
399int shmget(key_t key, size_t size, int shmflg)
400{
401 int mapid = -1;
d3987946
BC
402 uint32_t size_low = size & 0xFFFFFFFF;
403 uint32_t size_high = ((uint64_t)size) >> 32;
404 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
9277ec14
BC
405 if (hMapping != NULL) {
406 fileMappings[nFileMappings] = hMapping;
407 mapid = nFileMappings;
408 nFileMappings++;
409 } else {
410 errno = ENOSYS;
411 }
412
413 return mapid;
414}
415
416void *shmat(int shmid, const void *shmaddr, int shmflg)
417{
418 void* mapAddr;
419 MEMORY_BASIC_INFORMATION memInfo;
420 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
421 VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
422 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
423 return mapAddr;
424}
425
426int shmdt(const void *shmaddr)
427{
428 return !UnmapViewOfFile(shmaddr);
429}
430
431int shmctl(int shmid, int cmd, struct shmid_ds *buf)
432{
433 if (cmd == IPC_RMID) {
434 fileMappings[shmid] = INVALID_HANDLE_VALUE;
435 return 0;
436 } else {
437 log_err("%s is not implemented\n", __func__);
438 }
439 return (-1);
440}
441
442int setuid(uid_t uid)
443{
444 log_err("%s is not implemented\n", __func__);
445 errno = ENOSYS;
446 return (-1);
447}
448
449int setgid(gid_t gid)
450{
451 log_err("%s is not implemented\n", __func__);
452 errno = ENOSYS;
453 return (-1);
454}
455
456int nice(int incr)
457{
458 if (incr != 0) {
459 errno = EINVAL;
460 return -1;
461 }
462
463 return 0;
464}
465
466int getrusage(int who, struct rusage *r_usage)
467{
9576f613 468 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
9277ec14
BC
469 FILETIME cTime, eTime, kTime, uTime;
470 time_t time;
471
472 memset(r_usage, 0, sizeof(*r_usage));
473
474 HANDLE hProcess = GetCurrentProcess();
475 GetProcessTimes(hProcess, &cTime, &eTime, &kTime, &uTime);
9576f613 476 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
9277ec14
BC
477 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
478 * 1601 to 1970 */
479 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
480 r_usage->ru_utime.tv_sec = time;
481 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
482 r_usage->ru_utime.tv_usec = 0;
9576f613 483 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
9277ec14
BC
484 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
485 * 1601 to 1970 */
486 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
487 r_usage->ru_stime.tv_sec = time;
488 r_usage->ru_stime.tv_usec = 0;
489 return 0;
490}
491
492int posix_madvise(void *addr, size_t len, int advice)
493{
494 log_err("%s is not implemented\n", __func__);
495 return ENOSYS;
496}
497
fc0b830f 498/* Windows doesn't support advice for memory pages. Just ignore it. */
9277ec14
BC
499int msync(void *addr, size_t len, int flags)
500{
501 log_err("%s is not implemented\n", __func__);
502 errno = ENOSYS;
503 return -1;
504}
505
506int fdatasync(int fildes)
507{
508 return fsync(fildes);
509}
510
511ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
512 off_t offset)
513{
9576f613
BC
514 int64_t pos = _telli64(fildes);
515 ssize_t len = _write(fildes, buf, nbyte);
516 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
517 return len;
518}
519
520ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
521{
9576f613 522 int64_t pos = _telli64(fildes);
9277ec14 523 ssize_t len = read(fildes, buf, nbyte);
9576f613 524 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
525 return len;
526}
527
528ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
529{
530 log_err("%s is not implemented\n", __func__);
531 errno = ENOSYS;
532 return (-1);
533}
534
535ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
536{
537 log_err("%s is not implemented\n", __func__);
538 errno = ENOSYS;
539 return (-1);
540}
541
542long long strtoll(const char *restrict str, char **restrict endptr,
543 int base)
544{
545 return _strtoi64(str, endptr, base);
546}
547
548char *strsep(char **stringp, const char *delim)
549{
550 char *orig = *stringp;
551 BOOL gotMatch = FALSE;
552 int i = 0;
553 int j = 0;
554
555 if (*stringp == NULL)
556 return NULL;
557
558 while ((*stringp)[i] != '\0') {
559 j = 0;
560 while (delim[j] != '\0') {
561 if ((*stringp)[i] == delim[j]) {
562 gotMatch = TRUE;
563 (*stringp)[i] = '\0';
564 *stringp = *stringp + i + 1;
565 break;
566 }
567 j++;
568 }
569 if (gotMatch)
570 break;
571
572 i++;
573 }
574
575 if (!gotMatch)
576 *stringp = NULL;
577
578 return orig;
579}
580
581int poll(struct pollfd fds[], nfds_t nfds, int timeout)
582{
583 struct timeval tv;
584 struct timeval *to = NULL;
585 fd_set readfds, writefds, exceptfds;
586 int i;
587 int rc;
588
589 if (timeout != -1)
f9a58c2a 590 to = &tv;
9277ec14
BC
591
592 to->tv_sec = timeout / 1000;
593 to->tv_usec = (timeout % 1000) * 1000;
594
595 FD_ZERO(&readfds);
596 FD_ZERO(&writefds);
597 FD_ZERO(&exceptfds);
598
599 for (i = 0; i < nfds; i++)
600 {
601 if (fds[i].fd < 0) {
602 fds[i].revents = 0;
603 continue;
604 }
605
606 if (fds[i].events & POLLIN)
607 FD_SET(fds[i].fd, &readfds);
608
609 if (fds[i].events & POLLOUT)
610 FD_SET(fds[i].fd, &writefds);
611
f9a58c2a 612 FD_SET(fds[i].fd, &exceptfds);
9277ec14
BC
613 }
614
615 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
616
617 if (rc != SOCKET_ERROR) {
618 for (i = 0; i < nfds; i++)
619 {
620 if (fds[i].fd < 0) {
621 continue;
622 }
623
624 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
625 fds[i].revents |= POLLIN;
626
627 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
628 fds[i].revents |= POLLOUT;
629
630 if (FD_ISSET(fds[i].fd, &exceptfds))
631 fds[i].revents |= POLLHUP;
632 }
633 }
634
635 return rc;
636}
637
638int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
639{
21c75387
BC
640 struct timeval tv;
641 DWORD ms_remaining;
642 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
643
644 if (ms_total == 0)
645 ms_total = 1;
646
647 ms_remaining = ms_total;
648
649 /* Since Sleep() can sleep for less than the requested time, add a loop to
650 ensure we only return after the requested length of time has elapsed */
651 do {
652 fio_gettime(&tv, NULL);
653 Sleep(ms_remaining);
654 ms_remaining = ms_total - mtime_since_now(&tv);
655 } while (ms_remaining > 0 && ms_remaining < ms_total);
656
657 /* this implementation will never sleep for less than the requested time */
658 if (rmtp != NULL) {
659 rmtp->tv_sec = 0;
660 rmtp->tv_nsec = 0;
661 }
662
663 return 0;
9277ec14
BC
664}
665
666DIR *opendir(const char *dirname)
667{
668 log_err("%s is not implemented\n", __func__);
669 errno = ENOSYS;
670 return NULL;
671}
672
673int closedir(DIR *dirp)
674{
675 log_err("%s is not implemented\n", __func__);
676 errno = ENOSYS;
677 return -1;
678}
679
680struct dirent *readdir(DIR *dirp)
681{
682 log_err("%s is not implemented\n", __func__);
683 errno = ENOSYS;
684 return NULL;
685}
686
687uid_t geteuid(void)
688{
689 log_err("%s is not implemented\n", __func__);
690 errno = ENOSYS;
691 return -1;
692}
693
694int inet_aton(char *addr)
695{
696 log_err("%s is not implemented\n", __func__);
697 errno = ENOSYS;
698 return 0;
699}
700
701const char* inet_ntop(int af, const void *restrict src,
702 char *restrict dst, socklen_t size)
703{
704 INT status = SOCKET_ERROR;
705 WSADATA wsd;
706 char *ret = NULL;
707
708 if (af != AF_INET && af != AF_INET6) {
709 errno = EAFNOSUPPORT;
710 return NULL;
711 }
712
713 WSAStartup(MAKEWORD(2,2), &wsd);
714
715 if (af == AF_INET) {
716 struct sockaddr_in si;
717 DWORD len = size;
718 memset(&si, 0, sizeof(si));
719 si.sin_family = af;
720 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
721 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
722 } else if (af == AF_INET6) {
723 struct sockaddr_in6 si6;
724 DWORD len = size;
725 memset(&si6, 0, sizeof(si6));
726 si6.sin6_family = af;
727 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
728 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
729 }
730
731 if (status != SOCKET_ERROR)
732 ret = dst;
733 else
734 errno = ENOSPC;
735
736 WSACleanup();
737 return ret;
738}
739
740int inet_pton(int af, const char *restrict src, void *restrict dst)
741{
742 INT status = SOCKET_ERROR;
743 WSADATA wsd;
744 int ret = 1;
745
746 if (af != AF_INET && af != AF_INET6) {
747 errno = EAFNOSUPPORT;
748 return -1;
749 }
750
751 WSAStartup(MAKEWORD(2,2), &wsd);
752
753 if (af == AF_INET) {
754 struct sockaddr_in si;
755 INT len = sizeof(si);
756 memset(&si, 0, sizeof(si));
757 si.sin_family = af;
758 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
759 if (status != SOCKET_ERROR)
760 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
761 } else if (af == AF_INET6) {
762 struct sockaddr_in6 si6;
763 INT len = sizeof(si6);
764 memset(&si6, 0, sizeof(si6));
765 si6.sin6_family = af;
766 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
767 if (status != SOCKET_ERROR)
768 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
769 }
770
771 if (status == SOCKET_ERROR) {
772 errno = ENOSPC;
773 ret = 0;
774 }
775
776 WSACleanup();
777
778 return ret;
779}