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.
7 #include <netinet/in.h>
15 #include <semaphore.h>
19 #include <sys/resource.h>
22 #include "../os-windows.h"
23 #include "../../lib/hweight.h"
25 extern unsigned long mtime_since_now(struct timeval *);
26 extern void fio_gettime(struct timeval *, void *);
28 /* These aren't defined in the MinGW headers */
29 HRESULT WINAPI StringCchCopyA(
34 HRESULT WINAPI StringCchPrintfA(
37 const char *pszFormat,
42 size_t numberOfElements,
46 int win_to_posix_error(DWORD winerr)
50 case ERROR_FILE_NOT_FOUND: return ENOENT;
51 case ERROR_PATH_NOT_FOUND: return ENOENT;
52 case ERROR_ACCESS_DENIED: return EACCES;
53 case ERROR_INVALID_HANDLE: return EBADF;
54 case ERROR_NOT_ENOUGH_MEMORY: return ENOMEM;
55 case ERROR_INVALID_DATA: return EINVAL;
56 case ERROR_OUTOFMEMORY: return ENOMEM;
57 case ERROR_INVALID_DRIVE: return ENODEV;
58 case ERROR_NOT_SAME_DEVICE: return EXDEV;
59 case ERROR_WRITE_PROTECT: return EROFS;
60 case ERROR_BAD_UNIT: return ENODEV;
61 case ERROR_SHARING_VIOLATION: return EACCES;
62 case ERROR_LOCK_VIOLATION: return EACCES;
63 case ERROR_SHARING_BUFFER_EXCEEDED: return ENOLCK;
64 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
65 case ERROR_NOT_SUPPORTED: return ENOSYS;
66 case ERROR_FILE_EXISTS: return EEXIST;
67 case ERROR_CANNOT_MAKE: return EPERM;
68 case ERROR_INVALID_PARAMETER: return EINVAL;
69 case ERROR_NO_PROC_SLOTS: return EAGAIN;
70 case ERROR_BROKEN_PIPE: return EPIPE;
71 case ERROR_OPEN_FAILED: return EIO;
72 case ERROR_NO_MORE_SEARCH_HANDLES: return ENFILE;
73 case ERROR_CALL_NOT_IMPLEMENTED: return ENOSYS;
74 case ERROR_INVALID_NAME: return ENOENT;
75 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
76 case ERROR_CHILD_NOT_COMPLETE: return EBUSY;
77 case ERROR_DIR_NOT_EMPTY: return ENOTEMPTY;
78 case ERROR_SIGNAL_REFUSED: return EIO;
79 case ERROR_BAD_PATHNAME: return ENOENT;
80 case ERROR_SIGNAL_PENDING: return EBUSY;
81 case ERROR_MAX_THRDS_REACHED: return EAGAIN;
82 case ERROR_BUSY: return EBUSY;
83 case ERROR_ALREADY_EXISTS: return EEXIST;
84 case ERROR_NO_SIGNAL_SENT: return EIO;
85 case ERROR_FILENAME_EXCED_RANGE: return EINVAL;
86 case ERROR_META_EXPANSION_TOO_LONG: return EINVAL;
87 case ERROR_INVALID_SIGNAL_NUMBER: return EINVAL;
88 case ERROR_THREAD_1_INACTIVE: return EINVAL;
89 case ERROR_BAD_PIPE: return EINVAL;
90 case ERROR_PIPE_BUSY: return EBUSY;
91 case ERROR_NO_DATA: return EPIPE;
92 case ERROR_MORE_DATA: return EAGAIN;
93 case ERROR_DIRECTORY: return ENOTDIR;
94 case ERROR_PIPE_CONNECTED: return EBUSY;
95 case ERROR_NO_TOKEN: return EINVAL;
96 case ERROR_PROCESS_ABORTED: return EFAULT;
97 case ERROR_BAD_DEVICE: return ENODEV;
98 case ERROR_BAD_USERNAME: return EINVAL;
99 case ERROR_OPEN_FILES: return EAGAIN;
100 case ERROR_ACTIVE_CONNECTIONS: return EAGAIN;
101 case ERROR_DEVICE_IN_USE: return EAGAIN;
102 case ERROR_INVALID_AT_INTERRUPT_TIME: return EINTR;
103 case ERROR_IO_DEVICE: return EIO;
104 case ERROR_NOT_OWNER: return EPERM;
105 case ERROR_END_OF_MEDIA: return ENOSPC;
106 case ERROR_EOM_OVERFLOW: return ENOSPC;
107 case ERROR_BEGINNING_OF_MEDIA: return ESPIPE;
108 case ERROR_SETMARK_DETECTED: return ESPIPE;
109 case ERROR_NO_DATA_DETECTED: return ENOSPC;
110 case ERROR_POSSIBLE_DEADLOCK: return EDEADLOCK;
111 case ERROR_CRC: return EIO;
112 case ERROR_NEGATIVE_SEEK: return EINVAL;
113 case ERROR_DISK_FULL: return ENOSPC;
114 case ERROR_NOACCESS: return EFAULT;
115 case ERROR_FILE_INVALID: return ENXIO;
121 int GetNumLogicalProcessors(void)
123 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *processor_info = NULL;
125 DWORD num_processors = 0;
129 while (!GetLogicalProcessorInformation(processor_info, &len)) {
130 error = GetLastError();
131 if (error == ERROR_INSUFFICIENT_BUFFER)
132 processor_info = malloc(len);
134 log_err("Error: GetLogicalProcessorInformation failed: %d\n", error);
138 if (processor_info == NULL) {
139 log_err("Error: failed to allocate memory for GetLogicalProcessorInformation");
144 for (i = 0; i < len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); i++)
146 if (processor_info[i].Relationship == RelationProcessorCore)
147 num_processors += hweight64(processor_info[i].ProcessorMask);
150 free(processor_info);
151 return num_processors;
154 long sysconf(int name)
159 MEMORYSTATUSEX status;
163 case _SC_NPROCESSORS_ONLN:
164 val = GetNumLogicalProcessors();
166 log_err("sysconf(_SC_NPROCESSORS_ONLN) failed\n");
171 GetSystemInfo(&sysInfo);
172 val = sysInfo.dwPageSize;
176 status.dwLength = sizeof(status);
177 val2 = sysconf(_SC_PAGESIZE);
178 if (GlobalMemoryStatusEx(&status) && val2 != -1)
179 val = status.ullTotalPhys / val2;
181 log_err("sysconf(_SC_PHYS_PAGES) failed\n");
184 log_err("sysconf(%d) is not implemented\n", name);
191 char *dl_error = NULL;
193 int dlclose(void *handle)
195 return !FreeLibrary((HMODULE)handle);
198 void *dlopen(const char *file, int mode)
202 hMod = LoadLibrary(file);
203 if (hMod == INVALID_HANDLE_VALUE)
204 dl_error = (char*)"LoadLibrary failed";
211 void *dlsym(void *handle, const char *name)
215 fnPtr = GetProcAddress((HMODULE)handle, name);
217 dl_error = (char*)"GetProcAddress failed";
229 int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
232 uint64_t unix_time, windows_time;
233 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
235 /* Ignore the timezone parameter */
239 * Windows time is stored as the number 100 ns intervals since January 1 1601.
240 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
241 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
243 GetSystemTimeAsFileTime(&fileTime);
244 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
245 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
246 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
247 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
248 tp->tv_sec = unix_time / 1000;
249 tp->tv_usec = (unix_time % 1000) * 1000;
253 int sigaction(int sig, const struct sigaction *act,
254 struct sigaction *oact)
257 void (*prev_handler)(int);
259 prev_handler = signal(sig, act->sa_handler);
261 oact->sa_handler = prev_handler;
263 if (prev_handler == SIG_ERR)
269 int lstat(const char * path, struct stat * buf)
271 return stat(path, buf);
274 void *mmap(void *addr, size_t len, int prot, int flags,
275 int fildes, off_t off)
278 void* allocAddr = NULL;
280 if (prot & PROT_NONE)
281 vaProt |= PAGE_NOACCESS;
283 if ((prot & PROT_READ) && !(prot & PROT_WRITE))
284 vaProt |= PAGE_READONLY;
286 if (prot & PROT_WRITE)
287 vaProt |= PAGE_READWRITE;
289 if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
291 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
292 if (allocAddr == NULL)
293 errno = win_to_posix_error(GetLastError());
299 int munmap(void *addr, size_t len)
301 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
302 errno = win_to_posix_error(GetLastError());
311 log_err("%s is not implemented\n", __func__);
318 log_err("%s is not implemented\n", __func__);
323 static HANDLE log_file = INVALID_HANDLE_VALUE;
325 void openlog(const char *ident, int logopt, int facility)
327 if (log_file == INVALID_HANDLE_VALUE)
328 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
333 CloseHandle(log_file);
334 log_file = INVALID_HANDLE_VALUE;
337 void syslog(int priority, const char *message, ... /* argument */)
344 if (log_file == INVALID_HANDLE_VALUE) {
345 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
348 if (log_file == INVALID_HANDLE_VALUE) {
349 log_err("syslog: failed to open log file\n");
353 va_start(v, message);
354 len = _vscprintf(message, v);
355 output = malloc(len + sizeof(char));
356 vsprintf(output, message, v);
357 WriteFile(log_file, output, len, &bytes_written, NULL);
362 int kill(pid_t pid, int sig)
369 * This is assumed to be used only by the network code,
370 * and so doesn't try and handle any of the other cases
372 int fcntl(int fildes, int cmd, ...)
375 * non-blocking mode doesn't work the same as in BSD sockets,
380 int val, opt, status;
384 else if (cmd != F_SETFL) {
391 opt = va_arg(ap, int);
392 if (opt & O_NONBLOCK)
397 status = ioctlsocket((SOCKET)fildes, opt, &val);
399 if (status == SOCKET_ERROR) {
412 * Get the value of a local clock source.
413 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
414 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
416 int clock_gettime(clockid_t clock_id, struct timespec *tp)
420 if (clock_id == CLOCK_MONOTONIC)
422 static LARGE_INTEGER freq = {{0,0}};
423 LARGE_INTEGER counts;
426 QueryPerformanceCounter(&counts);
427 if (freq.QuadPart == 0)
428 QueryPerformanceFrequency(&freq);
430 tp->tv_sec = counts.QuadPart / freq.QuadPart;
431 /* Get the difference between the number of ns stored
432 * in 'tv_sec' and that stored in 'counts' */
433 t = tp->tv_sec * freq.QuadPart;
434 t = counts.QuadPart - t;
435 /* 't' now contains the number of cycles since the last second.
436 * We want the number of nanoseconds, so multiply out by 1,000,000,000
437 * and then divide by the frequency. */
439 tp->tv_nsec = t / freq.QuadPart;
441 else if (clock_id == CLOCK_REALTIME)
443 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
444 * higher-precision field. */
446 gettimeofday(&tv, NULL);
447 tp->tv_sec = tv.tv_sec;
448 tp->tv_nsec = tv.tv_usec * 1000;
457 int mlock(const void * addr, size_t len)
461 HANDLE process = GetCurrentProcess();
463 success = GetProcessWorkingSetSize(process, &min, &max);
465 errno = win_to_posix_error(GetLastError());
471 success = SetProcessWorkingSetSize(process, min, max);
473 errno = win_to_posix_error(GetLastError());
477 success = VirtualLock((LPVOID)addr, len);
479 errno = win_to_posix_error(GetLastError());
486 int munlock(const void * addr, size_t len)
488 BOOL success = VirtualUnlock((LPVOID)addr, len);
490 errno = win_to_posix_error(GetLastError());
497 pid_t waitpid(pid_t pid, int *stat_loc, int options)
499 log_err("%s is not implemented\n", __func__);
504 int usleep(useconds_t useconds)
506 Sleep(useconds / 1000);
510 char *basename(char *path)
512 static char name[MAX_PATH];
515 if (path == NULL || strlen(path) == 0)
518 i = strlen(path) - 1;
520 while (path[i] != '\\' && path[i] != '/' && i >= 0)
523 strncpy(name, path + i + 1, MAX_PATH);
528 int fsync(int fildes)
530 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
531 if (!FlushFileBuffers(hFile)) {
532 errno = win_to_posix_error(GetLastError());
539 int nFileMappings = 0;
540 HANDLE fileMappings[1024];
542 int shmget(key_t key, size_t size, int shmflg)
545 uint32_t size_low = size & 0xFFFFFFFF;
546 uint32_t size_high = ((uint64_t)size) >> 32;
547 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
548 if (hMapping != NULL) {
549 fileMappings[nFileMappings] = hMapping;
550 mapid = nFileMappings;
559 void *shmat(int shmid, const void *shmaddr, int shmflg)
562 MEMORY_BASIC_INFORMATION memInfo;
563 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
564 if (mapAddr == NULL) {
565 errno = win_to_posix_error(GetLastError());
569 if (VirtualQuery(mapAddr, &memInfo, sizeof(memInfo)) == 0) {
570 errno = win_to_posix_error(GetLastError());
574 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
575 if (mapAddr == NULL) {
576 errno = win_to_posix_error(GetLastError());
583 int shmdt(const void *shmaddr)
585 if (!UnmapViewOfFile(shmaddr)) {
586 errno = win_to_posix_error(GetLastError());
593 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
595 if (cmd == IPC_RMID) {
596 fileMappings[shmid] = INVALID_HANDLE_VALUE;
599 log_err("%s is not implemented\n", __func__);
605 int setuid(uid_t uid)
607 log_err("%s is not implemented\n", __func__);
612 int setgid(gid_t gid)
614 log_err("%s is not implemented\n", __func__);
629 int getrusage(int who, struct rusage *r_usage)
631 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
632 FILETIME cTime, eTime, kTime, uTime;
636 memset(r_usage, 0, sizeof(*r_usage));
638 if (who == RUSAGE_SELF) {
639 h = GetCurrentProcess();
640 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
641 } else if (who == RUSAGE_THREAD) {
642 h = GetCurrentThread();
643 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
645 log_err("fio: getrusage %d is not implemented\n", who);
649 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
650 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
652 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
653 r_usage->ru_utime.tv_sec = time;
654 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
655 r_usage->ru_utime.tv_usec = 0;
656 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
657 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
659 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
660 r_usage->ru_stime.tv_sec = time;
661 r_usage->ru_stime.tv_usec = 0;
665 int posix_madvise(void *addr, size_t len, int advice)
667 log_err("%s is not implemented\n", __func__);
671 /* Windows doesn't support advice for memory pages. Just ignore it. */
672 int msync(void *addr, size_t len, int flags)
678 int fdatasync(int fildes)
680 return fsync(fildes);
683 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
686 int64_t pos = _telli64(fildes);
687 ssize_t len = _write(fildes, buf, nbyte);
688 _lseeki64(fildes, pos, SEEK_SET);
692 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
694 int64_t pos = _telli64(fildes);
695 ssize_t len = read(fildes, buf, nbyte);
696 _lseeki64(fildes, pos, SEEK_SET);
700 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
702 log_err("%s is not implemented\n", __func__);
707 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
709 log_err("%s is not implemented\n", __func__);
714 long long strtoll(const char *restrict str, char **restrict endptr,
717 return _strtoi64(str, endptr, base);
720 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
723 struct timeval *to = NULL;
724 fd_set readfds, writefds, exceptfds;
730 to->tv_sec = timeout / 1000;
731 to->tv_usec = (timeout % 1000) * 1000;
738 for (i = 0; i < nfds; i++)
745 if (fds[i].events & POLLIN)
746 FD_SET(fds[i].fd, &readfds);
748 if (fds[i].events & POLLOUT)
749 FD_SET(fds[i].fd, &writefds);
751 FD_SET(fds[i].fd, &exceptfds);
754 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
756 if (rc != SOCKET_ERROR) {
757 for (i = 0; i < nfds; i++)
763 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
764 fds[i].revents |= POLLIN;
766 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
767 fds[i].revents |= POLLOUT;
769 if (FD_ISSET(fds[i].fd, &exceptfds))
770 fds[i].revents |= POLLHUP;
777 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
781 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
786 ms_remaining = ms_total;
788 /* Since Sleep() can sleep for less than the requested time, add a loop to
789 ensure we only return after the requested length of time has elapsed */
791 fio_gettime(&tv, NULL);
793 ms_remaining = ms_total - mtime_since_now(&tv);
794 } while (ms_remaining > 0 && ms_remaining < ms_total);
796 /* this implementation will never sleep for less than the requested time */
805 DIR *opendir(const char *dirname)
807 struct dirent_ctx *dc = NULL;
809 /* See if we can open it. If not, we'll return an error here */
810 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
811 if (file != INVALID_HANDLE_VALUE) {
813 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
814 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
815 dc->find_handle = INVALID_HANDLE_VALUE;
817 DWORD error = GetLastError();
818 if (error == ERROR_FILE_NOT_FOUND)
821 else if (error == ERROR_PATH_NOT_FOUND)
823 else if (error == ERROR_TOO_MANY_OPEN_FILES)
825 else if (error == ERROR_ACCESS_DENIED)
834 int closedir(DIR *dirp)
836 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
837 FindClose(dirp->find_handle);
843 struct dirent *readdir(DIR *dirp)
845 static struct dirent de;
846 WIN32_FIND_DATA find_data;
851 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
852 char search_pattern[MAX_PATH];
853 StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
854 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
855 if (dirp->find_handle == INVALID_HANDLE_VALUE)
858 if (!FindNextFile(dirp->find_handle, &find_data))
862 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
870 log_err("%s is not implemented\n", __func__);
875 const char* inet_ntop(int af, const void *restrict src,
876 char *restrict dst, socklen_t size)
878 INT status = SOCKET_ERROR;
882 if (af != AF_INET && af != AF_INET6) {
883 errno = EAFNOSUPPORT;
887 WSAStartup(MAKEWORD(2,2), &wsd);
890 struct sockaddr_in si;
892 memset(&si, 0, sizeof(si));
894 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
895 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
896 } else if (af == AF_INET6) {
897 struct sockaddr_in6 si6;
899 memset(&si6, 0, sizeof(si6));
900 si6.sin6_family = af;
901 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
902 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
905 if (status != SOCKET_ERROR)
915 int inet_pton(int af, const char *restrict src, void *restrict dst)
917 INT status = SOCKET_ERROR;
921 if (af != AF_INET && af != AF_INET6) {
922 errno = EAFNOSUPPORT;
926 WSAStartup(MAKEWORD(2,2), &wsd);
929 struct sockaddr_in si;
930 INT len = sizeof(si);
931 memset(&si, 0, sizeof(si));
933 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
934 if (status != SOCKET_ERROR)
935 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
936 } else if (af == AF_INET6) {
937 struct sockaddr_in6 si6;
938 INT len = sizeof(si6);
939 memset(&si6, 0, sizeof(si6));
940 si6.sin6_family = af;
941 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
942 if (status != SOCKET_ERROR)
943 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
946 if (status == SOCKET_ERROR) {