Use common objects for qemu-img and qemu-nbd
[qemu] / osdep.c
1 /*
2  * QEMU low level functions
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #ifdef HOST_SOLARIS
32 #include <sys/types.h>
33 #include <sys/statvfs.h>
34 #endif
35
36 #include "qemu-common.h"
37 #include "sysemu.h"
38
39 #ifdef _WIN32
40 #define WIN32_LEAN_AND_MEAN
41 #include <windows.h>
42 #elif defined(_BSD)
43 #include <stdlib.h>
44 #else
45 #include <malloc.h>
46 #endif
47
48 #include "qemu_socket.h"
49
50 #if defined(_WIN32)
51 void *qemu_memalign(size_t alignment, size_t size)
52 {
53     return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
54 }
55
56 void *qemu_vmalloc(size_t size)
57 {
58     /* FIXME: this is not exactly optimal solution since VirtualAlloc
59        has 64Kb granularity, but at least it guarantees us that the
60        memory is page aligned. */
61     return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
62 }
63
64 void qemu_vfree(void *ptr)
65 {
66     VirtualFree(ptr, 0, MEM_RELEASE);
67 }
68
69 #else
70
71 #if defined(USE_KQEMU)
72
73 #ifdef __OpenBSD__
74 #include <sys/param.h>
75 #include <sys/types.h>
76 #include <sys/mount.h>
77 #else
78 #include <sys/vfs.h>
79 #endif
80
81 #include <sys/mman.h>
82 #include <fcntl.h>
83
84 static void *kqemu_vmalloc(size_t size)
85 {
86     static int phys_ram_fd = -1;
87     static int phys_ram_size = 0;
88     void *ptr;
89
90 #ifdef __OpenBSD__ /* no need (?) for a dummy file on OpenBSD */
91     int map_anon = MAP_ANON;
92 #else
93     int map_anon = 0;
94     const char *tmpdir;
95     char phys_ram_file[1024];
96 #ifdef HOST_SOLARIS
97     struct statvfs stfs;
98 #else
99     struct statfs stfs;
100 #endif
101
102     if (phys_ram_fd < 0) {
103         tmpdir = getenv("QEMU_TMPDIR");
104         if (!tmpdir)
105 #ifdef HOST_SOLARIS
106             tmpdir = "/tmp";
107         if (statvfs(tmpdir, &stfs) == 0) {
108 #else
109             tmpdir = "/dev/shm";
110         if (statfs(tmpdir, &stfs) == 0) {
111 #endif
112             int64_t free_space;
113             int ram_mb;
114
115             free_space = (int64_t)stfs.f_bavail * stfs.f_bsize;
116             if ((ram_size + 8192 * 1024) >= free_space) {
117                 ram_mb = (ram_size / (1024 * 1024));
118                 fprintf(stderr,
119                         "You do not have enough space in '%s' for the %d MB of QEMU virtual RAM.\n",
120                         tmpdir, ram_mb);
121                 if (strcmp(tmpdir, "/dev/shm") == 0) {
122                     fprintf(stderr, "To have more space available provided you have enough RAM and swap, do as root:\n"
123                             "mount -o remount,size=%dm /dev/shm\n",
124                             ram_mb + 16);
125                 } else {
126                     fprintf(stderr,
127                             "Use the '-m' option of QEMU to diminish the amount of virtual RAM or use the\n"
128                             "QEMU_TMPDIR environment variable to set another directory where the QEMU\n"
129                             "temporary RAM file will be opened.\n");
130                 }
131                 fprintf(stderr, "Or disable the accelerator module with -no-kqemu\n");
132                 exit(1);
133             }
134         }
135         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/qemuXXXXXX",
136                  tmpdir);
137         phys_ram_fd = mkstemp(phys_ram_file);
138         if (phys_ram_fd < 0) {
139             fprintf(stderr,
140                     "warning: could not create temporary file in '%s'.\n"
141                     "Use QEMU_TMPDIR to select a directory in a tmpfs filesystem.\n"
142                     "Using '/tmp' as fallback.\n",
143                     tmpdir);
144             snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/qemuXXXXXX",
145                      "/tmp");
146             phys_ram_fd = mkstemp(phys_ram_file);
147             if (phys_ram_fd < 0) {
148                 fprintf(stderr, "Could not create temporary memory file '%s'\n",
149                         phys_ram_file);
150                 exit(1);
151             }
152         }
153         unlink(phys_ram_file);
154     }
155     size = (size + 4095) & ~4095;
156     ftruncate(phys_ram_fd, phys_ram_size + size);
157 #endif /* !__OpenBSD__ */
158     ptr = mmap(NULL,
159                size,
160                PROT_WRITE | PROT_READ, map_anon | MAP_SHARED,
161                phys_ram_fd, phys_ram_size);
162     if (ptr == MAP_FAILED) {
163         fprintf(stderr, "Could not map physical memory\n");
164         exit(1);
165     }
166     phys_ram_size += size;
167     return ptr;
168 }
169
170 static void kqemu_vfree(void *ptr)
171 {
172     /* may be useful some day, but currently we do not need to free */
173 }
174
175 #endif
176
177 void *qemu_memalign(size_t alignment, size_t size)
178 {
179 #if defined(_POSIX_C_SOURCE)
180     int ret;
181     void *ptr;
182     ret = posix_memalign(&ptr, alignment, size);
183     if (ret != 0)
184         return NULL;
185     return ptr;
186 #elif defined(_BSD)
187     return valloc(size);
188 #else
189     return memalign(alignment, size);
190 #endif
191 }
192
193 /* alloc shared memory pages */
194 void *qemu_vmalloc(size_t size)
195 {
196 #if defined(USE_KQEMU)
197     if (kqemu_allowed)
198         return kqemu_vmalloc(size);
199 #endif
200 #ifdef _BSD
201     return valloc(size);
202 #else
203     return memalign(4096, size);
204 #endif
205 }
206
207 void qemu_vfree(void *ptr)
208 {
209 #if defined(USE_KQEMU)
210     if (kqemu_allowed)
211         kqemu_vfree(ptr);
212 #endif
213     free(ptr);
214 }
215
216 #endif
217
218 int qemu_create_pidfile(const char *filename)
219 {
220     char buffer[128];
221     int len;
222 #ifndef _WIN32
223     int fd;
224
225     fd = open(filename, O_RDWR | O_CREAT, 0600);
226     if (fd == -1)
227         return -1;
228
229     if (lockf(fd, F_TLOCK, 0) == -1)
230         return -1;
231
232     len = snprintf(buffer, sizeof(buffer), "%ld\n", (long)getpid());
233     if (write(fd, buffer, len) != len)
234         return -1;
235 #else
236     HANDLE file;
237     DWORD flags;
238     OVERLAPPED overlap;
239     BOOL ret;
240
241     /* Open for writing with no sharing. */
242     file = CreateFile(filename, GENERIC_WRITE, 0, NULL,
243                       OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
244
245     if (file == INVALID_HANDLE_VALUE)
246       return -1;
247
248     flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;
249     overlap.hEvent = 0;
250     /* Lock 1 byte. */
251     ret = LockFileEx(file, flags, 0, 0, 1, &overlap);
252     if (ret == 0)
253       return -1;
254
255     /* Write PID to file. */
256     len = snprintf(buffer, sizeof(buffer), "%ld\n", (long)getpid());
257     ret = WriteFileEx(file, (LPCVOID)buffer, (DWORD)len,
258                       &overlap, NULL);
259     if (ret == 0)
260       return -1;
261 #endif
262     return 0;
263 }
264
265 #ifdef _WIN32
266
267 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
268 #define _W32_FT_OFFSET (116444736000000000ULL)
269
270 int qemu_gettimeofday(qemu_timeval *tp)
271 {
272   union {
273     unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
274     FILETIME ft;
275   }  _now;
276
277   if(tp)
278     {
279       GetSystemTimeAsFileTime (&_now.ft);
280       tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL );
281       tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL);
282     }
283   /* Always return 0 as per Open Group Base Specifications Issue 6.
284      Do not set errno on error.  */
285   return 0;
286 }
287 #endif /* _WIN32 */
288
289
290 #ifdef _WIN32
291 void socket_set_nonblock(int fd)
292 {
293     unsigned long opt = 1;
294     ioctlsocket(fd, FIONBIO, &opt);
295 }
296
297 int inet_aton(const char *cp, struct in_addr *ia)
298 {
299     uint32_t addr = inet_addr(cp);
300     if (addr == 0xffffffff)
301         return 0;
302     ia->s_addr = addr;
303     return 1;
304 }
305 #else
306 void socket_set_nonblock(int fd)
307 {
308     int f;
309     f = fcntl(fd, F_GETFL);
310     fcntl(fd, F_SETFL, f | O_NONBLOCK);
311 }
312 #endif