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