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