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 GetNumLogicalProcessors(void)
48 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *processor_info = NULL;
50 DWORD num_processors = 0;
54 while (!GetLogicalProcessorInformation(processor_info, &len)) {
55 error = GetLastError();
56 if (error == ERROR_INSUFFICIENT_BUFFER)
57 processor_info = malloc(len);
59 log_err("Error: GetLogicalProcessorInformation failed: %d\n", error);
63 if (processor_info == NULL) {
64 log_err("Error: failed to allocate memory for GetLogicalProcessorInformation");
69 for (i = 0; i < len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); i++)
71 if (processor_info[i].Relationship == RelationProcessorCore)
72 num_processors += hweight64(processor_info[i].ProcessorMask);
76 return num_processors;
79 long sysconf(int name)
83 MEMORYSTATUSEX status;
87 case _SC_NPROCESSORS_ONLN:
88 val = GetNumLogicalProcessors();
90 log_err("_SC_NPROCESSORS_ONLN failed\n");
95 GetSystemInfo(&sysInfo);
96 val = sysInfo.dwPageSize;
100 status.dwLength = sizeof(status);
101 GlobalMemoryStatusEx(&status);
102 val = status.ullTotalPhys;
105 log_err("sysconf(%d) is not implemented\n", name);
112 char *dl_error = NULL;
114 int dlclose(void *handle)
116 return !FreeLibrary((HMODULE)handle);
119 void *dlopen(const char *file, int mode)
123 hMod = LoadLibrary(file);
124 if (hMod == INVALID_HANDLE_VALUE)
125 dl_error = (char*)"LoadLibrary failed";
132 void *dlsym(void *handle, const char *name)
136 fnPtr = GetProcAddress((HMODULE)handle, name);
138 dl_error = (char*)"GetProcAddress failed";
150 int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
153 uint64_t unix_time, windows_time;
154 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
156 /* Ignore the timezone parameter */
160 * Windows time is stored as the number 100 ns intervals since January 1 1601.
161 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
162 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
164 GetSystemTimeAsFileTime(&fileTime);
165 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
166 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
167 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
168 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
169 tp->tv_sec = unix_time / 1000;
170 tp->tv_usec = (unix_time % 1000) * 1000;
174 int sigaction(int sig, const struct sigaction *act,
175 struct sigaction *oact)
178 void (*prev_handler)(int);
180 prev_handler = signal(sig, act->sa_handler);
182 oact->sa_handler = prev_handler;
184 if (prev_handler == SIG_ERR)
190 int lstat(const char * path, struct stat * buf)
192 return stat(path, buf);
195 void *mmap(void *addr, size_t len, int prot, int flags,
196 int fildes, off_t off)
199 void* allocAddr = NULL;
201 if (prot & PROT_NONE)
202 vaProt |= PAGE_NOACCESS;
204 if ((prot & PROT_READ) && !(prot & PROT_WRITE))
205 vaProt |= PAGE_READONLY;
207 if (prot & PROT_WRITE)
208 vaProt |= PAGE_READWRITE;
210 if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
212 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
218 int munmap(void *addr, size_t len)
220 return !VirtualFree(addr, 0, MEM_RELEASE);
225 log_err("%s is not implemented\n", __func__);
232 log_err("%s is not implemented\n", __func__);
237 static HANDLE log_file = INVALID_HANDLE_VALUE;
239 void openlog(const char *ident, int logopt, int facility)
241 if (log_file == INVALID_HANDLE_VALUE)
242 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
247 CloseHandle(log_file);
248 log_file = INVALID_HANDLE_VALUE;
251 void syslog(int priority, const char *message, ... /* argument */)
258 if (log_file == INVALID_HANDLE_VALUE) {
259 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
262 if (log_file == INVALID_HANDLE_VALUE) {
263 log_err("syslog: failed to open log file\n");
267 va_start(v, message);
268 len = _vscprintf(message, v);
269 output = malloc(len + sizeof(char));
270 vsprintf(output, message, v);
271 WriteFile(log_file, output, len, &bytes_written, NULL);
276 int kill(pid_t pid, int sig)
283 * This is assumed to be used only by the network code,
284 * and so doesn't try and handle any of the other cases
286 int fcntl(int fildes, int cmd, ...)
289 * non-blocking mode doesn't work the same as in BSD sockets,
294 int val, opt, status;
298 else if (cmd != F_SETFL) {
305 opt = va_arg(ap, int);
306 if (opt & O_NONBLOCK)
311 status = ioctlsocket((SOCKET)fildes, opt, &val);
313 if (status == SOCKET_ERROR) {
326 * Get the value of a local clock source.
327 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
328 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
330 int clock_gettime(clockid_t clock_id, struct timespec *tp)
334 if (clock_id == CLOCK_MONOTONIC)
336 static LARGE_INTEGER freq = {{0,0}};
337 LARGE_INTEGER counts;
339 QueryPerformanceCounter(&counts);
340 if (freq.QuadPart == 0)
341 QueryPerformanceFrequency(&freq);
343 tp->tv_sec = counts.QuadPart / freq.QuadPart;
344 /* Get the difference between the number of ns stored
345 * in 'tv_sec' and that stored in 'counts' */
346 uint64_t t = tp->tv_sec * freq.QuadPart;
347 t = counts.QuadPart - t;
348 /* 't' now contains the number of cycles since the last second.
349 * We want the number of nanoseconds, so multiply out by 1,000,000,000
350 * and then divide by the frequency. */
352 tp->tv_nsec = t / freq.QuadPart;
354 else if (clock_id == CLOCK_REALTIME)
356 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
357 * higher-precision field. */
359 gettimeofday(&tv, NULL);
360 tp->tv_sec = tv.tv_sec;
361 tp->tv_nsec = tv.tv_usec * 1000;
370 int mlock(const void * addr, size_t len)
372 return !VirtualLock((LPVOID)addr, len);
375 int munlock(const void * addr, size_t len)
377 return !VirtualUnlock((LPVOID)addr, len);
380 pid_t waitpid(pid_t pid, int *stat_loc, int options)
382 log_err("%s is not implemented\n", __func__);
387 int usleep(useconds_t useconds)
389 Sleep(useconds / 1000);
393 char *basename(char *path)
395 static char name[MAX_PATH];
398 if (path == NULL || strlen(path) == 0)
401 i = strlen(path) - 1;
403 while (path[i] != '\\' && path[i] != '/' && i >= 0)
406 strncpy(name, path + i + 1, MAX_PATH);
411 int posix_fallocate(int fd, off_t offset, off_t len)
413 const int BUFFER_SIZE = 256 * 1024;
416 unsigned int write_len;
417 unsigned int bytes_written;
418 off_t bytes_remaining = len;
420 if (len == 0 || offset < 0)
423 buf = malloc(BUFFER_SIZE);
428 memset(buf, 0, BUFFER_SIZE);
430 int64_t prev_pos = _telli64(fd);
432 if (_lseeki64(fd, offset, SEEK_SET) == -1)
435 while (bytes_remaining > 0) {
436 if (bytes_remaining < BUFFER_SIZE)
437 write_len = (unsigned int)bytes_remaining;
439 write_len = BUFFER_SIZE;
441 bytes_written = _write(fd, buf, write_len);
442 if (bytes_written == -1) {
447 /* Don't allow Windows to cache the write: flush it to disk */
450 bytes_remaining -= bytes_written;
454 _lseeki64(fd, prev_pos, SEEK_SET);
458 int ftruncate(int fildes, off_t length)
461 int64_t prev_pos = _telli64(fildes);
462 _lseeki64(fildes, length, SEEK_SET);
463 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
464 bSuccess = SetEndOfFile(hFile);
465 _lseeki64(fildes, prev_pos, SEEK_SET);
469 int fsync(int fildes)
471 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
472 return !FlushFileBuffers(hFile);
475 int nFileMappings = 0;
476 HANDLE fileMappings[1024];
478 int shmget(key_t key, size_t size, int shmflg)
481 uint32_t size_low = size & 0xFFFFFFFF;
482 uint32_t size_high = ((uint64_t)size) >> 32;
483 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
484 if (hMapping != NULL) {
485 fileMappings[nFileMappings] = hMapping;
486 mapid = nFileMappings;
495 void *shmat(int shmid, const void *shmaddr, int shmflg)
498 MEMORY_BASIC_INFORMATION memInfo;
499 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
500 VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
501 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
505 int shmdt(const void *shmaddr)
507 return !UnmapViewOfFile(shmaddr);
510 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
512 if (cmd == IPC_RMID) {
513 fileMappings[shmid] = INVALID_HANDLE_VALUE;
516 log_err("%s is not implemented\n", __func__);
521 int setuid(uid_t uid)
523 log_err("%s is not implemented\n", __func__);
528 int setgid(gid_t gid)
530 log_err("%s is not implemented\n", __func__);
545 int getrusage(int who, struct rusage *r_usage)
547 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
548 FILETIME cTime, eTime, kTime, uTime;
552 memset(r_usage, 0, sizeof(*r_usage));
554 if (who == RUSAGE_SELF) {
555 h = GetCurrentProcess();
556 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
557 } else if (who == RUSAGE_THREAD) {
558 h = GetCurrentThread();
559 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
561 log_err("fio: getrusage %d is not implemented\n", who);
565 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
566 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
568 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
569 r_usage->ru_utime.tv_sec = time;
570 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
571 r_usage->ru_utime.tv_usec = 0;
572 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
573 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
575 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
576 r_usage->ru_stime.tv_sec = time;
577 r_usage->ru_stime.tv_usec = 0;
581 int posix_fadvise(int fd, off_t offset, off_t len, int advice)
586 int posix_madvise(void *addr, size_t len, int advice)
588 log_err("%s is not implemented\n", __func__);
592 /* Windows doesn't support advice for memory pages. Just ignore it. */
593 int msync(void *addr, size_t len, int flags)
599 int fdatasync(int fildes)
601 return fsync(fildes);
604 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
607 int64_t pos = _telli64(fildes);
608 ssize_t len = _write(fildes, buf, nbyte);
609 _lseeki64(fildes, pos, SEEK_SET);
613 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
615 int64_t pos = _telli64(fildes);
616 ssize_t len = read(fildes, buf, nbyte);
617 _lseeki64(fildes, pos, SEEK_SET);
621 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
623 log_err("%s is not implemented\n", __func__);
628 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
630 log_err("%s is not implemented\n", __func__);
635 long long strtoll(const char *restrict str, char **restrict endptr,
638 return _strtoi64(str, endptr, base);
641 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
644 struct timeval *to = NULL;
645 fd_set readfds, writefds, exceptfds;
651 to->tv_sec = timeout / 1000;
652 to->tv_usec = (timeout % 1000) * 1000;
659 for (i = 0; i < nfds; i++)
666 if (fds[i].events & POLLIN)
667 FD_SET(fds[i].fd, &readfds);
669 if (fds[i].events & POLLOUT)
670 FD_SET(fds[i].fd, &writefds);
672 FD_SET(fds[i].fd, &exceptfds);
675 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
677 if (rc != SOCKET_ERROR) {
678 for (i = 0; i < nfds; i++)
684 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
685 fds[i].revents |= POLLIN;
687 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
688 fds[i].revents |= POLLOUT;
690 if (FD_ISSET(fds[i].fd, &exceptfds))
691 fds[i].revents |= POLLHUP;
698 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
702 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
707 ms_remaining = ms_total;
709 /* Since Sleep() can sleep for less than the requested time, add a loop to
710 ensure we only return after the requested length of time has elapsed */
712 fio_gettime(&tv, NULL);
714 ms_remaining = ms_total - mtime_since_now(&tv);
715 } while (ms_remaining > 0 && ms_remaining < ms_total);
717 /* this implementation will never sleep for less than the requested time */
726 DIR *opendir(const char *dirname)
728 struct dirent_ctx *dc = NULL;
730 /* See if we can open it. If not, we'll return an error here */
731 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
732 if (file != INVALID_HANDLE_VALUE) {
734 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
735 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
736 dc->find_handle = INVALID_HANDLE_VALUE;
738 DWORD error = GetLastError();
739 if (error == ERROR_FILE_NOT_FOUND)
742 else if (error == ERROR_PATH_NOT_FOUND)
744 else if (error == ERROR_TOO_MANY_OPEN_FILES)
746 else if (error == ERROR_ACCESS_DENIED)
755 int closedir(DIR *dirp)
757 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
758 FindClose(dirp->find_handle);
764 struct dirent *readdir(DIR *dirp)
766 static struct dirent de;
767 WIN32_FIND_DATA find_data;
772 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
773 char search_pattern[MAX_PATH];
774 StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
775 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
776 if (dirp->find_handle == INVALID_HANDLE_VALUE)
779 if (!FindNextFile(dirp->find_handle, &find_data))
783 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
791 log_err("%s is not implemented\n", __func__);
796 const char* inet_ntop(int af, const void *restrict src,
797 char *restrict dst, socklen_t size)
799 INT status = SOCKET_ERROR;
803 if (af != AF_INET && af != AF_INET6) {
804 errno = EAFNOSUPPORT;
808 WSAStartup(MAKEWORD(2,2), &wsd);
811 struct sockaddr_in si;
813 memset(&si, 0, sizeof(si));
815 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
816 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
817 } else if (af == AF_INET6) {
818 struct sockaddr_in6 si6;
820 memset(&si6, 0, sizeof(si6));
821 si6.sin6_family = af;
822 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
823 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
826 if (status != SOCKET_ERROR)
836 int inet_pton(int af, const char *restrict src, void *restrict dst)
838 INT status = SOCKET_ERROR;
842 if (af != AF_INET && af != AF_INET6) {
843 errno = EAFNOSUPPORT;
847 WSAStartup(MAKEWORD(2,2), &wsd);
850 struct sockaddr_in si;
851 INT len = sizeof(si);
852 memset(&si, 0, sizeof(si));
854 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
855 if (status != SOCKET_ERROR)
856 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
857 } else if (af == AF_INET6) {
858 struct sockaddr_in6 si6;
859 INT len = sizeof(si6);
860 memset(&si6, 0, sizeof(si6));
861 si6.sin6_family = af;
862 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
863 if (status != SOCKET_ERROR)
864 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
867 if (status == SOCKET_ERROR) {