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 ftruncate(int fildes, off_t length)
414 int64_t prev_pos = _telli64(fildes);
415 _lseeki64(fildes, length, SEEK_SET);
416 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
417 bSuccess = SetEndOfFile(hFile);
418 _lseeki64(fildes, prev_pos, SEEK_SET);
422 int fsync(int fildes)
424 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
425 return !FlushFileBuffers(hFile);
428 int nFileMappings = 0;
429 HANDLE fileMappings[1024];
431 int shmget(key_t key, size_t size, int shmflg)
434 uint32_t size_low = size & 0xFFFFFFFF;
435 uint32_t size_high = ((uint64_t)size) >> 32;
436 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
437 if (hMapping != NULL) {
438 fileMappings[nFileMappings] = hMapping;
439 mapid = nFileMappings;
448 void *shmat(int shmid, const void *shmaddr, int shmflg)
451 MEMORY_BASIC_INFORMATION memInfo;
452 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
453 VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
454 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
458 int shmdt(const void *shmaddr)
460 return !UnmapViewOfFile(shmaddr);
463 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
465 if (cmd == IPC_RMID) {
466 fileMappings[shmid] = INVALID_HANDLE_VALUE;
469 log_err("%s is not implemented\n", __func__);
474 int setuid(uid_t uid)
476 log_err("%s is not implemented\n", __func__);
481 int setgid(gid_t gid)
483 log_err("%s is not implemented\n", __func__);
498 int getrusage(int who, struct rusage *r_usage)
500 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
501 FILETIME cTime, eTime, kTime, uTime;
505 memset(r_usage, 0, sizeof(*r_usage));
507 if (who == RUSAGE_SELF) {
508 h = GetCurrentProcess();
509 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
510 } else if (who == RUSAGE_THREAD) {
511 h = GetCurrentThread();
512 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
514 log_err("fio: getrusage %d is not implemented\n", who);
518 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
519 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
521 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
522 r_usage->ru_utime.tv_sec = time;
523 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
524 r_usage->ru_utime.tv_usec = 0;
525 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
526 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
528 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
529 r_usage->ru_stime.tv_sec = time;
530 r_usage->ru_stime.tv_usec = 0;
534 int posix_fadvise(int fd, off_t offset, off_t len, int advice)
539 int posix_madvise(void *addr, size_t len, int advice)
541 log_err("%s is not implemented\n", __func__);
545 /* Windows doesn't support advice for memory pages. Just ignore it. */
546 int msync(void *addr, size_t len, int flags)
552 int fdatasync(int fildes)
554 return fsync(fildes);
557 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
560 int64_t pos = _telli64(fildes);
561 ssize_t len = _write(fildes, buf, nbyte);
562 _lseeki64(fildes, pos, SEEK_SET);
566 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
568 int64_t pos = _telli64(fildes);
569 ssize_t len = read(fildes, buf, nbyte);
570 _lseeki64(fildes, pos, SEEK_SET);
574 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
576 log_err("%s is not implemented\n", __func__);
581 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
583 log_err("%s is not implemented\n", __func__);
588 long long strtoll(const char *restrict str, char **restrict endptr,
591 return _strtoi64(str, endptr, base);
594 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
597 struct timeval *to = NULL;
598 fd_set readfds, writefds, exceptfds;
604 to->tv_sec = timeout / 1000;
605 to->tv_usec = (timeout % 1000) * 1000;
612 for (i = 0; i < nfds; i++)
619 if (fds[i].events & POLLIN)
620 FD_SET(fds[i].fd, &readfds);
622 if (fds[i].events & POLLOUT)
623 FD_SET(fds[i].fd, &writefds);
625 FD_SET(fds[i].fd, &exceptfds);
628 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
630 if (rc != SOCKET_ERROR) {
631 for (i = 0; i < nfds; i++)
637 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
638 fds[i].revents |= POLLIN;
640 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
641 fds[i].revents |= POLLOUT;
643 if (FD_ISSET(fds[i].fd, &exceptfds))
644 fds[i].revents |= POLLHUP;
651 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
655 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
660 ms_remaining = ms_total;
662 /* Since Sleep() can sleep for less than the requested time, add a loop to
663 ensure we only return after the requested length of time has elapsed */
665 fio_gettime(&tv, NULL);
667 ms_remaining = ms_total - mtime_since_now(&tv);
668 } while (ms_remaining > 0 && ms_remaining < ms_total);
670 /* this implementation will never sleep for less than the requested time */
679 DIR *opendir(const char *dirname)
681 struct dirent_ctx *dc = NULL;
683 /* See if we can open it. If not, we'll return an error here */
684 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
685 if (file != INVALID_HANDLE_VALUE) {
687 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
688 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
689 dc->find_handle = INVALID_HANDLE_VALUE;
691 DWORD error = GetLastError();
692 if (error == ERROR_FILE_NOT_FOUND)
695 else if (error == ERROR_PATH_NOT_FOUND)
697 else if (error == ERROR_TOO_MANY_OPEN_FILES)
699 else if (error == ERROR_ACCESS_DENIED)
708 int closedir(DIR *dirp)
710 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
711 FindClose(dirp->find_handle);
717 struct dirent *readdir(DIR *dirp)
719 static struct dirent de;
720 WIN32_FIND_DATA find_data;
725 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
726 char search_pattern[MAX_PATH];
727 StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
728 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
729 if (dirp->find_handle == INVALID_HANDLE_VALUE)
732 if (!FindNextFile(dirp->find_handle, &find_data))
736 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
744 log_err("%s is not implemented\n", __func__);
749 const char* inet_ntop(int af, const void *restrict src,
750 char *restrict dst, socklen_t size)
752 INT status = SOCKET_ERROR;
756 if (af != AF_INET && af != AF_INET6) {
757 errno = EAFNOSUPPORT;
761 WSAStartup(MAKEWORD(2,2), &wsd);
764 struct sockaddr_in si;
766 memset(&si, 0, sizeof(si));
768 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
769 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
770 } else if (af == AF_INET6) {
771 struct sockaddr_in6 si6;
773 memset(&si6, 0, sizeof(si6));
774 si6.sin6_family = af;
775 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
776 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
779 if (status != SOCKET_ERROR)
789 int inet_pton(int af, const char *restrict src, void *restrict dst)
791 INT status = SOCKET_ERROR;
795 if (af != AF_INET && af != AF_INET6) {
796 errno = EAFNOSUPPORT;
800 WSAStartup(MAKEWORD(2,2), &wsd);
803 struct sockaddr_in si;
804 INT len = sizeof(si);
805 memset(&si, 0, sizeof(si));
807 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
808 if (status != SOCKET_ERROR)
809 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
810 } else if (af == AF_INET6) {
811 struct sockaddr_in6 si6;
812 INT len = sizeof(si6);
813 memset(&si6, 0, sizeof(si6));
814 si6.sin6_family = af;
815 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
816 if (status != SOCKET_ERROR)
817 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
820 if (status == SOCKET_ERROR) {