master
c 621 lines 13.7 KB
Raw
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 "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "qemu/sockets.h"
28 #include "qemu/error-report.h"
29 #include "qemu/madvise.h"
30 #include "qemu/mprotect.h"
31 #include "qemu/hw-version.h"
32 #include "monitor/monitor.h"
33
34 int socket_set_cork(int fd, int v)
35 {
36 #if defined(SOL_TCP) && defined(TCP_CORK)
37 return setsockopt(fd, SOL_TCP, TCP_CORK, &v, sizeof(v));
38 #else
39 return 0;
40 #endif
41 }
42
43 int socket_set_nodelay(int fd)
44 {
45 int v = 1;
46 return setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v));
47 }
48
49 int qemu_madvise(void *addr, size_t len, int advice)
50 {
51 if (advice == QEMU_MADV_INVALID) {
52 errno = EINVAL;
53 return -1;
54 }
55 #if defined(CONFIG_MADVISE)
56 return madvise(addr, len, advice);
57 #elif defined(CONFIG_POSIX_MADVISE)
58 int rc = posix_madvise(addr, len, advice);
59 if (rc) {
60 errno = rc;
61 return -1;
62 }
63 return 0;
64 #else
65 errno = ENOSYS;
66 return -1;
67 #endif
68 }
69
70 static int qemu_mprotect__osdep(void *addr, size_t size, int prot)
71 {
72 g_assert(!((uintptr_t)addr & ~qemu_real_host_page_mask()));
73 g_assert(!(size & ~qemu_real_host_page_mask()));
74
75 #ifdef _WIN32
76 DWORD old_protect;
77
78 if (!VirtualProtect(addr, size, prot, &old_protect)) {
79 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
80 error_report("%s: VirtualProtect failed: %s", __func__, emsg);
81 return -1;
82 }
83 return 0;
84 #else
85 if (mprotect(addr, size, prot)) {
86 error_report("%s: mprotect failed: %s", __func__, strerror(errno));
87 return -1;
88 }
89 return 0;
90 #endif
91 }
92
93 int qemu_mprotect_rw(void *addr, size_t size)
94 {
95 #ifdef _WIN32
96 return qemu_mprotect__osdep(addr, size, PAGE_READWRITE);
97 #else
98 return qemu_mprotect__osdep(addr, size, PROT_READ | PROT_WRITE);
99 #endif
100 }
101
102 int qemu_mprotect_rwx(void *addr, size_t size)
103 {
104 #ifdef _WIN32
105 return qemu_mprotect__osdep(addr, size, PAGE_EXECUTE_READWRITE);
106 #else
107 return qemu_mprotect__osdep(addr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
108 #endif
109 }
110
111 int qemu_mprotect_none(void *addr, size_t size)
112 {
113 #ifdef _WIN32
114 return qemu_mprotect__osdep(addr, size, PAGE_NOACCESS);
115 #else
116 return qemu_mprotect__osdep(addr, size, PROT_NONE);
117 #endif
118 }
119
120 #ifndef _WIN32
121
122 static int fcntl_op_setlk = -1;
123 static int fcntl_op_getlk = -1;
124
125 /*
126 * Dups an fd and sets the flags
127 */
128 int qemu_dup_flags(int fd, int flags)
129 {
130 int ret;
131 int serrno;
132 int dup_flags;
133
134 ret = qemu_dup(fd);
135 if (ret == -1) {
136 goto fail;
137 }
138
139 dup_flags = fcntl(ret, F_GETFL);
140 if (dup_flags == -1) {
141 goto fail;
142 }
143
144 if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
145 errno = EINVAL;
146 goto fail;
147 }
148
149 /* Set/unset flags that we can with fcntl */
150 if (fcntl(ret, F_SETFL, flags) == -1) {
151 goto fail;
152 }
153
154 /* Truncate the file in the cases that open() would truncate it */
155 if (flags & O_TRUNC ||
156 ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
157 if (ftruncate(ret, 0) == -1) {
158 goto fail;
159 }
160 }
161
162 return ret;
163
164 fail:
165 serrno = errno;
166 if (ret != -1) {
167 close(ret);
168 }
169 errno = serrno;
170 return -1;
171 }
172
173 int qemu_dup(int fd)
174 {
175 int ret;
176 #ifdef F_DUPFD_CLOEXEC
177 ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
178 #else
179 ret = dup(fd);
180 if (ret != -1) {
181 qemu_set_cloexec(ret);
182 }
183 #endif
184 return ret;
185 }
186
187 static int qemu_parse_fdset(const char *param)
188 {
189 return qemu_parse_fd(param);
190 }
191
192 static void qemu_probe_lock_ops(void)
193 {
194 if (fcntl_op_setlk == -1) {
195 #ifdef F_OFD_SETLK
196 int fd;
197 int ret;
198 struct flock fl = {
199 .l_whence = SEEK_SET,
200 .l_start = 0,
201 .l_len = 0,
202 .l_type = F_WRLCK,
203 };
204
205 fd = open("/dev/null", O_RDWR);
206 if (fd < 0) {
207 fprintf(stderr,
208 "Failed to open /dev/null for OFD lock probing: %s\n",
209 strerror(errno));
210 fcntl_op_setlk = F_SETLK;
211 fcntl_op_getlk = F_GETLK;
212 return;
213 }
214 ret = fcntl(fd, F_OFD_GETLK, &fl);
215 close(fd);
216 if (!ret) {
217 fcntl_op_setlk = F_OFD_SETLK;
218 fcntl_op_getlk = F_OFD_GETLK;
219 } else {
220 fcntl_op_setlk = F_SETLK;
221 fcntl_op_getlk = F_GETLK;
222 }
223 #else
224 fcntl_op_setlk = F_SETLK;
225 fcntl_op_getlk = F_GETLK;
226 #endif
227 }
228 }
229
230 bool qemu_has_ofd_lock(void)
231 {
232 qemu_probe_lock_ops();
233 #ifdef F_OFD_SETLK
234 return fcntl_op_setlk == F_OFD_SETLK;
235 #else
236 return false;
237 #endif
238 }
239
240 static int qemu_lock_fcntl(int fd, int64_t start, int64_t len, int fl_type)
241 {
242 int ret;
243 struct flock fl = {
244 .l_whence = SEEK_SET,
245 .l_start = start,
246 .l_len = len,
247 .l_type = fl_type,
248 };
249 qemu_probe_lock_ops();
250 ret = RETRY_ON_EINTR(fcntl(fd, fcntl_op_setlk, &fl));
251 return ret == -1 ? -errno : 0;
252 }
253
254 int qemu_lock_fd(int fd, int64_t start, int64_t len, bool exclusive)
255 {
256 return qemu_lock_fcntl(fd, start, len, exclusive ? F_WRLCK : F_RDLCK);
257 }
258
259 int qemu_unlock_fd(int fd, int64_t start, int64_t len)
260 {
261 return qemu_lock_fcntl(fd, start, len, F_UNLCK);
262 }
263
264 int qemu_lock_fd_test(int fd, int64_t start, int64_t len, bool exclusive)
265 {
266 int ret;
267 struct flock fl = {
268 .l_whence = SEEK_SET,
269 .l_start = start,
270 .l_len = len,
271 .l_type = exclusive ? F_WRLCK : F_RDLCK,
272 };
273 qemu_probe_lock_ops();
274 ret = fcntl(fd, fcntl_op_getlk, &fl);
275 if (ret == -1) {
276 return -errno;
277 } else {
278 return fl.l_type == F_UNLCK ? 0 : -EAGAIN;
279 }
280 }
281
282 /**
283 * Set the given flag(s) (fcntl GETFL/SETFL) on the given FD, while retaining
284 * other flags.
285 */
286 int qemu_fcntl_addfl(int fd, int flag)
287 {
288 int flags;
289
290 flags = fcntl(fd, F_GETFL);
291 if (flags == -1) {
292 return -errno;
293 }
294 if (fcntl(fd, F_SETFL, flags | flag) == -1) {
295 return -errno;
296 }
297 return 0;
298 }
299 #endif
300
301 bool qemu_has_direct_io(void)
302 {
303 #ifdef O_DIRECT
304 return true;
305 #else
306 return false;
307 #endif
308 }
309
310 static int qemu_open_cloexec(const char *name, int flags, mode_t mode)
311 {
312 int ret;
313 #ifdef O_CLOEXEC
314 ret = open(name, flags | O_CLOEXEC, mode);
315 #else
316 ret = open(name, flags, mode);
317 if (ret >= 0) {
318 qemu_set_cloexec(ret);
319 }
320 #endif
321 return ret;
322 }
323
324 /*
325 * Opens a file with FD_CLOEXEC set
326 */
327 static int
328 qemu_open_internal(const char *name, int flags, mode_t mode, Error **errp)
329 {
330 int ret;
331
332 #ifndef _WIN32
333 const char *fdset_id_str;
334
335 /* Attempt dup of fd from fd set */
336 if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
337 int64_t fdset_id;
338
339 fdset_id = qemu_parse_fdset(fdset_id_str);
340 if (fdset_id == -1) {
341 error_setg(errp, "Could not parse fdset %s", name);
342 errno = EINVAL;
343 return -1;
344 }
345
346 return monitor_fdset_dup_fd_add(fdset_id, flags, errp);
347 }
348 #endif
349
350 ret = qemu_open_cloexec(name, flags, mode);
351
352 if (ret == -1) {
353 const char *action = flags & O_CREAT ? "create" : "open";
354 #ifdef O_DIRECT
355 /* Give more helpful error message for O_DIRECT */
356 if (errno == EINVAL && (flags & O_DIRECT)) {
357 ret = open(name, flags & ~O_DIRECT, mode);
358 if (ret != -1) {
359 close(ret);
360 error_setg(errp, "Could not %s '%s': "
361 "filesystem does not support O_DIRECT",
362 action, name);
363 errno = EINVAL; /* restore first open()'s errno */
364 return -1;
365 }
366 }
367 #endif /* O_DIRECT */
368 error_setg_errno(errp, errno, "Could not %s '%s'",
369 action, name);
370 }
371
372 return ret;
373 }
374
375
376 int qemu_open(const char *name, int flags, Error **errp)
377 {
378 assert(!(flags & O_CREAT));
379
380 return qemu_open_internal(name, flags, 0, errp);
381 }
382
383
384 int qemu_create(const char *name, int flags, mode_t mode, Error **errp)
385 {
386 assert(!(flags & O_CREAT));
387
388 return qemu_open_internal(name, flags | O_CREAT, mode, errp);
389 }
390
391
392 int qemu_open_old(const char *name, int flags, ...)
393 {
394 va_list ap;
395 mode_t mode = 0;
396 int ret;
397
398 va_start(ap, flags);
399 if (flags & O_CREAT) {
400 mode = va_arg(ap, int);
401 }
402 va_end(ap);
403
404 ret = qemu_open_internal(name, flags, mode, NULL);
405
406 #ifdef O_DIRECT
407 if (ret == -1 && errno == EINVAL && (flags & O_DIRECT)) {
408 error_report("file system may not support O_DIRECT");
409 errno = EINVAL; /* in case it was clobbered */
410 }
411 #endif /* O_DIRECT */
412
413 return ret;
414 }
415
416 int qemu_close(int fd)
417 {
418 /* Close fd that was dup'd from an fdset */
419 monitor_fdset_dup_fd_remove(fd);
420 return close(fd);
421 }
422
423 /*
424 * Delete a file from the filesystem, unless the filename is /dev/fdset/...
425 *
426 * Returns: On success, zero is returned. On error, -1 is returned,
427 * and errno is set appropriately.
428 */
429 int qemu_unlink(const char *name)
430 {
431 if (g_str_has_prefix(name, "/dev/fdset/")) {
432 return 0;
433 }
434
435 return unlink(name);
436 }
437
438 /*
439 * A variant of write(2) which handles partial write.
440 *
441 * Return the number of bytes transferred.
442 * Set errno if fewer than `count' bytes are written.
443 *
444 * This function don't work with non-blocking fd's.
445 * Any of the possibilities with non-blocking fd's is bad:
446 * - return a short write (then name is wrong)
447 * - busy wait adding (errno == EAGAIN) to the loop
448 */
449 ssize_t qemu_write_full(int fd, const void *buf, size_t count)
450 {
451 ssize_t ret = 0;
452 ssize_t total = 0;
453
454 while (count) {
455 ret = write(fd, buf, count);
456 if (ret < 0) {
457 if (errno == EINTR)
458 continue;
459 break;
460 }
461
462 count -= ret;
463 buf += ret;
464 total += ret;
465 }
466
467 return total;
468 }
469
470 /*
471 * Opens a socket with FD_CLOEXEC set
472 */
473 int qemu_socket(int domain, int type, int protocol)
474 {
475 int ret;
476
477 #ifdef SOCK_CLOEXEC
478 ret = socket(domain, type | SOCK_CLOEXEC, protocol);
479 if (ret != -1 || errno != EINVAL) {
480 return ret;
481 }
482 #endif
483 ret = socket(domain, type, protocol);
484 if (ret >= 0) {
485 qemu_set_cloexec(ret);
486 }
487
488 return ret;
489 }
490
491 /*
492 * Accept a connection and set FD_CLOEXEC
493 */
494 int qemu_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
495 {
496 int ret;
497
498 #ifdef CONFIG_ACCEPT4
499 ret = accept4(s, addr, addrlen, SOCK_CLOEXEC);
500 if (ret != -1 || errno != ENOSYS) {
501 return ret;
502 }
503 #endif
504 ret = accept(s, addr, addrlen);
505 if (ret >= 0) {
506 qemu_set_cloexec(ret);
507 }
508
509 return ret;
510 }
511
512 ssize_t qemu_send_full(int s, const void *buf, size_t count)
513 {
514 ssize_t ret = 0;
515 ssize_t total = 0;
516
517 while (count) {
518 ret = send(s, buf, count, 0);
519 if (ret < 0) {
520 if (errno == EINTR) {
521 continue;
522 }
523 break;
524 }
525
526 count -= ret;
527 buf += ret;
528 total += ret;
529 }
530
531 return total;
532 }
533
534 #ifdef _WIN32
535 static void socket_cleanup(void)
536 {
537 WSACleanup();
538 }
539 #endif
540
541 int socket_init(void)
542 {
543 #ifdef _WIN32
544 WSADATA Data;
545 int ret, err;
546
547 ret = WSAStartup(MAKEWORD(2, 2), &Data);
548 if (ret != 0) {
549 err = WSAGetLastError();
550 fprintf(stderr, "WSAStartup: %d\n", err);
551 return -1;
552 }
553 atexit(socket_cleanup);
554 #endif
555 return 0;
556 }
557
558
559 #ifndef CONFIG_IOVEC
560 static ssize_t
561 readv_writev(int fd, const struct iovec *iov, int iov_cnt, bool do_write)
562 {
563 unsigned i = 0;
564 ssize_t ret = 0;
565 ssize_t off = 0;
566 while (i < iov_cnt) {
567 ssize_t r = do_write
568 ? write(fd, iov[i].iov_base + off, iov[i].iov_len - off)
569 : read(fd, iov[i].iov_base + off, iov[i].iov_len - off);
570 if (r > 0) {
571 ret += r;
572 off += r;
573 if (off < iov[i].iov_len) {
574 continue;
575 }
576 } else if (!r) {
577 break;
578 } else if (errno == EINTR) {
579 continue;
580 } else {
581 /* else it is some "other" error,
582 * only return if there was no data processed. */
583 if (ret == 0) {
584 ret = -1;
585 }
586 break;
587 }
588 off = 0;
589 i++;
590 }
591 return ret;
592 }
593
594 ssize_t
595 readv(int fd, const struct iovec *iov, int iov_cnt)
596 {
597 return readv_writev(fd, iov, iov_cnt, false);
598 }
599
600 ssize_t
601 writev(int fd, const struct iovec *iov, int iov_cnt)
602 {
603 return readv_writev(fd, iov, iov_cnt, true);
604 }
605 #endif
606
607 /*
608 * Make sure data goes on disk, but if possible do not bother to
609 * write out the inode just for timestamp updates.
610 *
611 * Unfortunately even in 2009 many operating systems do not support
612 * fdatasync and have to fall back to fsync.
613 */
614 int qemu_fdatasync(int fd)
615 {
616 #ifdef CONFIG_FDATASYNC
617 return fdatasync(fd);
618 #else
619 return fsync(fd);
620 #endif
621 }