sd: sdhci: mask transfer mode register value
[qemu/ar7.git] / util / oslib-win32.c
blob0b1890fd3302c5e59ca0f47be3bea07cac64321e
1 /*
2 * os-win32.c
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2010-2016 Red Hat, Inc.
7 * QEMU library functions for win32 which are shared between QEMU and
8 * the QEMU tools.
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
28 * The implementation of g_poll (functions poll_rest, g_poll) at the end of
29 * this file are based on code from GNOME glib-2 and use a different license,
30 * see the license comment there.
32 #include "qemu/osdep.h"
33 #include <windows.h>
34 #include "qapi/error.h"
35 #include "sysemu/sysemu.h"
36 #include "qemu/main-loop.h"
37 #include "trace.h"
38 #include "qemu/sockets.h"
39 #include "qemu/cutils.h"
41 /* this must come after including "trace.h" */
42 #include <shlobj.h>
44 void *qemu_oom_check(void *ptr)
46 if (ptr == NULL) {
47 fprintf(stderr, "Failed to allocate memory: %lu\n", GetLastError());
48 abort();
50 return ptr;
53 void *qemu_try_memalign(size_t alignment, size_t size)
55 void *ptr;
57 if (!size) {
58 abort();
60 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
61 trace_qemu_memalign(alignment, size, ptr);
62 return ptr;
65 void *qemu_memalign(size_t alignment, size_t size)
67 return qemu_oom_check(qemu_try_memalign(alignment, size));
70 void *qemu_anon_ram_alloc(size_t size, uint64_t *align)
72 void *ptr;
74 /* FIXME: this is not exactly optimal solution since VirtualAlloc
75 has 64Kb granularity, but at least it guarantees us that the
76 memory is page aligned. */
77 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
78 trace_qemu_anon_ram_alloc(size, ptr);
79 return ptr;
82 void qemu_vfree(void *ptr)
84 trace_qemu_vfree(ptr);
85 if (ptr) {
86 VirtualFree(ptr, 0, MEM_RELEASE);
90 void qemu_anon_ram_free(void *ptr, size_t size)
92 trace_qemu_anon_ram_free(ptr, size);
93 if (ptr) {
94 VirtualFree(ptr, 0, MEM_RELEASE);
98 #ifndef CONFIG_LOCALTIME_R
99 /* FIXME: add proper locking */
100 struct tm *gmtime_r(const time_t *timep, struct tm *result)
102 struct tm *p = gmtime(timep);
103 memset(result, 0, sizeof(*result));
104 if (p) {
105 *result = *p;
106 p = result;
108 return p;
111 /* FIXME: add proper locking */
112 struct tm *localtime_r(const time_t *timep, struct tm *result)
114 struct tm *p = localtime(timep);
115 memset(result, 0, sizeof(*result));
116 if (p) {
117 *result = *p;
118 p = result;
120 return p;
122 #endif /* CONFIG_LOCALTIME_R */
124 void qemu_set_block(int fd)
126 unsigned long opt = 0;
127 WSAEventSelect(fd, NULL, 0);
128 ioctlsocket(fd, FIONBIO, &opt);
131 void qemu_set_nonblock(int fd)
133 unsigned long opt = 1;
134 ioctlsocket(fd, FIONBIO, &opt);
135 qemu_fd_register(fd);
138 int socket_set_fast_reuse(int fd)
140 /* Enabling the reuse of an endpoint that was used by a socket still in
141 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
142 * fast reuse is the default and SO_REUSEADDR does strange things. So we
143 * don't have to do anything here. More info can be found at:
144 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
145 return 0;
149 static int socket_error(void)
151 switch (WSAGetLastError()) {
152 case 0:
153 return 0;
154 case WSAEINTR:
155 return EINTR;
156 case WSAEINVAL:
157 return EINVAL;
158 case WSA_INVALID_HANDLE:
159 return EBADF;
160 case WSA_NOT_ENOUGH_MEMORY:
161 return ENOMEM;
162 case WSA_INVALID_PARAMETER:
163 return EINVAL;
164 case WSAENAMETOOLONG:
165 return ENAMETOOLONG;
166 case WSAENOTEMPTY:
167 return ENOTEMPTY;
168 case WSAEWOULDBLOCK:
169 /* not using EWOULDBLOCK as we don't want code to have
170 * to check both EWOULDBLOCK and EAGAIN */
171 return EAGAIN;
172 case WSAEINPROGRESS:
173 return EINPROGRESS;
174 case WSAEALREADY:
175 return EALREADY;
176 case WSAENOTSOCK:
177 return ENOTSOCK;
178 case WSAEDESTADDRREQ:
179 return EDESTADDRREQ;
180 case WSAEMSGSIZE:
181 return EMSGSIZE;
182 case WSAEPROTOTYPE:
183 return EPROTOTYPE;
184 case WSAENOPROTOOPT:
185 return ENOPROTOOPT;
186 case WSAEPROTONOSUPPORT:
187 return EPROTONOSUPPORT;
188 case WSAEOPNOTSUPP:
189 return EOPNOTSUPP;
190 case WSAEAFNOSUPPORT:
191 return EAFNOSUPPORT;
192 case WSAEADDRINUSE:
193 return EADDRINUSE;
194 case WSAEADDRNOTAVAIL:
195 return EADDRNOTAVAIL;
196 case WSAENETDOWN:
197 return ENETDOWN;
198 case WSAENETUNREACH:
199 return ENETUNREACH;
200 case WSAENETRESET:
201 return ENETRESET;
202 case WSAECONNABORTED:
203 return ECONNABORTED;
204 case WSAECONNRESET:
205 return ECONNRESET;
206 case WSAENOBUFS:
207 return ENOBUFS;
208 case WSAEISCONN:
209 return EISCONN;
210 case WSAENOTCONN:
211 return ENOTCONN;
212 case WSAETIMEDOUT:
213 return ETIMEDOUT;
214 case WSAECONNREFUSED:
215 return ECONNREFUSED;
216 case WSAELOOP:
217 return ELOOP;
218 case WSAEHOSTUNREACH:
219 return EHOSTUNREACH;
220 default:
221 return EIO;
225 int inet_aton(const char *cp, struct in_addr *ia)
227 uint32_t addr = inet_addr(cp);
228 if (addr == 0xffffffff) {
229 return 0;
231 ia->s_addr = addr;
232 return 1;
235 void qemu_set_cloexec(int fd)
239 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
240 #define _W32_FT_OFFSET (116444736000000000ULL)
242 int qemu_gettimeofday(qemu_timeval *tp)
244 union {
245 unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
246 FILETIME ft;
247 } _now;
249 if(tp) {
250 GetSystemTimeAsFileTime (&_now.ft);
251 tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL );
252 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL);
254 /* Always return 0 as per Open Group Base Specifications Issue 6.
255 Do not set errno on error. */
256 return 0;
259 int qemu_get_thread_id(void)
261 return GetCurrentThreadId();
264 char *
265 qemu_get_local_state_pathname(const char *relative_pathname)
267 HRESULT result;
268 char base_path[MAX_PATH+1] = "";
270 result = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL,
271 /* SHGFP_TYPE_CURRENT */ 0, base_path);
272 if (result != S_OK) {
273 /* misconfigured environment */
274 g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result);
275 abort();
277 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", base_path,
278 relative_pathname);
281 void qemu_set_tty_echo(int fd, bool echo)
283 HANDLE handle = (HANDLE)_get_osfhandle(fd);
284 DWORD dwMode = 0;
286 if (handle == INVALID_HANDLE_VALUE) {
287 return;
290 GetConsoleMode(handle, &dwMode);
292 if (echo) {
293 SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
294 } else {
295 SetConsoleMode(handle,
296 dwMode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
300 static char exec_dir[PATH_MAX];
302 void qemu_init_exec_dir(const char *argv0)
305 char *p;
306 char buf[MAX_PATH];
307 DWORD len;
309 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
310 if (len == 0) {
311 return;
314 buf[len] = 0;
315 p = buf + len - 1;
316 while (p != buf && *p != '\\') {
317 p--;
319 *p = 0;
320 if (access(buf, R_OK) == 0) {
321 pstrcpy(exec_dir, sizeof(exec_dir), buf);
325 char *qemu_get_exec_dir(void)
327 return g_strdup(exec_dir);
330 #if !GLIB_CHECK_VERSION(2, 50, 0)
332 * The original implementation of g_poll from glib has a problem on Windows
333 * when using timeouts < 10 ms.
335 * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
336 * of wait. This causes significant performance degradation of QEMU.
338 * The following code is a copy of the original code from glib/gpoll.c
339 * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
340 * Some debug code was removed and the code was reformatted.
341 * All other code modifications are marked with 'QEMU'.
345 * gpoll.c: poll(2) abstraction
346 * Copyright 1998 Owen Taylor
347 * Copyright 2008 Red Hat, Inc.
349 * This library is free software; you can redistribute it and/or
350 * modify it under the terms of the GNU Lesser General Public
351 * License as published by the Free Software Foundation; either
352 * version 2 of the License, or (at your option) any later version.
354 * This library is distributed in the hope that it will be useful,
355 * but WITHOUT ANY WARRANTY; without even the implied warranty of
356 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
357 * Lesser General Public License for more details.
359 * You should have received a copy of the GNU Lesser General Public
360 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
363 static int poll_rest(gboolean poll_msgs, HANDLE *handles, gint nhandles,
364 GPollFD *fds, guint nfds, gint timeout)
366 DWORD ready;
367 GPollFD *f;
368 int recursed_result;
370 if (poll_msgs) {
371 /* Wait for either messages or handles
372 * -> Use MsgWaitForMultipleObjectsEx
374 ready = MsgWaitForMultipleObjectsEx(nhandles, handles, timeout,
375 QS_ALLINPUT, MWMO_ALERTABLE);
377 if (ready == WAIT_FAILED) {
378 gchar *emsg = g_win32_error_message(GetLastError());
379 g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg);
380 g_free(emsg);
382 } else if (nhandles == 0) {
383 /* No handles to wait for, just the timeout */
384 if (timeout == INFINITE) {
385 ready = WAIT_FAILED;
386 } else {
387 SleepEx(timeout, TRUE);
388 ready = WAIT_TIMEOUT;
390 } else {
391 /* Wait for just handles
392 * -> Use WaitForMultipleObjectsEx
394 ready =
395 WaitForMultipleObjectsEx(nhandles, handles, FALSE, timeout, TRUE);
396 if (ready == WAIT_FAILED) {
397 gchar *emsg = g_win32_error_message(GetLastError());
398 g_warning("WaitForMultipleObjectsEx failed: %s", emsg);
399 g_free(emsg);
403 if (ready == WAIT_FAILED) {
404 return -1;
405 } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {
406 return 0;
407 } else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles) {
408 for (f = fds; f < &fds[nfds]; ++f) {
409 if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN) {
410 f->revents |= G_IO_IN;
414 /* If we have a timeout, or no handles to poll, be satisfied
415 * with just noticing we have messages waiting.
417 if (timeout != 0 || nhandles == 0) {
418 return 1;
421 /* If no timeout and handles to poll, recurse to poll them,
422 * too.
424 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
425 return (recursed_result == -1) ? -1 : 1 + recursed_result;
426 } else if (/* QEMU: removed the following unneeded statement which causes
427 * a compiler warning: ready >= WAIT_OBJECT_0 && */
428 ready < WAIT_OBJECT_0 + nhandles) {
429 for (f = fds; f < &fds[nfds]; ++f) {
430 if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0]) {
431 f->revents = f->events;
435 /* If no timeout and polling several handles, recurse to poll
436 * the rest of them.
438 if (timeout == 0 && nhandles > 1) {
439 /* Remove the handle that fired */
440 int i;
441 if (ready < nhandles - 1) {
442 for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {
443 handles[i-1] = handles[i];
446 nhandles--;
447 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
448 return (recursed_result == -1) ? -1 : 1 + recursed_result;
450 return 1;
453 return 0;
456 gint g_poll(GPollFD *fds, guint nfds, gint timeout)
458 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
459 gboolean poll_msgs = FALSE;
460 GPollFD *f;
461 gint nhandles = 0;
462 int retval;
464 for (f = fds; f < &fds[nfds]; ++f) {
465 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN)) {
466 poll_msgs = TRUE;
467 } else if (f->fd > 0) {
468 /* Don't add the same handle several times into the array, as
469 * docs say that is not allowed, even if it actually does seem
470 * to work.
472 gint i;
474 for (i = 0; i < nhandles; i++) {
475 if (handles[i] == (HANDLE) f->fd) {
476 break;
480 if (i == nhandles) {
481 if (nhandles == MAXIMUM_WAIT_OBJECTS) {
482 g_warning("Too many handles to wait for!\n");
483 break;
484 } else {
485 handles[nhandles++] = (HANDLE) f->fd;
491 for (f = fds; f < &fds[nfds]; ++f) {
492 f->revents = 0;
495 if (timeout == -1) {
496 timeout = INFINITE;
499 /* Polling for several things? */
500 if (nhandles > 1 || (nhandles > 0 && poll_msgs)) {
501 /* First check if one or several of them are immediately
502 * available
504 retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, 0);
506 /* If not, and we have a significant timeout, poll again with
507 * timeout then. Note that this will return indication for only
508 * one event, or only for messages. We ignore timeouts less than
509 * ten milliseconds as they are mostly pointless on Windows, the
510 * MsgWaitForMultipleObjectsEx() call will timeout right away
511 * anyway.
513 * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
515 if (retval == 0 && (timeout == INFINITE || timeout > 0)) {
516 retval = poll_rest(poll_msgs, handles, nhandles,
517 fds, nfds, timeout);
519 } else {
520 /* Just polling for one thing, so no need to check first if
521 * available immediately
523 retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, timeout);
526 if (retval == -1) {
527 for (f = fds; f < &fds[nfds]; ++f) {
528 f->revents = 0;
532 return retval;
534 #endif
536 int getpagesize(void)
538 SYSTEM_INFO system_info;
540 GetSystemInfo(&system_info);
541 return system_info.dwPageSize;
544 void os_mem_prealloc(int fd, char *area, size_t memory, Error **errp)
546 int i;
547 size_t pagesize = getpagesize();
549 memory = (memory + pagesize - 1) & -pagesize;
550 for (i = 0; i < memory / pagesize; i++) {
551 memset(area + pagesize * i, 0, 1);
556 /* XXX: put correct support for win32 */
557 int qemu_read_password(char *buf, int buf_size)
559 int c, i;
561 printf("Password: ");
562 fflush(stdout);
563 i = 0;
564 for (;;) {
565 c = getchar();
566 if (c < 0) {
567 buf[i] = '\0';
568 return -1;
569 } else if (c == '\n') {
570 break;
571 } else if (i < (buf_size - 1)) {
572 buf[i++] = c;
575 buf[i] = '\0';
576 return 0;
580 char *qemu_get_pid_name(pid_t pid)
582 /* XXX Implement me */
583 abort();
587 pid_t qemu_fork(Error **errp)
589 errno = ENOSYS;
590 error_setg_errno(errp, errno,
591 "cannot fork child process");
592 return -1;
596 #undef connect
597 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
598 socklen_t addrlen)
600 int ret;
601 ret = connect(sockfd, addr, addrlen);
602 if (ret < 0) {
603 errno = socket_error();
605 return ret;
609 #undef listen
610 int qemu_listen_wrap(int sockfd, int backlog)
612 int ret;
613 ret = listen(sockfd, backlog);
614 if (ret < 0) {
615 errno = socket_error();
617 return ret;
621 #undef bind
622 int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
623 socklen_t addrlen)
625 int ret;
626 ret = bind(sockfd, addr, addrlen);
627 if (ret < 0) {
628 errno = socket_error();
630 return ret;
634 #undef socket
635 int qemu_socket_wrap(int domain, int type, int protocol)
637 int ret;
638 ret = socket(domain, type, protocol);
639 if (ret < 0) {
640 errno = socket_error();
642 return ret;
646 #undef accept
647 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
648 socklen_t *addrlen)
650 int ret;
651 ret = accept(sockfd, addr, addrlen);
652 if (ret < 0) {
653 errno = socket_error();
655 return ret;
659 #undef shutdown
660 int qemu_shutdown_wrap(int sockfd, int how)
662 int ret;
663 ret = shutdown(sockfd, how);
664 if (ret < 0) {
665 errno = socket_error();
667 return ret;
671 #undef ioctlsocket
672 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
674 int ret;
675 ret = ioctlsocket(fd, req, val);
676 if (ret < 0) {
677 errno = socket_error();
679 return ret;
683 #undef closesocket
684 int qemu_closesocket_wrap(int fd)
686 int ret;
687 ret = closesocket(fd);
688 if (ret < 0) {
689 errno = socket_error();
691 return ret;
695 #undef getsockopt
696 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
697 void *optval, socklen_t *optlen)
699 int ret;
700 ret = getsockopt(sockfd, level, optname, optval, optlen);
701 if (ret < 0) {
702 errno = socket_error();
704 return ret;
708 #undef setsockopt
709 int qemu_setsockopt_wrap(int sockfd, int level, int optname,
710 const void *optval, socklen_t optlen)
712 int ret;
713 ret = setsockopt(sockfd, level, optname, optval, optlen);
714 if (ret < 0) {
715 errno = socket_error();
717 return ret;
721 #undef getpeername
722 int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
723 socklen_t *addrlen)
725 int ret;
726 ret = getpeername(sockfd, addr, addrlen);
727 if (ret < 0) {
728 errno = socket_error();
730 return ret;
734 #undef getsockname
735 int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
736 socklen_t *addrlen)
738 int ret;
739 ret = getsockname(sockfd, addr, addrlen);
740 if (ret < 0) {
741 errno = socket_error();
743 return ret;
747 #undef send
748 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
750 int ret;
751 ret = send(sockfd, buf, len, flags);
752 if (ret < 0) {
753 errno = socket_error();
755 return ret;
759 #undef sendto
760 ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
761 const struct sockaddr *addr, socklen_t addrlen)
763 int ret;
764 ret = sendto(sockfd, buf, len, flags, addr, addrlen);
765 if (ret < 0) {
766 errno = socket_error();
768 return ret;
772 #undef recv
773 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
775 int ret;
776 ret = recv(sockfd, buf, len, flags);
777 if (ret < 0) {
778 errno = socket_error();
780 return ret;
784 #undef recvfrom
785 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
786 struct sockaddr *addr, socklen_t *addrlen)
788 int ret;
789 ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
790 if (ret < 0) {
791 errno = socket_error();
793 return ret;