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)
84 MEMORYSTATUSEX status;
88 case _SC_NPROCESSORS_ONLN:
89 val = GetNumLogicalProcessors();
91 log_err("sysconf(_SC_NPROCESSORS_ONLN) failed\n");
96 GetSystemInfo(&sysInfo);
97 val = sysInfo.dwPageSize;
101 status.dwLength = sizeof(status);
102 val2 = sysconf(_SC_PAGESIZE);
103 if (GlobalMemoryStatusEx(&status) && val2 != -1)
104 val = status.ullTotalPhys / val2;
106 log_err("sysconf(_SC_PHYS_PAGES) failed\n");
109 log_err("sysconf(%d) is not implemented\n", name);
116 char *dl_error = NULL;
118 int dlclose(void *handle)
120 return !FreeLibrary((HMODULE)handle);
123 void *dlopen(const char *file, int mode)
127 hMod = LoadLibrary(file);
128 if (hMod == INVALID_HANDLE_VALUE)
129 dl_error = (char*)"LoadLibrary failed";
136 void *dlsym(void *handle, const char *name)
140 fnPtr = GetProcAddress((HMODULE)handle, name);
142 dl_error = (char*)"GetProcAddress failed";
154 int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
157 uint64_t unix_time, windows_time;
158 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
160 /* Ignore the timezone parameter */
164 * Windows time is stored as the number 100 ns intervals since January 1 1601.
165 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
166 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
168 GetSystemTimeAsFileTime(&fileTime);
169 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
170 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
171 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
172 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
173 tp->tv_sec = unix_time / 1000;
174 tp->tv_usec = (unix_time % 1000) * 1000;
178 int sigaction(int sig, const struct sigaction *act,
179 struct sigaction *oact)
182 void (*prev_handler)(int);
184 prev_handler = signal(sig, act->sa_handler);
186 oact->sa_handler = prev_handler;
188 if (prev_handler == SIG_ERR)
194 int lstat(const char * path, struct stat * buf)
196 return stat(path, buf);
199 void *mmap(void *addr, size_t len, int prot, int flags,
200 int fildes, off_t off)
203 void* allocAddr = NULL;
205 if (prot & PROT_NONE)
206 vaProt |= PAGE_NOACCESS;
208 if ((prot & PROT_READ) && !(prot & PROT_WRITE))
209 vaProt |= PAGE_READONLY;
211 if (prot & PROT_WRITE)
212 vaProt |= PAGE_READWRITE;
214 if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
216 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
222 int munmap(void *addr, size_t len)
224 return !VirtualFree(addr, 0, MEM_RELEASE);
229 log_err("%s is not implemented\n", __func__);
236 log_err("%s is not implemented\n", __func__);
241 static HANDLE log_file = INVALID_HANDLE_VALUE;
243 void openlog(const char *ident, int logopt, int facility)
245 if (log_file == INVALID_HANDLE_VALUE)
246 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
251 CloseHandle(log_file);
252 log_file = INVALID_HANDLE_VALUE;
255 void syslog(int priority, const char *message, ... /* argument */)
262 if (log_file == INVALID_HANDLE_VALUE) {
263 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
266 if (log_file == INVALID_HANDLE_VALUE) {
267 log_err("syslog: failed to open log file\n");
271 va_start(v, message);
272 len = _vscprintf(message, v);
273 output = malloc(len + sizeof(char));
274 vsprintf(output, message, v);
275 WriteFile(log_file, output, len, &bytes_written, NULL);
280 int kill(pid_t pid, int sig)
287 * This is assumed to be used only by the network code,
288 * and so doesn't try and handle any of the other cases
290 int fcntl(int fildes, int cmd, ...)
293 * non-blocking mode doesn't work the same as in BSD sockets,
298 int val, opt, status;
302 else if (cmd != F_SETFL) {
309 opt = va_arg(ap, int);
310 if (opt & O_NONBLOCK)
315 status = ioctlsocket((SOCKET)fildes, opt, &val);
317 if (status == SOCKET_ERROR) {
330 * Get the value of a local clock source.
331 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
332 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
334 int clock_gettime(clockid_t clock_id, struct timespec *tp)
338 if (clock_id == CLOCK_MONOTONIC)
340 static LARGE_INTEGER freq = {{0,0}};
341 LARGE_INTEGER counts;
343 QueryPerformanceCounter(&counts);
344 if (freq.QuadPart == 0)
345 QueryPerformanceFrequency(&freq);
347 tp->tv_sec = counts.QuadPart / freq.QuadPart;
348 /* Get the difference between the number of ns stored
349 * in 'tv_sec' and that stored in 'counts' */
350 uint64_t t = tp->tv_sec * freq.QuadPart;
351 t = counts.QuadPart - t;
352 /* 't' now contains the number of cycles since the last second.
353 * We want the number of nanoseconds, so multiply out by 1,000,000,000
354 * and then divide by the frequency. */
356 tp->tv_nsec = t / freq.QuadPart;
358 else if (clock_id == CLOCK_REALTIME)
360 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
361 * higher-precision field. */
363 gettimeofday(&tv, NULL);
364 tp->tv_sec = tv.tv_sec;
365 tp->tv_nsec = tv.tv_usec * 1000;
374 int mlock(const void * addr, size_t len)
376 return !VirtualLock((LPVOID)addr, len);
379 int munlock(const void * addr, size_t len)
381 return !VirtualUnlock((LPVOID)addr, len);
384 pid_t waitpid(pid_t pid, int *stat_loc, int options)
386 log_err("%s is not implemented\n", __func__);
391 int usleep(useconds_t useconds)
393 Sleep(useconds / 1000);
397 char *basename(char *path)
399 static char name[MAX_PATH];
402 if (path == NULL || strlen(path) == 0)
405 i = strlen(path) - 1;
407 while (path[i] != '\\' && path[i] != '/' && i >= 0)
410 strncpy(name, path + i + 1, MAX_PATH);
415 int ftruncate(int fildes, off_t length)
418 int64_t prev_pos = _telli64(fildes);
419 _lseeki64(fildes, length, SEEK_SET);
420 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
421 bSuccess = SetEndOfFile(hFile);
422 _lseeki64(fildes, prev_pos, SEEK_SET);
426 int fsync(int fildes)
428 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
429 return !FlushFileBuffers(hFile);
432 int nFileMappings = 0;
433 HANDLE fileMappings[1024];
435 int shmget(key_t key, size_t size, int shmflg)
438 uint32_t size_low = size & 0xFFFFFFFF;
439 uint32_t size_high = ((uint64_t)size) >> 32;
440 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
441 if (hMapping != NULL) {
442 fileMappings[nFileMappings] = hMapping;
443 mapid = nFileMappings;
452 void *shmat(int shmid, const void *shmaddr, int shmflg)
455 MEMORY_BASIC_INFORMATION memInfo;
456 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
457 VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
458 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
462 int shmdt(const void *shmaddr)
464 return !UnmapViewOfFile(shmaddr);
467 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
469 if (cmd == IPC_RMID) {
470 fileMappings[shmid] = INVALID_HANDLE_VALUE;
473 log_err("%s is not implemented\n", __func__);
478 int setuid(uid_t uid)
480 log_err("%s is not implemented\n", __func__);
485 int setgid(gid_t gid)
487 log_err("%s is not implemented\n", __func__);
502 int getrusage(int who, struct rusage *r_usage)
504 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
505 FILETIME cTime, eTime, kTime, uTime;
509 memset(r_usage, 0, sizeof(*r_usage));
511 if (who == RUSAGE_SELF) {
512 h = GetCurrentProcess();
513 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
514 } else if (who == RUSAGE_THREAD) {
515 h = GetCurrentThread();
516 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
518 log_err("fio: getrusage %d is not implemented\n", who);
522 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
523 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
525 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
526 r_usage->ru_utime.tv_sec = time;
527 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
528 r_usage->ru_utime.tv_usec = 0;
529 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
530 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
532 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
533 r_usage->ru_stime.tv_sec = time;
534 r_usage->ru_stime.tv_usec = 0;
538 int posix_fadvise(int fd, off_t offset, off_t len, int advice)
543 int posix_madvise(void *addr, size_t len, int advice)
545 log_err("%s is not implemented\n", __func__);
549 /* Windows doesn't support advice for memory pages. Just ignore it. */
550 int msync(void *addr, size_t len, int flags)
556 int fdatasync(int fildes)
558 return fsync(fildes);
561 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
564 int64_t pos = _telli64(fildes);
565 ssize_t len = _write(fildes, buf, nbyte);
566 _lseeki64(fildes, pos, SEEK_SET);
570 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
572 int64_t pos = _telli64(fildes);
573 ssize_t len = read(fildes, buf, nbyte);
574 _lseeki64(fildes, pos, SEEK_SET);
578 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
580 log_err("%s is not implemented\n", __func__);
585 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
587 log_err("%s is not implemented\n", __func__);
592 long long strtoll(const char *restrict str, char **restrict endptr,
595 return _strtoi64(str, endptr, base);
598 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
601 struct timeval *to = NULL;
602 fd_set readfds, writefds, exceptfds;
608 to->tv_sec = timeout / 1000;
609 to->tv_usec = (timeout % 1000) * 1000;
616 for (i = 0; i < nfds; i++)
623 if (fds[i].events & POLLIN)
624 FD_SET(fds[i].fd, &readfds);
626 if (fds[i].events & POLLOUT)
627 FD_SET(fds[i].fd, &writefds);
629 FD_SET(fds[i].fd, &exceptfds);
632 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
634 if (rc != SOCKET_ERROR) {
635 for (i = 0; i < nfds; i++)
641 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
642 fds[i].revents |= POLLIN;
644 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
645 fds[i].revents |= POLLOUT;
647 if (FD_ISSET(fds[i].fd, &exceptfds))
648 fds[i].revents |= POLLHUP;
655 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
659 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
664 ms_remaining = ms_total;
666 /* Since Sleep() can sleep for less than the requested time, add a loop to
667 ensure we only return after the requested length of time has elapsed */
669 fio_gettime(&tv, NULL);
671 ms_remaining = ms_total - mtime_since_now(&tv);
672 } while (ms_remaining > 0 && ms_remaining < ms_total);
674 /* this implementation will never sleep for less than the requested time */
683 DIR *opendir(const char *dirname)
685 struct dirent_ctx *dc = NULL;
687 /* See if we can open it. If not, we'll return an error here */
688 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
689 if (file != INVALID_HANDLE_VALUE) {
691 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
692 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
693 dc->find_handle = INVALID_HANDLE_VALUE;
695 DWORD error = GetLastError();
696 if (error == ERROR_FILE_NOT_FOUND)
699 else if (error == ERROR_PATH_NOT_FOUND)
701 else if (error == ERROR_TOO_MANY_OPEN_FILES)
703 else if (error == ERROR_ACCESS_DENIED)
712 int closedir(DIR *dirp)
714 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
715 FindClose(dirp->find_handle);
721 struct dirent *readdir(DIR *dirp)
723 static struct dirent de;
724 WIN32_FIND_DATA find_data;
729 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
730 char search_pattern[MAX_PATH];
731 StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
732 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
733 if (dirp->find_handle == INVALID_HANDLE_VALUE)
736 if (!FindNextFile(dirp->find_handle, &find_data))
740 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
748 log_err("%s is not implemented\n", __func__);
753 const char* inet_ntop(int af, const void *restrict src,
754 char *restrict dst, socklen_t size)
756 INT status = SOCKET_ERROR;
760 if (af != AF_INET && af != AF_INET6) {
761 errno = EAFNOSUPPORT;
765 WSAStartup(MAKEWORD(2,2), &wsd);
768 struct sockaddr_in si;
770 memset(&si, 0, sizeof(si));
772 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
773 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
774 } else if (af == AF_INET6) {
775 struct sockaddr_in6 si6;
777 memset(&si6, 0, sizeof(si6));
778 si6.sin6_family = af;
779 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
780 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
783 if (status != SOCKET_ERROR)
793 int inet_pton(int af, const char *restrict src, void *restrict dst)
795 INT status = SOCKET_ERROR;
799 if (af != AF_INET && af != AF_INET6) {
800 errno = EAFNOSUPPORT;
804 WSAStartup(MAKEWORD(2,2), &wsd);
807 struct sockaddr_in si;
808 INT len = sizeof(si);
809 memset(&si, 0, sizeof(si));
811 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
812 if (status != SOCKET_ERROR)
813 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
814 } else if (af == AF_INET6) {
815 struct sockaddr_in6 si6;
816 INT len = sizeof(si6);
817 memset(&si6, 0, sizeof(si6));
818 si6.sin6_family = af;
819 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
820 if (status != SOCKET_ERROR)
821 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
824 if (status == SOCKET_ERROR) {