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