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