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"
24 extern unsigned long mtime_since_now(struct timeval *);
25 extern void fio_gettime(struct timeval *, void *);
27 /* These aren't defined in the MinGW headers */
28 HRESULT WINAPI StringCchCopyA(
33 HRESULT WINAPI StringCchPrintfA(
36 const char *pszFormat,
41 size_t numberOfElements,
45 long sysconf(int name)
49 SYSTEM_LOGICAL_PROCESSOR_INFORMATION processorInfo;
51 MEMORYSTATUSEX status;
55 case _SC_NPROCESSORS_ONLN:
56 len = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
57 GetLogicalProcessorInformation(&processorInfo, &len);
58 val = len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
62 GetSystemInfo(&sysInfo);
63 val = sysInfo.dwPageSize;
67 status.dwLength = sizeof(status);
68 GlobalMemoryStatusEx(&status);
69 val = status.ullTotalPhys;
72 log_err("sysconf(%d) is not implemented\n", name);
79 char *dl_error = NULL;
81 int dlclose(void *handle)
83 return !FreeLibrary((HMODULE)handle);
86 void *dlopen(const char *file, int mode)
90 hMod = LoadLibrary(file);
91 if (hMod == INVALID_HANDLE_VALUE)
92 dl_error = (char*)"LoadLibrary failed";
99 void *dlsym(void *handle, const char *name)
103 fnPtr = GetProcAddress((HMODULE)handle, name);
105 dl_error = (char*)"GetProcAddress failed";
117 int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
120 uint64_t unix_time, windows_time;
121 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
123 /* Ignore the timezone parameter */
127 * Windows time is stored as the number 100 ns intervals since January 1 1601.
128 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
129 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
131 GetSystemTimeAsFileTime(&fileTime);
132 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
133 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
134 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
135 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
136 tp->tv_sec = unix_time / 1000;
137 tp->tv_usec = (unix_time % 1000) * 1000;
141 int sigaction(int sig, const struct sigaction *act,
142 struct sigaction *oact)
145 void (*prev_handler)(int);
147 prev_handler = signal(sig, act->sa_handler);
149 oact->sa_handler = prev_handler;
151 if (prev_handler == SIG_ERR)
157 int lstat(const char * path, struct stat * buf)
159 return stat(path, buf);
162 void *mmap(void *addr, size_t len, int prot, int flags,
163 int fildes, off_t off)
166 void* allocAddr = NULL;
168 if (prot & PROT_NONE)
169 vaProt |= PAGE_NOACCESS;
171 if ((prot & PROT_READ) && !(prot & PROT_WRITE))
172 vaProt |= PAGE_READONLY;
174 if (prot & PROT_WRITE)
175 vaProt |= PAGE_READWRITE;
177 if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
179 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
185 int munmap(void *addr, size_t len)
187 return !VirtualFree(addr, 0, MEM_RELEASE);
192 log_err("%s is not implemented\n", __func__);
199 log_err("%s is not implemented\n", __func__);
204 static HANDLE log_file = INVALID_HANDLE_VALUE;
206 void openlog(const char *ident, int logopt, int facility)
208 if (log_file == INVALID_HANDLE_VALUE)
209 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
214 CloseHandle(log_file);
215 log_file = INVALID_HANDLE_VALUE;
218 void syslog(int priority, const char *message, ... /* argument */)
225 if (log_file == INVALID_HANDLE_VALUE) {
226 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
229 if (log_file == INVALID_HANDLE_VALUE) {
230 log_err("syslog: failed to open log file\n");
234 va_start(v, message);
235 len = _vscprintf(message, v);
236 output = malloc(len + sizeof(char));
237 vsprintf(output, message, v);
238 WriteFile(log_file, output, len, &bytes_written, NULL);
243 int kill(pid_t pid, int sig)
250 * This is assumed to be used only by the network code,
251 * and so doesn't try and handle any of the other cases
253 int fcntl(int fildes, int cmd, ...)
256 * non-blocking mode doesn't work the same as in BSD sockets,
261 int val, opt, status;
265 else if (cmd != F_SETFL) {
272 opt = va_arg(ap, int);
273 if (opt & O_NONBLOCK)
278 status = ioctlsocket((SOCKET)fildes, opt, &val);
280 if (status == SOCKET_ERROR) {
293 * Get the value of a local clock source.
294 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
295 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
297 int clock_gettime(clockid_t clock_id, struct timespec *tp)
301 if (clock_id == CLOCK_MONOTONIC)
303 static LARGE_INTEGER freq = {{0,0}};
304 LARGE_INTEGER counts;
306 QueryPerformanceCounter(&counts);
307 if (freq.QuadPart == 0)
308 QueryPerformanceFrequency(&freq);
310 tp->tv_sec = counts.QuadPart / freq.QuadPart;
311 /* Get the difference between the number of ns stored
312 * in 'tv_sec' and that stored in 'counts' */
313 uint64_t t = tp->tv_sec * freq.QuadPart;
314 t = counts.QuadPart - t;
315 /* 't' now contains the number of cycles since the last second.
316 * We want the number of nanoseconds, so multiply out by 1,000,000,000
317 * and then divide by the frequency. */
319 tp->tv_nsec = t / freq.QuadPart;
321 else if (clock_id == CLOCK_REALTIME)
323 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
324 * higher-precision field. */
326 gettimeofday(&tv, NULL);
327 tp->tv_sec = tv.tv_sec;
328 tp->tv_nsec = tv.tv_usec * 1000;
337 int mlock(const void * addr, size_t len)
339 return !VirtualLock((LPVOID)addr, len);
342 int munlock(const void * addr, size_t len)
344 return !VirtualUnlock((LPVOID)addr, len);
347 pid_t waitpid(pid_t pid, int *stat_loc, int options)
349 log_err("%s is not implemented\n", __func__);
354 int usleep(useconds_t useconds)
356 Sleep(useconds / 1000);
360 char *basename(char *path)
362 static char name[MAX_PATH];
365 if (path == NULL || strlen(path) == 0)
368 i = strlen(path) - 1;
370 while (path[i] != '\\' && path[i] != '/' && i >= 0)
373 strncpy(name, path + i + 1, MAX_PATH);
378 int posix_fallocate(int fd, off_t offset, off_t len)
380 const int BUFFER_SIZE = 256 * 1024;
383 unsigned int write_len;
384 unsigned int bytes_written;
385 off_t bytes_remaining = len;
387 if (len == 0 || offset < 0)
390 buf = malloc(BUFFER_SIZE);
395 memset(buf, 0, BUFFER_SIZE);
397 int64_t prev_pos = _telli64(fd);
399 if (_lseeki64(fd, offset, SEEK_SET) == -1)
402 while (bytes_remaining > 0) {
403 if (bytes_remaining < BUFFER_SIZE)
404 write_len = (unsigned int)bytes_remaining;
406 write_len = BUFFER_SIZE;
408 bytes_written = _write(fd, buf, write_len);
409 if (bytes_written == -1) {
414 bytes_remaining -= bytes_written;
418 _lseeki64(fd, prev_pos, SEEK_SET);
422 int ftruncate(int fildes, off_t length)
425 int64_t prev_pos = _telli64(fildes);
426 _lseeki64(fildes, length, SEEK_SET);
427 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
428 bSuccess = SetEndOfFile(hFile);
429 _lseeki64(fildes, prev_pos, SEEK_SET);
433 int fsync(int fildes)
435 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
436 return !FlushFileBuffers(hFile);
439 int nFileMappings = 0;
440 HANDLE fileMappings[1024];
442 int shmget(key_t key, size_t size, int shmflg)
445 uint32_t size_low = size & 0xFFFFFFFF;
446 uint32_t size_high = ((uint64_t)size) >> 32;
447 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
448 if (hMapping != NULL) {
449 fileMappings[nFileMappings] = hMapping;
450 mapid = nFileMappings;
459 void *shmat(int shmid, const void *shmaddr, int shmflg)
462 MEMORY_BASIC_INFORMATION memInfo;
463 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
464 VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
465 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
469 int shmdt(const void *shmaddr)
471 return !UnmapViewOfFile(shmaddr);
474 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
476 if (cmd == IPC_RMID) {
477 fileMappings[shmid] = INVALID_HANDLE_VALUE;
480 log_err("%s is not implemented\n", __func__);
485 int setuid(uid_t uid)
487 log_err("%s is not implemented\n", __func__);
492 int setgid(gid_t gid)
494 log_err("%s is not implemented\n", __func__);
509 int getrusage(int who, struct rusage *r_usage)
511 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
512 FILETIME cTime, eTime, kTime, uTime;
515 memset(r_usage, 0, sizeof(*r_usage));
517 HANDLE hProcess = GetCurrentProcess();
518 GetProcessTimes(hProcess, &cTime, &eTime, &kTime, &uTime);
519 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
520 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
522 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
523 r_usage->ru_utime.tv_sec = time;
524 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
525 r_usage->ru_utime.tv_usec = 0;
526 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
527 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
529 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
530 r_usage->ru_stime.tv_sec = time;
531 r_usage->ru_stime.tv_usec = 0;
535 int posix_madvise(void *addr, size_t len, int advice)
537 log_err("%s is not implemented\n", __func__);
541 /* Windows doesn't support advice for memory pages. Just ignore it. */
542 int msync(void *addr, size_t len, int flags)
548 int fdatasync(int fildes)
550 return fsync(fildes);
553 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
556 int64_t pos = _telli64(fildes);
557 ssize_t len = _write(fildes, buf, nbyte);
558 _lseeki64(fildes, pos, SEEK_SET);
562 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
564 int64_t pos = _telli64(fildes);
565 ssize_t len = read(fildes, buf, nbyte);
566 _lseeki64(fildes, pos, SEEK_SET);
570 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
572 log_err("%s is not implemented\n", __func__);
577 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
579 log_err("%s is not implemented\n", __func__);
584 long long strtoll(const char *restrict str, char **restrict endptr,
587 return _strtoi64(str, endptr, base);
590 char *strsep(char **stringp, const char *delim)
592 char *orig = *stringp;
593 BOOL gotMatch = FALSE;
597 if (*stringp == NULL)
600 while ((*stringp)[i] != '\0') {
602 while (delim[j] != '\0') {
603 if ((*stringp)[i] == delim[j]) {
605 (*stringp)[i] = '\0';
606 *stringp = *stringp + i + 1;
623 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
626 struct timeval *to = NULL;
627 fd_set readfds, writefds, exceptfds;
634 to->tv_sec = timeout / 1000;
635 to->tv_usec = (timeout % 1000) * 1000;
641 for (i = 0; i < nfds; i++)
648 if (fds[i].events & POLLIN)
649 FD_SET(fds[i].fd, &readfds);
651 if (fds[i].events & POLLOUT)
652 FD_SET(fds[i].fd, &writefds);
654 FD_SET(fds[i].fd, &exceptfds);
657 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
659 if (rc != SOCKET_ERROR) {
660 for (i = 0; i < nfds; i++)
666 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
667 fds[i].revents |= POLLIN;
669 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
670 fds[i].revents |= POLLOUT;
672 if (FD_ISSET(fds[i].fd, &exceptfds))
673 fds[i].revents |= POLLHUP;
680 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
684 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
689 ms_remaining = ms_total;
691 /* Since Sleep() can sleep for less than the requested time, add a loop to
692 ensure we only return after the requested length of time has elapsed */
694 fio_gettime(&tv, NULL);
696 ms_remaining = ms_total - mtime_since_now(&tv);
697 } while (ms_remaining > 0 && ms_remaining < ms_total);
699 /* this implementation will never sleep for less than the requested time */
708 DIR *opendir(const char *dirname)
710 struct dirent_ctx *dc = NULL;
712 /* See if we can open it. If not, we'll return an error here */
713 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
714 if (file != INVALID_HANDLE_VALUE) {
716 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
717 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
718 dc->find_handle = INVALID_HANDLE_VALUE;
720 DWORD error = GetLastError();
721 if (error == ERROR_FILE_NOT_FOUND)
724 else if (error == ERROR_PATH_NOT_FOUND)
726 else if (error == ERROR_TOO_MANY_OPEN_FILES)
728 else if (error == ERROR_ACCESS_DENIED)
737 int closedir(DIR *dirp)
739 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
740 FindClose(dirp->find_handle);
746 struct dirent *readdir(DIR *dirp)
748 static struct dirent de;
749 WIN32_FIND_DATA find_data;
754 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
755 char search_pattern[MAX_PATH];
756 StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
757 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
758 if (dirp->find_handle == INVALID_HANDLE_VALUE)
761 if (!FindNextFile(dirp->find_handle, &find_data))
765 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
773 log_err("%s is not implemented\n", __func__);
778 const char* inet_ntop(int af, const void *restrict src,
779 char *restrict dst, socklen_t size)
781 INT status = SOCKET_ERROR;
785 if (af != AF_INET && af != AF_INET6) {
786 errno = EAFNOSUPPORT;
790 WSAStartup(MAKEWORD(2,2), &wsd);
793 struct sockaddr_in si;
795 memset(&si, 0, sizeof(si));
797 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
798 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
799 } else if (af == AF_INET6) {
800 struct sockaddr_in6 si6;
802 memset(&si6, 0, sizeof(si6));
803 si6.sin6_family = af;
804 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
805 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
808 if (status != SOCKET_ERROR)
817 int inet_pton(int af, const char *restrict src, void *restrict dst)
819 INT status = SOCKET_ERROR;
823 if (af != AF_INET && af != AF_INET6) {
824 errno = EAFNOSUPPORT;
828 WSAStartup(MAKEWORD(2,2), &wsd);
831 struct sockaddr_in si;
832 INT len = sizeof(si);
833 memset(&si, 0, sizeof(si));
835 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
836 if (status != SOCKET_ERROR)
837 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
838 } else if (af == AF_INET6) {
839 struct sockaddr_in6 si6;
840 INT len = sizeof(si6);
841 memset(&si6, 0, sizeof(si6));
842 si6.sin6_family = af;
843 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
844 if (status != SOCKET_ERROR)
845 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
848 if (status == SOCKET_ERROR) {