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 /* Don't allow Windows to cache the write: flush it to disk */
417 bytes_remaining -= bytes_written;
421 _lseeki64(fd, prev_pos, SEEK_SET);
425 int ftruncate(int fildes, off_t length)
428 int64_t prev_pos = _telli64(fildes);
429 _lseeki64(fildes, length, SEEK_SET);
430 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
431 bSuccess = SetEndOfFile(hFile);
432 _lseeki64(fildes, prev_pos, SEEK_SET);
436 int fsync(int fildes)
438 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
439 return !FlushFileBuffers(hFile);
442 int nFileMappings = 0;
443 HANDLE fileMappings[1024];
445 int shmget(key_t key, size_t size, int shmflg)
448 uint32_t size_low = size & 0xFFFFFFFF;
449 uint32_t size_high = ((uint64_t)size) >> 32;
450 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
451 if (hMapping != NULL) {
452 fileMappings[nFileMappings] = hMapping;
453 mapid = nFileMappings;
462 void *shmat(int shmid, const void *shmaddr, int shmflg)
465 MEMORY_BASIC_INFORMATION memInfo;
466 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
467 VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
468 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
472 int shmdt(const void *shmaddr)
474 return !UnmapViewOfFile(shmaddr);
477 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
479 if (cmd == IPC_RMID) {
480 fileMappings[shmid] = INVALID_HANDLE_VALUE;
483 log_err("%s is not implemented\n", __func__);
488 int setuid(uid_t uid)
490 log_err("%s is not implemented\n", __func__);
495 int setgid(gid_t gid)
497 log_err("%s is not implemented\n", __func__);
512 int getrusage(int who, struct rusage *r_usage)
514 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
515 FILETIME cTime, eTime, kTime, uTime;
518 memset(r_usage, 0, sizeof(*r_usage));
520 HANDLE hProcess = GetCurrentProcess();
521 GetProcessTimes(hProcess, &cTime, &eTime, &kTime, &uTime);
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_madvise(void *addr, size_t len, int advice)
540 log_err("%s is not implemented\n", __func__);
544 /* Windows doesn't support advice for memory pages. Just ignore it. */
545 int msync(void *addr, size_t len, int flags)
551 int fdatasync(int fildes)
553 return fsync(fildes);
556 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
559 int64_t pos = _telli64(fildes);
560 ssize_t len = _write(fildes, buf, nbyte);
561 _lseeki64(fildes, pos, SEEK_SET);
565 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
567 int64_t pos = _telli64(fildes);
568 ssize_t len = read(fildes, buf, nbyte);
569 _lseeki64(fildes, pos, SEEK_SET);
573 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
575 log_err("%s is not implemented\n", __func__);
580 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
582 log_err("%s is not implemented\n", __func__);
587 long long strtoll(const char *restrict str, char **restrict endptr,
590 return _strtoi64(str, endptr, base);
593 char *strsep(char **stringp, const char *delim)
595 char *orig = *stringp;
596 BOOL gotMatch = FALSE;
600 if (*stringp == NULL)
603 while ((*stringp)[i] != '\0') {
605 while (delim[j] != '\0') {
606 if ((*stringp)[i] == delim[j]) {
608 (*stringp)[i] = '\0';
609 *stringp = *stringp + i + 1;
626 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
629 struct timeval *to = NULL;
630 fd_set readfds, writefds, exceptfds;
636 to->tv_sec = timeout / 1000;
637 to->tv_usec = (timeout % 1000) * 1000;
644 for (i = 0; i < nfds; i++)
651 if (fds[i].events & POLLIN)
652 FD_SET(fds[i].fd, &readfds);
654 if (fds[i].events & POLLOUT)
655 FD_SET(fds[i].fd, &writefds);
657 FD_SET(fds[i].fd, &exceptfds);
660 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
662 if (rc != SOCKET_ERROR) {
663 for (i = 0; i < nfds; i++)
669 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
670 fds[i].revents |= POLLIN;
672 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
673 fds[i].revents |= POLLOUT;
675 if (FD_ISSET(fds[i].fd, &exceptfds))
676 fds[i].revents |= POLLHUP;
683 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
687 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
692 ms_remaining = ms_total;
694 /* Since Sleep() can sleep for less than the requested time, add a loop to
695 ensure we only return after the requested length of time has elapsed */
697 fio_gettime(&tv, NULL);
699 ms_remaining = ms_total - mtime_since_now(&tv);
700 } while (ms_remaining > 0 && ms_remaining < ms_total);
702 /* this implementation will never sleep for less than the requested time */
711 DIR *opendir(const char *dirname)
713 struct dirent_ctx *dc = NULL;
715 /* See if we can open it. If not, we'll return an error here */
716 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
717 if (file != INVALID_HANDLE_VALUE) {
719 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
720 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
721 dc->find_handle = INVALID_HANDLE_VALUE;
723 DWORD error = GetLastError();
724 if (error == ERROR_FILE_NOT_FOUND)
727 else if (error == ERROR_PATH_NOT_FOUND)
729 else if (error == ERROR_TOO_MANY_OPEN_FILES)
731 else if (error == ERROR_ACCESS_DENIED)
740 int closedir(DIR *dirp)
742 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
743 FindClose(dirp->find_handle);
749 struct dirent *readdir(DIR *dirp)
751 static struct dirent de;
752 WIN32_FIND_DATA find_data;
757 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
758 char search_pattern[MAX_PATH];
759 StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
760 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
761 if (dirp->find_handle == INVALID_HANDLE_VALUE)
764 if (!FindNextFile(dirp->find_handle, &find_data))
768 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
776 log_err("%s is not implemented\n", __func__);
781 const char* inet_ntop(int af, const void *restrict src,
782 char *restrict dst, socklen_t size)
784 INT status = SOCKET_ERROR;
788 if (af != AF_INET && af != AF_INET6) {
789 errno = EAFNOSUPPORT;
793 WSAStartup(MAKEWORD(2,2), &wsd);
796 struct sockaddr_in si;
798 memset(&si, 0, sizeof(si));
800 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
801 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
802 } else if (af == AF_INET6) {
803 struct sockaddr_in6 si6;
805 memset(&si6, 0, sizeof(si6));
806 si6.sin6_family = af;
807 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
808 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
811 if (status != SOCKET_ERROR)
821 int inet_aton(const char *cp, struct in_addr *inp)
823 return inet_pton(AF_INET, cp, inp);
826 int inet_pton(int af, const char *restrict src, void *restrict dst)
828 INT status = SOCKET_ERROR;
832 if (af != AF_INET && af != AF_INET6) {
833 errno = EAFNOSUPPORT;
837 WSAStartup(MAKEWORD(2,2), &wsd);
840 struct sockaddr_in si;
841 INT len = sizeof(si);
842 memset(&si, 0, sizeof(si));
844 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
845 if (status != SOCKET_ERROR)
846 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
847 } else if (af == AF_INET6) {
848 struct sockaddr_in6 si6;
849 INT len = sizeof(si6);
850 memset(&si6, 0, sizeof(si6));
851 si6.sin6_family = af;
852 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
853 if (status != SOCKET_ERROR)
854 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
857 if (status == SOCKET_ERROR) {