Skip to contentSkip to conversation

file descriptor passing using fd sets

PATCH Superseded Corey Bryant 3 participants 36 messages Jul 23, 2012 – Aug 7, 2012 Block layer

v5 of 11 Superseded Latest is v11 →

lore
Share & tools
lore
#7 lore raw

PATCH v5 3/6 monitor: Clean up fd sets on monitor disconnect

In reply to Corey Bryant

Each fd set has a boolean that keeps track of whether or not the fd set is in use by a monitor connection. When a monitor disconnects, all fds that are members of an fd set with refcount of zero are closed. This prevents any fd leakage associated with a client disconnect prior to using a passed fd.

v5:
-This patch is new in v5.
-This support addresses concerns from v4 regarding fd leakage
if the client disconnects unexpectedly. ([email protected], [email protected], [email protected])

---
 monitor.c |   15 +++++++++++++++
 1 file changed, 15 insertions(+)
monitor.c +15 -0
index e27dbbe..30b085f 100644
@@ -2538,6 +2538,19 @@ FdsetInfoList *qmp_query_fdsets(Error **errp)
     return fdset_list;
 }
 
+static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_t *mon_fdset_next;
+
+    QLIST_FOREACH_SAFE(mon_fdset, &mon->fdsets, next, mon_fdset_next) {
+        mon_fdset->in_use = in_use;
+        if (!in_use) {
+            monitor_fdset_cleanup(mon_fdset);
+        }
+    }
+}
+
 /* mon_cmds and info_cmds would be sorted at runtime */
 static mon_cmd_t mon_cmds[] = {
 #include "hmp-commands.h"
@@ -4751,9 +4764,11 @@ static void monitor_control_event(void *opaque, int event)
         data = get_qmp_greeting();
         monitor_json_emitter(mon, data);
         qobject_decref(data);
+        monitor_fdsets_set_in_use(mon, true);
         break;
     case CHR_EVENT_CLOSED:
         json_message_parser_destroy(&mon->mc->parser);
+        monitor_fdsets_set_in_use(mon, false);
         break;
     }
 }
Signature · 1 line
1.7.10.4
#12 lore raw

PATCH v5 6/6 block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

v2:
-Get rid of file_open and move dup code to qemu_open
([email protected])
-Use strtol wrapper instead of atoi ([email protected])

v3:
-Add note about fd leakage ([email protected])

v4
-Moved patch to be later in series ([email protected]) -Update qemu_open to check access mode flags and set flags that
can be set ([email protected], [email protected])

v5:
-This patch was overhauled quite a bit in this version, with
the addition of fd set and refcount support.
-Use qemu_set_cloexec() on dup'd fd ([email protected]) -Modify flags set by fcntl on dup'd fd ([email protected]) -Reduce syscalls when setting flags for dup'd fd ([email protected]) -Fix O_RDWR, O_RDONLY, O_WRONLY checks ([email protected])

---
 block/raw-posix.c |   24 +++++-----
 block/raw-win32.c |    2 +-
 block/vmdk.c      |    4 +-
 block/vpc.c       |    2 +-
 block/vvfat.c     |   12 ++---
 cutils.c          |    5 ++
 monitor.c         |   85 +++++++++++++++++++++++++++++++++
 monitor.h         |    4 ++
 osdep.c           |  138 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 qemu-common.h     |    3 +-
 qemu-tool.c       |   12 +++++
 11 files changed, 267 insertions(+), 24 deletions(-)
block/raw-posix.c +12 -12
index a172de3..5d0a801 100644
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs, const char *filename,
 out_free_buf:
     qemu_vfree(s->aligned_buf);
 out_close:
-    qemu_close(fd);
+    qemu_close(fd, filename);
     return -errno;
 }
 
@@ -376,7 +376,7 @@ static void raw_close(BlockDriverState *bs)
 {
     BDRVRawState *s = bs->opaque;
     if (s->fd >= 0) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
         s->fd = -1;
         if (s->aligned_buf != NULL)
             qemu_vfree(s->aligned_buf);
@@ -580,7 +580,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
             result = -errno;
         }
-        if (qemu_close(fd) != 0) {
+        if (qemu_close(fd, filename) != 0) {
             result = -errno;
         }
     }
@@ -850,7 +850,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
             if (fd < 0) {
                 bsdPath[strlen(bsdPath)-1] = '1';
             } else {
-                qemu_close(fd);
+                qemu_close(fd, bsdPath);
             }
             filename = bsdPath;
         }
@@ -889,7 +889,7 @@ static int fd_open(BlockDriverState *bs)
     last_media_present = (s->fd >= 0);
     if (s->fd >= 0 &&
         (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
         s->fd = -1;
 #ifdef DEBUG_FLOPPY
         printf("Floppy closed\n");
@@ -988,7 +988,7 @@ static int hdev_create(const char *filename, QEMUOptionParameter *options)
     else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
         ret = -ENOSPC;
 
-    qemu_close(fd);
+    qemu_close(fd, filename);
     return ret;
 }
 
@@ -1038,7 +1038,7 @@ static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
         return ret;
 
     /* close fd so that we can reopen it as needed */
-    qemu_close(s->fd);
+    qemu_close(s->fd, filename);
     s->fd = -1;
     s->fd_media_changed = 1;
 
@@ -1070,7 +1070,7 @@ static int floppy_probe_device(const char *filename)
         prio = 100;
 
 outc:
-    qemu_close(fd);
+    qemu_close(fd, filename);
 out:
     return prio;
 }
@@ -1105,14 +1105,14 @@ static void floppy_eject(BlockDriverState *bs, bool eject_flag)
     int fd;
 
     if (s->fd >= 0) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
         s->fd = -1;
     }
     fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
     if (fd >= 0) {
         if (ioctl(fd, FDEJECT, 0) < 0)
             perror("FDEJECT");
-        qemu_close(fd);
+        qemu_close(fd, bs->filename);
     }
 }
 
@@ -1173,7 +1173,7 @@ static int cdrom_probe_device(const char *filename)
         prio = 100;
 
 outc:
-    qemu_close(fd);
+    qemu_close(fd, filename);
 out:
     return prio;
 }
@@ -1281,7 +1281,7 @@ static int cdrom_reopen(BlockDriverState *bs)
      * FreeBSD seems to not notice sometimes...
      */
     if (s->fd >= 0)
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
     fd = qemu_open(bs->filename, s->open_flags, 0644);
     if (fd < 0) {
         s->fd = -1;
block/raw-win32.c +1 -1
index c56bf83..b795871 100644
@@ -261,7 +261,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         return -EIO;
     set_sparse(fd);
     ftruncate(fd, total_size * 512);
-    qemu_close(fd);
+    qemu_close(fd, filename);
     return 0;
 }
 
block/vmdk.c +2 -2
index daee426..7f1206b 100644
@@ -1258,7 +1258,7 @@ static int vmdk_create_extent(const char *filename, int64_t filesize,
 
     ret = 0;
  exit:
-    qemu_close(fd);
+    qemu_close(fd, filename);
     return ret;
 }
 
@@ -1506,7 +1506,7 @@ static int vmdk_create(const char *filename, QEMUOptionParameter *options)
     }
     ret = 0;
 exit:
-    qemu_close(fd);
+    qemu_close(fd, filename);
     return ret;
 }
 
block/vpc.c +1 -1
index c0b82c4..20f648a 100644
@@ -744,7 +744,7 @@ static int vpc_create(const char *filename, QEMUOptionParameter *options)
     }
 
  fail:
-    qemu_close(fd);
+    qemu_close(fd, filename);
     return ret;
 }
 
block/vvfat.c +6 -6
index 59d3c5b..cbc7543 100644
@@ -1105,7 +1105,7 @@ static inline void vvfat_close_current_file(BDRVVVFATState *s)
     if(s->current_mapping) {
 	s->current_mapping = NULL;
 	if (s->current_fd) {
-		qemu_close(s->current_fd);
+		qemu_close(s->current_fd, s->current_mapping->path);
 		s->current_fd = 0;
 	}
     }
@@ -2230,7 +2230,7 @@ static int commit_one_file(BDRVVVFATState* s,
     }
     if (offset > 0) {
         if (lseek(fd, offset, SEEK_SET) != offset) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
             g_free(cluster);
             return -3;
         }
@@ -2251,13 +2251,13 @@ static int commit_one_file(BDRVVVFATState* s,
 	    (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
 
         if (ret < 0) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
             g_free(cluster);
             return ret;
         }
 
         if (write(fd, cluster, rest_size) < 0) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
             g_free(cluster);
             return -2;
         }
@@ -2268,11 +2268,11 @@ static int commit_one_file(BDRVVVFATState* s,
 
     if (ftruncate(fd, size)) {
         perror("ftruncate()");
-        qemu_close(fd);
+        qemu_close(fd, mapping->path);
         g_free(cluster);
         return -4;
     }
-    qemu_close(fd);
+    qemu_close(fd, mapping->path);
     g_free(cluster);
 
     return commit_mappings(s, first_cluster, dir_index);
cutils.c +5 -0
index e2bc1b8..4e6bfdc 100644
@@ -375,3 +375,8 @@ int qemu_parse_fd(const char *param)
     }
     return fd;
 }
+
+int qemu_parse_fdset(const char *param)
+{
+    return qemu_parse_fd(param);
+}
monitor.c +85 -0

91 lines not on this page · raw message

monitor.h +4 -0
index 5f4de1b..1efed38 100644
@@ -86,4 +86,8 @@ int qmp_qom_set(Monitor *mon, const QDict *qdict, QObject **ret);
 
 int qmp_qom_get(Monitor *mon, const QDict *qdict, QObject **ret);
 
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags);
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id);
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id);
+
 #endif /* !MONITOR_H */
osdep.c +137 -1

163 lines not on this page · raw message

qemu-common.h +2 -1
index c8ddf2f..6b4123c 100644
@@ -147,6 +147,7 @@ int qemu_fls(int i);
 int qemu_fdatasync(int fd);
 int fcntl_setfl(int fd, int flag);
 int qemu_parse_fd(const char *param);
+int qemu_parse_fdset(const char *param);
 
 /*
  * strtosz() suffixes used to specify the default treatment of an
@@ -188,7 +189,7 @@ const char *path(const char *pathname);
 void *qemu_oom_check(void *ptr);
 
 int qemu_open(const char *name, int flags, ...);
-int qemu_close(int fd);
+int qemu_close(int fd, const char *name);
 ssize_t qemu_write_full(int fd, const void *buf, size_t count)
     QEMU_WARN_UNUSED_RESULT;
 ssize_t qemu_send_full(int fd, const void *buf, size_t count, int flags)
qemu-tool.c +12 -0
index 318c5fc..f4db9db 100644
@@ -31,6 +31,7 @@ struct QEMUBH
 };
 
 Monitor *cur_mon;
+Monitor *default_mon;
 
 int monitor_cur_is_qmp(void)
 {
@@ -57,6 +58,17 @@ void monitor_protocol_event(MonitorEvent event, QObject *data)
 {
 }
 
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    return -1;
+}
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+}
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id)
+{
+}
+
 int64_t cpu_get_clock(void)
 {
     return qemu_get_clock_ns(rt_clock);
Signature · 1 line
1.7.10.4
#11 lore raw

PATCH v5 5/6 block: Convert close calls to qemu_close

In reply to Corey Bryant

This patch converts all block layer close calls, that correspond to qemu_open calls, to qemu_close.

v5:
-This patch is new in v5. ([email protected], [email protected])

---
 block/raw-posix.c |   24 ++++++++++++------------
 block/raw-win32.c |    2 +-
 block/vmdk.c      |    4 ++--
 block/vpc.c       |    2 +-
 block/vvfat.c     |   12 ++++++------
 osdep.c           |    5 +++++
 qemu-common.h     |    1 +
 savevm.c          |    4 ++--
 8 files changed, 30 insertions(+), 24 deletions(-)
block/raw-posix.c +12 -12
index 7408a42..a172de3 100644
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs, const char *filename,
 out_free_buf:
     qemu_vfree(s->aligned_buf);
 out_close:
-    close(fd);
+    qemu_close(fd);
     return -errno;
 }
 
@@ -376,7 +376,7 @@ static void raw_close(BlockDriverState *bs)
 {
     BDRVRawState *s = bs->opaque;
     if (s->fd >= 0) {
-        close(s->fd);
+        qemu_close(s->fd);
         s->fd = -1;
         if (s->aligned_buf != NULL)
             qemu_vfree(s->aligned_buf);
@@ -580,7 +580,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
             result = -errno;
         }
-        if (close(fd) != 0) {
+        if (qemu_close(fd) != 0) {
             result = -errno;
         }
     }
@@ -850,7 +850,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
             if (fd < 0) {
                 bsdPath[strlen(bsdPath)-1] = '1';
             } else {
-                close(fd);
+                qemu_close(fd);
             }
             filename = bsdPath;
         }
@@ -889,7 +889,7 @@ static int fd_open(BlockDriverState *bs)
     last_media_present = (s->fd >= 0);
     if (s->fd >= 0 &&
         (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
-        close(s->fd);
+        qemu_close(s->fd);
         s->fd = -1;
 #ifdef DEBUG_FLOPPY
         printf("Floppy closed\n");
@@ -988,7 +988,7 @@ static int hdev_create(const char *filename, QEMUOptionParameter *options)
     else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
         ret = -ENOSPC;
 
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
@@ -1038,7 +1038,7 @@ static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
         return ret;
 
     /* close fd so that we can reopen it as needed */
-    close(s->fd);
+    qemu_close(s->fd);
     s->fd = -1;
     s->fd_media_changed = 1;
 
@@ -1070,7 +1070,7 @@ static int floppy_probe_device(const char *filename)
         prio = 100;
 
 outc:
-    close(fd);
+    qemu_close(fd);
 out:
     return prio;
 }
@@ -1105,14 +1105,14 @@ static void floppy_eject(BlockDriverState *bs, bool eject_flag)
     int fd;
 
     if (s->fd >= 0) {
-        close(s->fd);
+        qemu_close(s->fd);
         s->fd = -1;
     }
     fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
     if (fd >= 0) {
         if (ioctl(fd, FDEJECT, 0) < 0)
             perror("FDEJECT");
-        close(fd);
+        qemu_close(fd);
     }
 }
 
@@ -1173,7 +1173,7 @@ static int cdrom_probe_device(const char *filename)
         prio = 100;
 
 outc:
-    close(fd);
+    qemu_close(fd);
 out:
     return prio;
 }
@@ -1281,7 +1281,7 @@ static int cdrom_reopen(BlockDriverState *bs)
      * FreeBSD seems to not notice sometimes...
      */
     if (s->fd >= 0)
-        close(s->fd);
+        qemu_close(s->fd);
     fd = qemu_open(bs->filename, s->open_flags, 0644);
     if (fd < 0) {
         s->fd = -1;
block/raw-win32.c +1 -1
index 8d7838d..c56bf83 100644
@@ -261,7 +261,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         return -EIO;
     set_sparse(fd);
     ftruncate(fd, total_size * 512);
-    close(fd);
+    qemu_close(fd);
     return 0;
 }
 
block/vmdk.c +2 -2
index 557dc1b..daee426 100644
@@ -1258,7 +1258,7 @@ static int vmdk_create_extent(const char *filename, int64_t filesize,
 
     ret = 0;
  exit:
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
@@ -1506,7 +1506,7 @@ static int vmdk_create(const char *filename, QEMUOptionParameter *options)
     }
     ret = 0;
 exit:
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
block/vpc.c +1 -1
index 60ebf5a..c0b82c4 100644
@@ -744,7 +744,7 @@ static int vpc_create(const char *filename, QEMUOptionParameter *options)
     }
 
  fail:
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
block/vvfat.c +6 -6
index 22b586a..59d3c5b 100644
@@ -1105,7 +1105,7 @@ static inline void vvfat_close_current_file(BDRVVVFATState *s)
     if(s->current_mapping) {
 	s->current_mapping = NULL;
 	if (s->current_fd) {
-		close(s->current_fd);
+		qemu_close(s->current_fd);
 		s->current_fd = 0;
 	}
     }
@@ -2230,7 +2230,7 @@ static int commit_one_file(BDRVVVFATState* s,
     }
     if (offset > 0) {
         if (lseek(fd, offset, SEEK_SET) != offset) {
-            close(fd);
+            qemu_close(fd);
             g_free(cluster);
             return -3;
         }
@@ -2251,13 +2251,13 @@ static int commit_one_file(BDRVVVFATState* s,
 	    (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
 
         if (ret < 0) {
-            close(fd);
+            qemu_close(fd);
             g_free(cluster);
             return ret;
         }
 
         if (write(fd, cluster, rest_size) < 0) {
-            close(fd);
+            qemu_close(fd);
             g_free(cluster);
             return -2;
         }
@@ -2268,11 +2268,11 @@ static int commit_one_file(BDRVVVFATState* s,
 
     if (ftruncate(fd, size)) {
         perror("ftruncate()");
-        close(fd);
+        qemu_close(fd);
         g_free(cluster);
         return -4;
     }
-    close(fd);
+    qemu_close(fd);
     g_free(cluster);
 
     return commit_mappings(s, first_cluster, dir_index);
osdep.c +5 -0
index 03817f0..7b09dff 100644
@@ -104,6 +104,11 @@ int qemu_open(const char *name, int flags, ...)
     return ret;
 }
 
+int qemu_close(int fd)
+{
+    return close(fd);
+}
+
 /*
  * A variant of write(2) which handles partial write.
  *
qemu-common.h +1 -0
index 09676f5..c8ddf2f 100644
@@ -188,6 +188,7 @@ const char *path(const char *pathname);
 void *qemu_oom_check(void *ptr);
 
 int qemu_open(const char *name, int flags, ...);
+int qemu_close(int fd);
 ssize_t qemu_write_full(int fd, const void *buf, size_t count)
     QEMU_WARN_UNUSED_RESULT;
 ssize_t qemu_send_full(int fd, const void *buf, size_t count, int flags)
savevm.c +2 -2
index a15c163..3269dd4 100644
@@ -513,7 +513,7 @@ static void qemu_fill_buffer(QEMUFile *f)
  *
  * Returns f->close() return value, or 0 if close function is not set.
  */
-static int qemu_close(QEMUFile *f)
+static int _qemu_fclose(QEMUFile *f)
 {
     int ret = 0;
     if (f->close) {
@@ -535,7 +535,7 @@ int qemu_fclose(QEMUFile *f)
 {
     int ret;
     qemu_fflush(f);
-    ret = qemu_close(f);
+    ret = _qemu_fclose(f);
     /* If any error was spotted before closing, we should report it
      * instead of the close() return value.
      */
Signature · 1 line
1.7.10.4
#1 lore raw

PATCH v5 1/6 qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg

In reply to Corey Bryant

Set the close-on-exec flag for the file descriptor received via SCM_RIGHTS.

v4
-This patch is new in v4 ([email protected])

v5
-Fallback to FD_CLOEXEC if MSG_CMSG_CLOEXEC is not available
([email protected], [email protected])

---
 qemu-char.c |   10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
qemu-char.c +9 -1
index c2aaaee..eedf66d 100644
@@ -2263,9 +2263,17 @@ static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
     msg.msg_control = &msg_control;
     msg.msg_controllen = sizeof(msg_control);
 
+#ifdef MSG_CMSG_CLOEXEC
+    ret = recvmsg(s->fd, &msg, MSG_CMSG_CLOEXEC);
+#else
     ret = recvmsg(s->fd, &msg, 0);
-    if (ret > 0 && s->is_unix)
+    if (ret > 0) {
+        qemu_set_cloexec(s->fd);
+    }
+#endif
+    if (ret > 0 && s->is_unix) {
         unix_process_msgfd(chr, &msg);
+    }
 
     return ret;
 }
Signature · 1 line
1.7.10.4
#0 lore raw

v5 cover file descriptor passing using fd sets

libvirt's sVirt security driver provides SELinux MAC isolation for Qemu guest processes and their corresponding image files. In other words, sVirt uses SELinux to prevent a QEMU process from opening files that do not belong to it.

sVirt provides this support by labeling guests and resources with security labels that are stored in file system extended attributes. Some file systems, such as NFS, do not support the extended attribute security namespace, and therefore cannot support sVirt isolation.

A solution to this problem is to provide fd passing support, where libvirt opens files and passes file descriptors to QEMU. This, along with SELinux policy to prevent QEMU from opening files, can provide image file isolation for NFS files stored on the same NFS mount.

This patch series adds the add-fd, remove-fd, and query-fdsets QMP monitor commands, which allow file descriptors to be passed via SCM_RIGHTS, and assigned to specified fd sets. This allows fd sets to be created per file with fds having, for example, different access rights. When QEMU needs to reopen a file with different access rights, it can search for a matching fd in the fd set. Fd sets also allow for easy tracking of fds per file, helping to prevent fd leaks.

Support is also added to the block layer to allow QEMU to dup an fd from an fdset when the filename is of the /dev/fdset/nnn format, where nnn is the fd set ID.

No new SELinux policy is required to prevent open of NFS files (files with type nfs_t). The virt_use_nfs boolean type simply needs to be set to false, and open will be prevented (and dup will be allowed). For example:

    # setsebool virt_use_nfs 0
    # getsebool virt_use_nfs
    virt_use_nfs --> off

Corey Bryant (6):
qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg
qapi: Introduce add-fd, remove-fd, query-fdsets
monitor: Clean up fd sets on monitor disconnect
block: Convert open calls to qemu_open
block: Convert close calls to qemu_close
block: Enable qemu_open/close to work with fd sets

 block/raw-posix.c |   42 ++++-----
 block/raw-win32.c |    6 +-
 block/vdi.c       |    5 +-
 block/vmdk.c      |   25 +++---
 block/vpc.c       |    4 +-
 block/vvfat.c     |   16 ++--
 cutils.c          |    5 ++
 monitor.c         |  244 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 monitor.h         |    4 +
 osdep.c           |  141 +++++++++++++++++++++++++++++++
 qapi-schema.json  |   97 +++++++++++++++++++++
 qemu-char.c       |   10 ++-
 qemu-common.h     |    2 +
 qemu-tool.c       |   12 +++
 qmp-commands.hx   |  121 ++++++++++++++++++++++++++
 savevm.c          |    4 +-
 16 files changed, 684 insertions(+), 54 deletions(-)
Signature · 1 line
1.7.10.4
#8 lore raw

PATCH v5 4/6 block: Convert open calls to qemu_open

This patch converts all block layer open calls to qemu_open.

Note that this adds the O_CLOEXEC flag to the changed open paths when the O_CLOEXEC macro is defined.

---
v2:
-Convert calls to qemu_open instead of file_open ([email protected]) -Mention introduction of O_CLOEXEC ([email protected])

v3-v5:
-No changes

---
 block/raw-posix.c |   18 +++++++++---------
 block/raw-win32.c |    4 ++--
 block/vdi.c       |    5 +++--
 block/vmdk.c      |   21 +++++++++------------
 block/vpc.c       |    2 +-
 block/vvfat.c     |    4 ++--
 6 files changed, 26 insertions(+), 28 deletions(-)
block/raw-posix.c +9 -9
index 0dce089..7408a42 100644
@@ -572,8 +572,8 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
-              0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
+                   0644);
     if (fd < 0) {
         result = -errno;
     } else {
@@ -846,7 +846,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
         if ( bsdPath[ 0 ] != '\0' ) {
             strcat(bsdPath,"s0");
             /* some CDs don't have a partition 0 */
-            fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
+            fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
             if (fd < 0) {
                 bsdPath[strlen(bsdPath)-1] = '1';
             } else {
@@ -903,7 +903,7 @@ static int fd_open(BlockDriverState *bs)
 #endif
             return -EIO;
         }
-        s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
+        s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
         if (s->fd < 0) {
             s->fd_error_time = get_clock();
             s->fd_got_error = 1;
@@ -977,7 +977,7 @@ static int hdev_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_BINARY);
+    fd = qemu_open(filename, O_WRONLY | O_BINARY);
     if (fd < 0)
         return -errno;
 
@@ -1055,7 +1055,7 @@ static int floppy_probe_device(const char *filename)
     if (strstart(filename, "/dev/fd", NULL))
         prio = 50;
 
-    fd = open(filename, O_RDONLY | O_NONBLOCK);
+    fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
     if (fd < 0) {
         goto out;
     }
@@ -1108,7 +1108,7 @@ static void floppy_eject(BlockDriverState *bs, bool eject_flag)
         close(s->fd);
         s->fd = -1;
     }
-    fd = open(bs->filename, s->open_flags | O_NONBLOCK);
+    fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
     if (fd >= 0) {
         if (ioctl(fd, FDEJECT, 0) < 0)
             perror("FDEJECT");
@@ -1158,7 +1158,7 @@ static int cdrom_probe_device(const char *filename)
     int prio = 0;
     struct stat st;
 
-    fd = open(filename, O_RDONLY | O_NONBLOCK);
+    fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
     if (fd < 0) {
         goto out;
     }
@@ -1282,7 +1282,7 @@ static int cdrom_reopen(BlockDriverState *bs)
      */
     if (s->fd >= 0)
         close(s->fd);
-    fd = open(bs->filename, s->open_flags, 0644);
+    fd = qemu_open(bs->filename, s->open_flags, 0644);
     if (fd < 0) {
         s->fd = -1;
         return -EIO;
block/raw-win32.c +2 -2
index e4b0b75..8d7838d 100644
@@ -255,8 +255,8 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
-              0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
+                   0644);
     if (fd < 0)
         return -EIO;
     set_sparse(fd);
block/vdi.c +3 -2
index 57325d6..c4f1529 100644
@@ -653,8 +653,9 @@ static int vdi_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-              0644);
+    fd = qemu_open(filename,
+                   O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                   0644);
     if (fd < 0) {
         return -errno;
     }
block/vmdk.c +9 -12
index 18e9b4c..557dc1b 100644
@@ -1161,10 +1161,9 @@ static int vmdk_create_extent(const char *filename, int64_t filesize,
     VMDK4Header header;
     uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
 
-    fd = open(
-        filename,
-        O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-        0644);
+    fd = qemu_open(filename,
+                   O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                   0644);
     if (fd < 0) {
         return -errno;
     }
@@ -1484,15 +1483,13 @@ static int vmdk_create(const char *filename, QEMUOptionParameter *options)
             (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
             total_size / (int64_t)(63 * 16 * 512));
     if (split || flat) {
-        fd = open(
-                filename,
-                O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-                0644);
+        fd = qemu_open(filename,
+                       O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                       0644);
     } else {
-        fd = open(
-                filename,
-                O_WRONLY | O_BINARY | O_LARGEFILE,
-                0644);
+        fd = qemu_open(filename,
+                       O_WRONLY | O_BINARY | O_LARGEFILE,
+                       0644);
     }
     if (fd < 0) {
         return -errno;
block/vpc.c +1 -1
index 5cd13d1..60ebf5a 100644
@@ -678,7 +678,7 @@ static int vpc_create(const char *filename, QEMUOptionParameter *options)
     }
 
     /* Create the file */
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
     if (fd < 0) {
         return -EIO;
     }
block/vvfat.c +2 -2
index 7b1dcee..22b586a 100644
@@ -1162,7 +1162,7 @@ static int open_file(BDRVVVFATState* s,mapping_t* mapping)
     if(!s->current_mapping ||
 	    strcmp(s->current_mapping->path,mapping->path)) {
 	/* open file */
-	int fd = open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
+	int fd = qemu_open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
 	if(fd<0)
 	    return -1;
 	vvfat_close_current_file(s);
@@ -2221,7 +2221,7 @@ static int commit_one_file(BDRVVVFATState* s,
     for (i = s->cluster_size; i < offset; i += s->cluster_size)
 	c = modified_fat_get(s, c);
 
-    fd = open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
+    fd = qemu_open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
     if (fd < 0) {
 	fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
 		strerror(errno), errno);
Signature · 1 line
1.7.10.4
#4 lore raw

PATCH v5 2/6 qapi: Introduce add-fd, remove-fd, query-fdsets

In reply to Corey Bryant

This patch adds support that enables passing of file descriptors to the QEMU monitor where they will be stored in specified file descriptor sets.

A file descriptor set can be used by a client like libvirt to store file descriptors for the same file. This allows the client to open a file with different access modes (O_RDWR, O_WRONLY, O_RDONLY) and add/remove the passed fds to/from an fd set as needed. This will allow QEMU to (in a later patch in this series) "open" and "reopen" the same file by dup()ing the fd in the fd set that corresponds to the file, where the fd has the matching access mode flag that QEMU requests.

The new QMP commands are:
add-fd: Add a file descriptor to an fd set
remove-fd: Remove a file descriptor from an fd set
query-fdsets: Return information describing all fd sets

Note: These commands are not compatible with the existing getfd and closefd QMP commands.

v5:
-This patch is new in v5 and replaces the pass-fd QMP command
from v4.
-By grouping fds in fd sets, we ease managability with an fd
set per file, addressing concerns raised in v4 about handling "reopens" and preventing fd leakage. ([email protected], [email protected], [email protected])

---
 monitor.c        |  144 +++++++++++++++++++++++++++++++++++++++++++++++++++++-
 qapi-schema.json |   97 ++++++++++++++++++++++++++++++++++++
 qmp-commands.hx  |  121 +++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 361 insertions(+), 1 deletion(-)
monitor.c +143 -1
index 09aa3cd..e27dbbe 100644
@@ -140,6 +140,24 @@ struct mon_fd_t {
     QLIST_ENTRY(mon_fd_t) next;
 };
 
+/* file descriptor associated with a file descriptor set */
+typedef struct mon_fdset_fd_t mon_fdset_fd_t;
+struct mon_fdset_fd_t {
+    int fd;
+    bool removed;
+    QLIST_ENTRY(mon_fdset_fd_t) next;
+};
+
+/* file descriptor set containing fds passed via SCM_RIGHTS */
+typedef struct mon_fdset_t mon_fdset_t;
+struct mon_fdset_t {
+    int64_t id;
+    int refcount;
+    bool in_use;
+    QLIST_HEAD(, mon_fdset_fd_t) fds;
+    QLIST_ENTRY(mon_fdset_t) next;
+};
+
 typedef struct MonitorControl {
     QObject *id;
     JSONMessageParser parser;
@@ -176,7 +194,8 @@ struct Monitor {
     int print_calls_nr;
 #endif
     QError *error;
-    QLIST_HEAD(,mon_fd_t) fds;
+    QLIST_HEAD(, mon_fd_t) fds;
+    QLIST_HEAD(, mon_fdset_t) fdsets;
     QLIST_ENTRY(Monitor) entry;
 };
 
@@ -2396,6 +2415,129 @@ int monitor_get_fd(Monitor *mon, const char *fdname)
     return -1;
 }
 
+static void monitor_fdset_cleanup(mon_fdset_t *mon_fdset)
+{
+    mon_fdset_fd_t *mon_fdset_fd;
+    mon_fdset_fd_t *mon_fdset_fd_next;
+
+    if (mon_fdset->refcount != 0) {
+        return;
+    }
+
+    QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
+        if (!mon_fdset->in_use || mon_fdset_fd->removed) {
+            close(mon_fdset_fd->fd);
+            QLIST_REMOVE(mon_fdset_fd, next);
+            g_free(mon_fdset_fd);
+        }
+    }
+
+    if (QLIST_EMPTY(&mon_fdset->fds)) {
+        QLIST_REMOVE(mon_fdset, next);
+        g_free(mon_fdset);
+    }
+}
+
+AddfdInfo *qmp_add_fd(int64_t fdset_id, Error **errp)
+{
+    int fd;
+    Monitor *mon = cur_mon;
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    AddfdInfo *fdinfo;
+
+    fd = qemu_chr_fe_get_msgfd(mon->chr);
+    if (fd == -1) {
+        qerror_report(QERR_FD_NOT_SUPPLIED);
+        return NULL;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            break;
+        }
+    }
+
+    if (!mon_fdset) {
+        mon_fdset = g_malloc0(sizeof(*mon_fdset));
+        mon_fdset->id = fdset_id;
+        mon_fdset->refcount = 0;
+        mon_fdset->in_use = true;
+        QLIST_INSERT_HEAD(&mon->fdsets, mon_fdset, next);
+    }
+
+    mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
+    mon_fdset_fd->fd = fd;
+    mon_fdset_fd->removed = false;
+    QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
+
+    fdinfo = g_malloc0(sizeof(*fdinfo));
+    fdinfo->fdset_id = fdset_id;
+    fdinfo->fd = fd;
+
+    return fdinfo;
+}
+
+void qmp_remove_fd(int64_t fdset_id, int64_t fd, Error **errp)
+{
+    Monitor *mon = cur_mon;
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    char fd_str[20];
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->fd != fd) {
+                continue;
+            }
+            mon_fdset_fd->removed = true;
+            monitor_fdset_cleanup(mon_fdset);
+            return;
+        }
+    }
+    snprintf(fd_str, sizeof(fd_str), "%ld", fd);
+    qerror_report(QERR_FD_NOT_FOUND, fd_str);
+}
+
+FdsetInfoList *qmp_query_fdsets(Error **errp)
+{
+    Monitor *mon = cur_mon;
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    FdsetInfoList *fdset_list = NULL;
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
+        FdsetFdInfoList *fdsetfd_list = NULL;
+
+        fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
+        fdset_info->value->fdset_id = mon_fdset->id;
+        fdset_info->value->refcount = mon_fdset->refcount;
+        fdset_info->value->in_use = mon_fdset->in_use;
+
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            FdsetFdInfoList *fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
+
+            fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
+            fdsetfd_info->value->fd = mon_fdset_fd->fd;
+            fdsetfd_info->value->removed = mon_fdset_fd->removed;
+
+            fdsetfd_info->next = fdsetfd_list;
+            fdsetfd_list = fdsetfd_info;
+        }
+
+        fdset_info->value->fds = fdsetfd_list;
+
+        fdset_info->next = fdset_list;
+        fdset_list = fdset_info;
+    }
+
+    return fdset_list;
+}
+
 /* mon_cmds and info_cmds would be sorted at runtime */
 static mon_cmd_t mon_cmds[] = {
 #include "hmp-commands.h"
qapi-schema.json +97 -0

100 lines not on this page · raw message

qmp-commands.hx +121 -0

127 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#13 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant
Quoted 486 lines · Corey Bryant

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

v2:
-Get rid of file_open and move dup code to qemu_open
([email protected])
-Use strtol wrapper instead of atoi ([email protected])

v3:
-Add note about fd leakage ([email protected])

v4
-Moved patch to be later in series ([email protected]) -Update qemu_open to check access mode flags and set flags that
can be set ([email protected], [email protected])

v5:
-This patch was overhauled quite a bit in this version, with
the addition of fd set and refcount support.
-Use qemu_set_cloexec() on dup'd fd ([email protected]) -Modify flags set by fcntl on dup'd fd ([email protected]) -Reduce syscalls when setting flags for dup'd fd ([email protected]) -Fix O_RDWR, O_RDONLY, O_WRONLY checks ([email protected])

---
  block/raw-posix.c |   24 +++++-----
  block/raw-win32.c |    2 +-
  block/vmdk.c      |    4 +-
  block/vpc.c       |    2 +-
  block/vvfat.c     |   12 ++---
  cutils.c          |    5 ++
  monitor.c         |   85 +++++++++++++++++++++++++++++++++
  monitor.h         |    4 ++
  osdep.c           |  138 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
  qemu-common.h     |    3 +-
  qemu-tool.c       |   12 +++++
  11 files changed, 267 insertions(+), 24 deletions(-)
block/raw-posix.c +12 -12
index a172de3..5d0a801 100644
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs, const char *filename,
  out_free_buf:
      qemu_vfree(s->aligned_buf);
  out_close:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return -errno;
  }
 
@@ -376,7 +376,7 @@ static void raw_close(BlockDriverState *bs)
  {
      BDRVRawState *s = bs->opaque;
      if (s->fd >= 0) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
          s->fd = -1;
          if (s->aligned_buf != NULL)
              qemu_vfree(s->aligned_buf);
@@ -580,7 +580,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
          if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
              result = -errno;
          }
-        if (qemu_close(fd) != 0) {
+        if (qemu_close(fd, filename) != 0) {
              result = -errno;
          }
      }
@@ -850,7 +850,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
              if (fd < 0) {
                  bsdPath[strlen(bsdPath)-1] = '1';
              } else {
-                qemu_close(fd);
+                qemu_close(fd, bsdPath);
              }
              filename = bsdPath;
          }
@@ -889,7 +889,7 @@ static int fd_open(BlockDriverState *bs)
      last_media_present = (s->fd >= 0);
      if (s->fd >= 0 &&
          (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
          s->fd = -1;
  #ifdef DEBUG_FLOPPY
          printf("Floppy closed\n");
@@ -988,7 +988,7 @@ static int hdev_create(const char *filename, QEMUOptionParameter *options)
      else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
          ret = -ENOSPC;
 
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
 
@@ -1038,7 +1038,7 @@ static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
          return ret;
 
      /* close fd so that we can reopen it as needed */
-    qemu_close(s->fd);
+    qemu_close(s->fd, filename);
      s->fd = -1;
      s->fd_media_changed = 1;
 
@@ -1070,7 +1070,7 @@ static int floppy_probe_device(const char *filename)
          prio = 100;
 
  outc:
-    qemu_close(fd);
+    qemu_close(fd, filename);
  out:
      return prio;
  }
@@ -1105,14 +1105,14 @@ static void floppy_eject(BlockDriverState *bs, bool eject_flag)
      int fd;
 
      if (s->fd >= 0) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
          s->fd = -1;
      }
      fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
      if (fd >= 0) {
          if (ioctl(fd, FDEJECT, 0) < 0)
              perror("FDEJECT");
-        qemu_close(fd);
+        qemu_close(fd, bs->filename);
      }
  }
 
@@ -1173,7 +1173,7 @@ static int cdrom_probe_device(const char *filename)
          prio = 100;
 
  outc:
-    qemu_close(fd);
+    qemu_close(fd, filename);
  out:
      return prio;
  }
@@ -1281,7 +1281,7 @@ static int cdrom_reopen(BlockDriverState *bs)
       * FreeBSD seems to not notice sometimes...
       */
      if (s->fd >= 0)
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
      fd = qemu_open(bs->filename, s->open_flags, 0644);
      if (fd < 0) {
          s->fd = -1;
block/raw-win32.c +1 -1
index c56bf83..b795871 100644
@@ -261,7 +261,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
          return -EIO;
      set_sparse(fd);
      ftruncate(fd, total_size * 512);
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return 0;
  }
 
block/vmdk.c +2 -2
index daee426..7f1206b 100644
@@ -1258,7 +1258,7 @@ static int vmdk_create_extent(const char *filename, int64_t filesize,
 
      ret = 0;
   exit:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
 
@@ -1506,7 +1506,7 @@ static int vmdk_create(const char *filename, QEMUOptionParameter *options)
      }
      ret = 0;
  exit:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
 
block/vpc.c +1 -1
index c0b82c4..20f648a 100644
@@ -744,7 +744,7 @@ static int vpc_create(const char *filename, QEMUOptionParameter *options)
      }
 
   fail:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
 
block/vvfat.c +6 -6
index 59d3c5b..cbc7543 100644
@@ -1105,7 +1105,7 @@ static inline void vvfat_close_current_file(BDRVVVFATState *s)
      if(s->current_mapping) {
  	s->current_mapping = NULL;
  	if (s->current_fd) {
-		qemu_close(s->current_fd);
+		qemu_close(s->current_fd, s->current_mapping->path);
  		s->current_fd = 0;
  	}
      }
@@ -2230,7 +2230,7 @@ static int commit_one_file(BDRVVVFATState* s,
      }
      if (offset > 0) {
          if (lseek(fd, offset, SEEK_SET) != offset) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
              g_free(cluster);
              return -3;
          }
@@ -2251,13 +2251,13 @@ static int commit_one_file(BDRVVVFATState* s,
  	    (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
 
          if (ret < 0) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
              g_free(cluster);
              return ret;
          }
 
          if (write(fd, cluster, rest_size) < 0) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
              g_free(cluster);
              return -2;
          }
@@ -2268,11 +2268,11 @@ static int commit_one_file(BDRVVVFATState* s,
 
      if (ftruncate(fd, size)) {
          perror("ftruncate()");
-        qemu_close(fd);
+        qemu_close(fd, mapping->path);
          g_free(cluster);
          return -4;
      }
-    qemu_close(fd);
+    qemu_close(fd, mapping->path);
      g_free(cluster);
 
      return commit_mappings(s, first_cluster, dir_index);
cutils.c +5 -0
index e2bc1b8..4e6bfdc 100644
@@ -375,3 +375,8 @@ int qemu_parse_fd(const char *param)
      }
      return fd;
  }
+
+int qemu_parse_fdset(const char *param)
+{
+    return qemu_parse_fd(param);
+}
monitor.c +85 -0
index 30b085f..fddd2b5 100644
@@ -2551,6 +2551,91 @@ static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use)
      }
  }
 
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount++;
+            break;
+        }
+    }
+}
+
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount--;
+            if (mon_fdset->refcount == 0) {
+                monitor_fdset_cleanup(mon_fdset);
+            }
+            break;
+        }
+    }
+}
+
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
+            if (mon_fd_flags == -1) {
+                return -1;
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_WRONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_WRONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            }
+        }
+        errno = EACCES;
+        return -1;
+    }
+    errno = ENOENT;
+    return -1;
+}
+
  /* mon_cmds and info_cmds would be sorted at runtime */
  static mon_cmd_t mon_cmds[] = {
  #include "hmp-commands.h"
monitor.h +4 -0
index 5f4de1b..1efed38 100644
@@ -86,4 +86,8 @@ int qmp_qom_set(Monitor *mon, const QDict *qdict, QObject **ret);
 
  int qmp_qom_get(Monitor *mon, const QDict *qdict, QObject **ret);
 
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags);
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id);
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id);
+
  #endif /* !MONITOR_H */
osdep.c +79 -0
index 7b09dff..0303cdd 100644
@@ -47,6 +47,7 @@ extern int madvise(caddr_t, size_t, int);
  #include "qemu-common.h"
  #include "trace.h"
  #include "qemu_socket.h"
+#include "monitor.h"
 
  static const char *qemu_version = QEMU_VERSION;
 
@@ -75,6 +76,79 @@ int qemu_madvise(void *addr, size_t len, int advice)
  #endif
  }
 
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup(int fd, int flags)
+{
+    int i;
+    int ret;
+    int serrno;
+    int dup_flags;
+    int setfl_flags[] = { O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,
+                          O_NONBLOCK, 0 };
+
+    if (flags & O_CLOEXEC) {
+        ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+        if (ret == -1 && errno == EINVAL) {
+            ret = dup(fd);
+            if (ret != -1 && fcntl_setfl(ret, O_CLOEXEC) == -1) {
+                goto fail;
+            }
+        }
+    } else {
+        ret = dup(fd);
+    }
+
+    if (ret == -1) {
+        goto fail;
+    }
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }
+
+    /* Set/unset flags that we can with fcntl */
+    i = 0;
+    while (setfl_flags[i] != 0) {
+        if (flags & setfl_flags[i]) {
+            dup_flags = (dup_flags | setfl_flags[i]);
+        } else {
+            dup_flags = (dup_flags & ~setfl_flags[i]);
+        }
+        i++;
+    }
+
+    if (fcntl(ret, F_SETFL, dup_flags) == -1) {
+        goto fail;
+    }
+
+    /* Truncate the file in the cases that open() would truncate it */
+    if (flags & O_TRUNC ||
+            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
+        if (ftruncate(ret, 0) == -1) {
+            goto fail;
+        }
+    }
+
+    qemu_set_cloexec(ret);
+
+    return ret;
+
+fail:
+    serrno = errno;
+    if (ret != -1) {
+        close(ret);
+    }
+    errno = serrno;
+    return -1;
+}
 
  /*
   * Opens a file with FD_CLOEXEC set
@@ -84,6 +158,36 @@ int qemu_open(const char *name, int flags, ...)
      int ret;
      int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {

osdep.c int qemu_open(const char *name, int flags, ...) · line 175

Quoted 10 lines
osdep.c +10 -0
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
+        }
+
+        fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);

I know that use of default_mon in this patch is not correct, but I wanted to get these patches out for review. I used default_mon for testing because cur_mon wasn't pointing to the monitor I'd added fd sets to. I need to figure out why.

Quoted 112 lines
osdep.c +48 -1
+        if (fd == -1) {
+            return -1;
+        }
+
+        dupfd = qemu_dup(fd, flags);
+        if (fd == -1) {
+            return -1;
+        }
+
+        monitor_fdset_increment_refcount(default_mon, fdset_id);
+
+        return dupfd;
+    }
+#endif
+
      if (flags & O_CREAT) {
          va_list ap;
 
@@ -104,8 +208,40 @@ int qemu_open(const char *name, int flags, ...)
      return ret;
  }
 
-int qemu_close(int fd)
+int qemu_close(int fd, const char *name)
  {
+    const char *fdset_id_str;
+
+    /* Close fd that was dup'd from an fdset */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int ret;
+        int64_t fdset_id;
+        int fdset_fd;
+        int flags;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            return -1;
+        }
+
+        flags = fcntl(fd, F_GETFL);
+        if (flags == -1) {
+            return -1;
+        }
+
+        fdset_fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);
+        if (fdset_fd == -1) {
+            return -1;
+        }
+
+        ret = close(fd);
+        if (ret == 0) {
+            monitor_fdset_decrement_refcount(default_mon, fdset_id);
+        }
+
+        return ret;
+    }
+
      return close(fd);
  }
 
qemu-common.h +2 -1
index c8ddf2f..6b4123c 100644
@@ -147,6 +147,7 @@ int qemu_fls(int i);
  int qemu_fdatasync(int fd);
  int fcntl_setfl(int fd, int flag);
  int qemu_parse_fd(const char *param);
+int qemu_parse_fdset(const char *param);
 
  /*
   * strtosz() suffixes used to specify the default treatment of an
@@ -188,7 +189,7 @@ const char *path(const char *pathname);
  void *qemu_oom_check(void *ptr);
 
  int qemu_open(const char *name, int flags, ...);
-int qemu_close(int fd);
+int qemu_close(int fd, const char *name);
  ssize_t qemu_write_full(int fd, const void *buf, size_t count)
      QEMU_WARN_UNUSED_RESULT;
  ssize_t qemu_send_full(int fd, const void *buf, size_t count, int flags)
qemu-tool.c +12 -0
index 318c5fc..f4db9db 100644
@@ -31,6 +31,7 @@ struct QEMUBH
  };
 
  Monitor *cur_mon;
+Monitor *default_mon;
 
  int monitor_cur_is_qmp(void)
  {
@@ -57,6 +58,17 @@ void monitor_protocol_event(MonitorEvent event, QObject *data)
  {
  }
 
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    return -1;
+}
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+}
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id)
+{
+}
+
  int64_t cpu_get_clock(void)
  {
      return qemu_get_clock_ns(rt_clock);
Signature · 2 lines
Regards,
Corey
#2 lore raw

Re: [Qemu-devel] [PATCH v5 1/6] qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg

In reply to Corey Bryant
Quoted 6 lines · Corey Bryant

Set the close-on-exec flag for the file descriptor received via SCM_RIGHTS.

+++ b/qemu-char.c

qemu-char.c static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len) · line 2271

Quoted 10 lines
qemu-char.c +5 -1
@@ -2263,9 +2263,17 @@ static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
     msg.msg_control = &msg_control;
     msg.msg_controllen = sizeof(msg_control);
 
+#ifdef MSG_CMSG_CLOEXEC
+    ret = recvmsg(s->fd, &msg, MSG_CMSG_CLOEXEC);
+#else
     ret = recvmsg(s->fd, &msg, 0);
-    if (ret > 0 && s->is_unix)
+    if (ret > 0) {
+        qemu_set_cloexec(s->fd);

Wrong fd. You aren't changing cloexec on the socket (s->fd), but on the fd that was received via msg (which you don't know at this point in time).

qemu-char.c static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len) · line 2275

Quoted 4 lines
qemu-char.c +3 -0
+    }
+#endif
+    if (ret > 0 && s->is_unix) {
         unix_process_msgfd(chr, &msg);

Only here do you know what fd you received.

I would write it more like:

int flags = 0;
#ifdef MSG_CMSG_CLOEXEC
flags |= MSG_CMSG_CLOEXEC
#endif
ret = recvmsg(s->fd, &msg, flags);

if (ret > 0 && s->is_unix) {
    unix_process_msgfd(chr, &msg);

#ifndef MSG_CMSG_CLOEXEC
qemu_set_cloexec(/* fd determined from msg */)
#endif
}

which almost implies that unix_process_msgfd() should be the function that sets cloexec, but without wasting the time doing so if recvmsg already did the job.

Signature · 2 lines
Eric Blake   [email protected]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#3 lore raw

Re: [Qemu-devel] [PATCH v5 1/6] qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg

Quoted 10 lines · Eric Blake
Quoted 9 lines · Corey Bryant

Set the close-on-exec flag for the file descriptor received via SCM_RIGHTS.

+++ b/qemu-char.c

qemu-char.c +0 -0
@@ -2263,9 +2263,17 @@ static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
      msg.msg_control = &msg_control;
      msg.msg_controllen = sizeof(msg_control);
 
Quoted 11 lines

qemu-char.c static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len) · line 2271

Quoted 7 lines
qemu-char.c +5 -1
+#ifdef MSG_CMSG_CLOEXEC
+    ret = recvmsg(s->fd, &msg, MSG_CMSG_CLOEXEC);
+#else
      ret = recvmsg(s->fd, &msg, 0);
-    if (ret > 0 && s->is_unix)
+    if (ret > 0) {
+        qemu_set_cloexec(s->fd);

Wrong fd. You aren't changing cloexec on the socket (s->fd), but on the fd that was received via msg (which you don't know at this point in time).

Ugh, that's bad.

Quoted 16 lines

qemu-char.c static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len) · line 2275

Quoted 4 lines
qemu-char.c +3 -0
+    }
+#endif
+    if (ret > 0 && s->is_unix) {
          unix_process_msgfd(chr, &msg);

Only here do you know what fd you received.

I would write it more like:

int flags = 0;
#ifdef MSG_CMSG_CLOEXEC
flags |= MSG_CMSG_CLOEXEC
#endif
ret = recvmsg(s->fd, &msg, flags);

if (ret > 0 && s->is_unix) {
     unix_process_msgfd(chr, &msg);
Quoted 9 lines

#ifndef MSG_CMSG_CLOEXEC
qemu_set_cloexec(/* fd determined from msg */)
#endif
}

which almost implies that unix_process_msgfd() should be the function that sets cloexec, but without wasting the time doing so if recvmsg already did the job.

Thanks for the suggestion and catching this. I'll take this into account in the next version.

Signature · 2 lines
Regards,
Corey
#20 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant

Am 23.07.2012 15:08, schrieb Corey Bryant:

Quoted 57 lines

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

v2:
-Get rid of file_open and move dup code to qemu_open
([email protected])
-Use strtol wrapper instead of atoi ([email protected])

v3:
-Add note about fd leakage ([email protected])

v4
-Moved patch to be later in series ([email protected]) -Update qemu_open to check access mode flags and set flags that
can be set ([email protected], [email protected])

v5:
-This patch was overhauled quite a bit in this version, with
the addition of fd set and refcount support.
-Use qemu_set_cloexec() on dup'd fd ([email protected]) -Modify flags set by fcntl on dup'd fd ([email protected]) -Reduce syscalls when setting flags for dup'd fd ([email protected]) -Fix O_RDWR, O_RDONLY, O_WRONLY checks ([email protected])

---
 block/raw-posix.c |   24 +++++-----
 block/raw-win32.c |    2 +-
 block/vmdk.c      |    4 +-
 block/vpc.c       |    2 +-
 block/vvfat.c     |   12 ++---
 cutils.c          |    5 ++
 monitor.c         |   85 +++++++++++++++++++++++++++++++++
 monitor.h         |    4 ++
 osdep.c           |  138 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 qemu-common.h     |    3 +-
 qemu-tool.c       |   12 +++++
 11 files changed, 267 insertions(+), 24 deletions(-)
block/raw-posix.c +0 -0
index a172de3..5d0a801 100644

block/raw-posix.c static int raw_open_common(BlockDriverState *bs, const char *filename, · line 276

Quoted 7 lines
block/raw-posix.c +1 -1
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs, const char *filename,
 out_free_buf:
     qemu_vfree(s->aligned_buf);
 out_close:
-    qemu_close(fd);
+    qemu_close(fd, filename);
     return -errno;
 }

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

But if we decided to keep it like this, please use the right interface from the beginning in patch 5 instead of updating it here.

Quoted 28 lines
block/raw-posix.c +24 -0
@@ -2551,6 +2551,91 @@ static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use)
     }
 }
 
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount++;
+            break;
+        }
+    }
+}
+
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+

block/raw-posix.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2587

Quoted 10 lines
block/raw-posix.c +10 -0
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount--;
+            if (mon_fdset->refcount == 0) {
+                monitor_fdset_cleanup(mon_fdset);
+            }
+            break;
+        }
+    }
+}

These two functions are almost the same. Would a monitor_fdset_update_refcount(mon, fdset_id, value) make sense? These functions could then be kept as thin wrappers around it, or they could even be dropped completely.

Quoted 33 lines
block/raw-posix.c +33 -0
+
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
+            if (mon_fd_flags == -1) {
+                return -1;
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:

block/raw-posix.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2630

Quoted 10 lines
block/raw-posix.c +10 -0
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_WRONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_WRONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            }

I think you mean:

  if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
      return mon_fdset_fd->fd;
  }

What about other flags that cannot be set with fcntl(), like O_SYNC on older kernels or possibly non-Linux? (The block layer doesn't use it any more, but I think we want to keep the function generally useful)

Quoted 43 lines
block/raw-posix.c +35 -0
+        }
+        errno = EACCES;
+        return -1;
+    }
+    errno = ENOENT;
+    return -1;
+}
+
 /* mon_cmds and info_cmds would be sorted at runtime */
 static mon_cmd_t mon_cmds[] = {
 #include "hmp-commands.h"
@@ -75,6 +76,79 @@ int qemu_madvise(void *addr, size_t len, int advice)
 #endif
 }
 
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup(int fd, int flags)
+{
+    int i;
+    int ret;
+    int serrno;
+    int dup_flags;
+    int setfl_flags[] = { O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,
+                          O_NONBLOCK, 0 };
+
+    if (flags & O_CLOEXEC) {
+        ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+        if (ret == -1 && errno == EINVAL) {
+            ret = dup(fd);
+            if (ret != -1 && fcntl_setfl(ret, O_CLOEXEC) == -1) {
+                goto fail;
+            }
+        }
+    } else {
+        ret = dup(fd);
+    }
+
+    if (ret == -1) {
+        goto fail;
+    }

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 115

Quoted 10 lines
block/raw-posix.c +10 -0
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }

It's worth trying to set it before failing, newer kernels can do it. But as I said above, if you can fail here, it makes sense to consider O_SYNC when selecting the right file descriptor from the fdset.

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 125

Quoted 10 lines
block/raw-posix.c +10 -0
+    /* Set/unset flags that we can with fcntl */
+    i = 0;
+    while (setfl_flags[i] != 0) {
+        if (flags & setfl_flags[i]) {
+            dup_flags = (dup_flags | setfl_flags[i]);
+        } else {
+            dup_flags = (dup_flags & ~setfl_flags[i]);
+        }
+        i++;
+    }

What about this instead of the loop:

  int setfl_flags = O_APPEND | O_ASYNC | ... ;

  dup_flags &= ~setfl_flags;
  dup_flags |= (flags & setfl_flags);

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 137

Quoted 12 lines
block/raw-posix.c +12 -0
+
+    if (fcntl(ret, F_SETFL, dup_flags) == -1) {
+        goto fail;
+    }
+
+    /* Truncate the file in the cases that open() would truncate it */
+    if (flags & O_TRUNC ||
+            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
+        if (ftruncate(ret, 0) == -1) {
+            goto fail;
+        }
+    }

O_CREAT | O_EXCL kind of loses its meaning here, but okay, it's hard to do better with file descriptors.

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 139

Quoted 2 lines
block/raw-posix.c +2 -0
+
+    qemu_set_cloexec(ret);

Wait... If O_CLOEXEC is set, you set the flag immediately and if it isn't you set it at the end of the function? What's the intended use case for not using O_CLOEXEC then?

Kevin

#34 lore raw
In reply to Corey Bryant

Am 23.07.2012 15:07, schrieb Corey Bryant:

Quoted 17 lines

Corey Bryant (6):
qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg
qapi: Introduce add-fd, remove-fd, query-fdsets
monitor: Clean up fd sets on monitor disconnect
block: Convert open calls to qemu_open
block: Convert close calls to qemu_close
block: Enable qemu_open/close to work with fd sets

 block/raw-posix.c |   42 ++++-----
 block/raw-win32.c |    6 +-
 block/vdi.c       |    5 +-
 block/vmdk.c      |   25 +++---
 block/vpc.c       |    4 +-
 block/vvfat.c     |   16 ++--
 cutils.c          |    5 ++
 monitor.c         |  244 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 monitor.h         |    4 +
Quoted 8 lines
 osdep.c           |  141 +++++++++++++++++++++++++++++++
 qapi-schema.json  |   97 +++++++++++++++++++++
 qemu-char.c       |   10 ++-
 qemu-common.h     |    2 +
 qemu-tool.c       |   12 +++
 qmp-commands.hx   |  121 ++++++++++++++++++++++++++
 savevm.c          |    4 +-
 16 files changed, 684 insertions(+), 54 deletions(-)

Apart from the points I commented on in patch 6, and what Eric and you found, this looks good to me.

Kevin

#21 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Kevin Wolf
Quoted 53 lines · Kevin Wolf

Am 23.07.2012 15:08, schrieb Corey Bryant:

Quoted 52 lines

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

v2:
-Get rid of file_open and move dup code to qemu_open
([email protected])
-Use strtol wrapper instead of atoi ([email protected])

v3:
-Add note about fd leakage ([email protected])

v4
-Moved patch to be later in series ([email protected]) -Update qemu_open to check access mode flags and set flags that
can be set ([email protected], [email protected])

v5:
-This patch was overhauled quite a bit in this version, with
the addition of fd set and refcount support.
-Use qemu_set_cloexec() on dup'd fd ([email protected]) -Modify flags set by fcntl on dup'd fd ([email protected]) -Reduce syscalls when setting flags for dup'd fd ([email protected]) -Fix O_RDWR, O_RDONLY, O_WRONLY checks ([email protected])

---
  block/raw-posix.c |   24 +++++-----
  block/raw-win32.c |    2 +-
  block/vmdk.c      |    4 +-
  block/vpc.c       |    2 +-
  block/vvfat.c     |   12 ++---
  cutils.c          |    5 ++
  monitor.c         |   85 +++++++++++++++++++++++++++++++++
  monitor.h         |    4 ++
  osdep.c           |  138 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
  qemu-common.h     |    3 +-
  qemu-tool.c       |   12 +++++
  11 files changed, 267 insertions(+), 24 deletions(-)
Quoted 17 lines

block/raw-posix.c static int raw_open_common(BlockDriverState *bs, const char *filename, · line 276

Quoted 12 lines
block/raw-posix.c +1 -1
index a172de3..5d0a801 100644
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs, const char *filename,
  out_free_buf:
      qemu_vfree(s->aligned_buf);
  out_close:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return -errno;
  }

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

I agree, I don't really like it either.

We already have a list of fd -> fdset mappings (mon_fdset_fd_t -> mon_fdset_t). Would it be too costly to loop through all the fdsets/fds at the beginning of every qemu_close()?

Quoted 3 lines

But if we decided to keep it like this, please use the right interface from the beginning in patch 5 instead of updating it here.

Ok

Quoted 35 lines
Quoted 35 lines
block/raw-posix.c +31 -0
@@ -2551,6 +2551,91 @@ static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use)
      }
  }
 
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount++;
+            break;
+        }
+    }
+}
+
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount--;
+            if (mon_fdset->refcount == 0) {
+                monitor_fdset_cleanup(mon_fdset);
+            }
+            break;
Quoted 9 lines

block/raw-posix.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2587

Quoted 3 lines
block/raw-posix.c +3 -0
+        }
+    }
+}

These two functions are almost the same. Would a monitor_fdset_update_refcount(mon, fdset_id, value) make sense? These functions could then be kept as thin wrappers around it, or they could even be dropped completely.

This makes sense and I'll try one of these approaches. I actually started to do something along these lines in v5 but reverted back to the two independent functions because it was easier to read the code.

Quoted 46 lines
Quoted 33 lines
block/raw-posix.c +33 -0
+
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
+            if (mon_fd_flags == -1) {
+                return -1;
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:

block/raw-posix.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2630

Quoted 10 lines
block/raw-posix.c +10 -0
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_WRONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_WRONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            }

I think you mean:

Quoted 3 lines
   if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
       return mon_fdset_fd->fd;
   }

Yes, that would be a bit simpler wouldn't it. :)

Quoted 5 lines

What about other flags that cannot be set with fcntl(), like O_SYNC on older kernels or possibly non-Linux? (The block layer doesn't use it any more, but I think we want to keep the function generally useful)

I see what you're getting at here. Basically you could have 2 fds in an fdset with the same access mode flags, but one has O_SYNC on and the other has O_SYNC off. That seems like it would make sense to implement.
As a work-around, I think a user could just create a separate fdset
for the same file with different O_SYNC value. But from a client perspective, it would be nicer to have this taken care of for you.

Quoted 49 lines
Quoted 49 lines
block/raw-posix.c +41 -0
+        }
+        errno = EACCES;
+        return -1;
+    }
+    errno = ENOENT;
+    return -1;
+}
+
  /* mon_cmds and info_cmds would be sorted at runtime */
  static mon_cmd_t mon_cmds[] = {
  #include "hmp-commands.h"
@@ -75,6 +76,79 @@ int qemu_madvise(void *addr, size_t len, int advice)
  #endif
  }
 
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup(int fd, int flags)
+{
+    int i;
+    int ret;
+    int serrno;
+    int dup_flags;
+    int setfl_flags[] = { O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,
+                          O_NONBLOCK, 0 };
+
+    if (flags & O_CLOEXEC) {
+        ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+        if (ret == -1 && errno == EINVAL) {
+            ret = dup(fd);
+            if (ret != -1 && fcntl_setfl(ret, O_CLOEXEC) == -1) {
+                goto fail;
+            }
+        }
+    } else {
+        ret = dup(fd);
+    }
+
+    if (ret == -1) {
+        goto fail;
+    }
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
Quoted 9 lines

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 115

Quoted 4 lines
block/raw-posix.c +4 -0
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }

It's worth trying to set it before failing, newer kernels can do it. But as I said above, if you can fail here, it makes sense to consider O_SYNC when selecting the right file descriptor from the fdset.

I'm on a 3.4.4 Fedora kernel that doesn't appear to support fcntl(O_SYNC), but perhaps I'm doing something wrong. Here's my test code (shortened for simplicty):

int main() {
    int fd;
    int flags;

    fd = open("/tmp/corey", O_RDWR | O_CREAT,
              S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

    flags = fcntl(fd, F_GETFL);
    printf("flags=%08x\n", flags); //A

    fcntl(fd, F_SETFL, O_SYNC);
    printf("O_SYNC=%08x\n", O_SYNC);

    flags = fcntl(fd, F_GETFL);
    printf("flags=%08x\n", flags); //B
}

fcntl doesn't fail, but the flags I print out at A are the same as the flags printed out at B, so it appears that O_SYNC doesn't get set.

Quoted 11 lines

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 125

Quoted 10 lines
block/raw-posix.c +10 -0
+    /* Set/unset flags that we can with fcntl */
+    i = 0;
+    while (setfl_flags[i] != 0) {
+        if (flags & setfl_flags[i]) {
+            dup_flags = (dup_flags | setfl_flags[i]);
+        } else {
+            dup_flags = (dup_flags & ~setfl_flags[i]);
+        }
+        i++;
+    }
Quoted 8 lines

What about this instead of the loop:

   int setfl_flags = O_APPEND | O_ASYNC | ... ;

   dup_flags &= ~setfl_flags;
   dup_flags |= (flags & setfl_flags);

I like your suggestion, it's much simpler.

Quoted 7 lines
Quoted 7 lines
block/raw-posix.c +7 -0
+
+    if (fcntl(ret, F_SETFL, dup_flags) == -1) {
+        goto fail;
+    }
+
+    /* Truncate the file in the cases that open() would truncate it */
+    if (flags & O_TRUNC ||
Quoted 9 lines

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 137

Quoted 5 lines
block/raw-posix.c +5 -0
+            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
+        if (ftruncate(ret, 0) == -1) {
+            goto fail;
+        }
+    }

O_CREAT | O_EXCL kind of loses its meaning here, but okay, it's hard to do better with file descriptors.

I agree and I don't know if we can do any better.

Quoted 7 lines

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 139

Quoted 2 lines
block/raw-posix.c +2 -0
+
+    qemu_set_cloexec(ret);

Wait... If O_CLOEXEC is set, you set the flag immediately and if it isn't you set it at the end of the function? What's the intended use case for not using O_CLOEXEC then?

This is a mistake. I think I just need to be using qemu_set_cloexec() instead of fcntl_setfl() earlier in this function and get rid of this latter call to qemu_set_cloexec().

Signature · 2 lines
Regards,
Corey
#35 lore raw
In reply to Kevin Wolf
Quoted 27 lines · Kevin Wolf

Am 23.07.2012 15:07, schrieb Corey Bryant:

Quoted 17 lines

Corey Bryant (6):
qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg
qapi: Introduce add-fd, remove-fd, query-fdsets
monitor: Clean up fd sets on monitor disconnect
block: Convert open calls to qemu_open
block: Convert close calls to qemu_close
block: Enable qemu_open/close to work with fd sets

  block/raw-posix.c |   42 ++++-----
  block/raw-win32.c |    6 +-
  block/vdi.c       |    5 +-
  block/vmdk.c      |   25 +++---
  block/vpc.c       |    4 +-
  block/vvfat.c     |   16 ++--
  cutils.c          |    5 ++
  monitor.c         |  244 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
  monitor.h         |    4 +
Quoted 8 lines
  osdep.c           |  141 +++++++++++++++++++++++++++++++
  qapi-schema.json  |   97 +++++++++++++++++++++
  qemu-char.c       |   10 ++-
  qemu-common.h     |    2 +
  qemu-tool.c       |   12 +++
  qmp-commands.hx   |  121 ++++++++++++++++++++++++++
  savevm.c          |    4 +-
  16 files changed, 684 insertions(+), 54 deletions(-)
Quoted 5 lines

Apart from the points I commented on in patch 6, and what Eric and you found, this looks good to me.

Kevin

Great, thanks for the review!

Signature · 2 lines
Regards,
Corey
#22 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant

Am 25.07.2012 05:41, schrieb Corey Bryant:

Quoted 18 lines
Quoted 8 lines
Quoted 8 lines
block/raw-posix.c +0 -0
index a172de3..5d0a801 100644
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs, const char *filename,
  out_free_buf:
      qemu_vfree(s->aligned_buf);
  out_close:
Quoted 9 lines

block/raw-posix.c static int raw_open_common(BlockDriverState *bs, const char *filename, · line 276

Quoted 4 lines
block/raw-posix.c +1 -1
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return -errno;
  }

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

Quoted 5 lines

I agree, I don't really like it either.

We already have a list of fd -> fdset mappings (mon_fdset_fd_t -> mon_fdset_t). Would it be too costly to loop through all the fdsets/fds at the beginning of every qemu_close()?

I don't think so. qemu_close() is not a fast path and happens almost never, and the list is short enough that searching it isn't a problem anyway.

Quoted 32 lines
Quoted 18 lines
Quoted 7 lines
block/raw-posix.c +7 -0
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:

block/raw-posix.c static int raw_open_common(BlockDriverState *bs, const char *filename,

Quoted 10 lines
block/raw-posix.c +10 -0
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_WRONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_WRONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            }
Quoted 5 lines

I think you mean:

   if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
       return mon_fdset_fd->fd;
   }

Yes, that would be a bit simpler wouldn't it. :)

Quoted 5 lines

What about other flags that cannot be set with fcntl(), like O_SYNC on older kernels or possibly non-Linux? (The block layer doesn't use it any more, but I think we want to keep the function generally useful)

Quoted 6 lines

I see what you're getting at here. Basically you could have 2 fds in an fdset with the same access mode flags, but one has O_SYNC on and the other has O_SYNC off. That seems like it would make sense to implement.
As a work-around, I think a user could just create a separate fdset
for the same file with different O_SYNC value. But from a client perspective, it would be nicer to have this taken care of for you.

Now that the block layer doesn't use O_SYNC any more, it's more of a theoretical point. I don't think there's any other place, where we'd need to switch O_SYNC during runtime.

Taking it into consideration is complicated by the fact that some kernels allow to fcntl() O_SYNC and others don't, so enforcing a match here wouldn't feel completely right either.

Maybe just leave it as it is. :-)

Quoted 60 lines
Quoted 50 lines
Quoted 50 lines
block/raw-posix.c +41 -0
+        }
+        errno = EACCES;
+        return -1;
+    }
+    errno = ENOENT;
+    return -1;
+}
+
  /* mon_cmds and info_cmds would be sorted at runtime */
  static mon_cmd_t mon_cmds[] = {
  #include "hmp-commands.h"
@@ -75,6 +76,79 @@ int qemu_madvise(void *addr, size_t len, int advice)
  #endif
  }
 
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup(int fd, int flags)
+{
+    int i;
+    int ret;
+    int serrno;
+    int dup_flags;
+    int setfl_flags[] = { O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,
+                          O_NONBLOCK, 0 };
+
+    if (flags & O_CLOEXEC) {
+        ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+        if (ret == -1 && errno == EINVAL) {
+            ret = dup(fd);
+            if (ret != -1 && fcntl_setfl(ret, O_CLOEXEC) == -1) {
+                goto fail;
+            }
+        }
+    } else {
+        ret = dup(fd);
+    }
+
+    if (ret == -1) {
+        goto fail;
+    }
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
Quoted 9 lines

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 115

Quoted 4 lines
block/raw-posix.c +4 -0
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }

It's worth trying to set it before failing, newer kernels can do it. But as I said above, if you can fail here, it makes sense to consider O_SYNC when selecting the right file descriptor from the fdset.

Quoted 3 lines

I'm on a 3.4.4 Fedora kernel that doesn't appear to support fcntl(O_SYNC), but perhaps I'm doing something wrong. Here's my test code (shortened for simplicty): [...]

Hm, true. So it seems that patch has never made it into the kernel, in fact...

Quoted 11 lines
Quoted 7 lines

block/raw-posix.c int qemu_madvise(void *addr, size_t len, int advice) · line 117

Quoted 2 lines
block/raw-posix.c +2 -0
+
+    qemu_set_cloexec(ret);

Wait... If O_CLOEXEC is set, you set the flag immediately and if it isn't you set it at the end of the function? What's the intended use case for not using O_CLOEXEC then?

This is a mistake. I think I just need to be using qemu_set_cloexec() instead of fcntl_setfl() earlier in this function and get rid of this latter call to qemu_set_cloexec().

Yes, probably. And in fact, I think this shouldn't even be conditional on flags & O_CLOEXEC. The whole reason qemu_open() was introduced originally was to always set O_CLOEXEC.

Kevin

#5 lore raw

Re: [Qemu-devel] [PATCH v5 2/6] qapi: Introduce add-fd, remove-fd, query-fdsets

In reply to Corey Bryant

qapi-schema.json line 1927

Quoted 10 lines · Corey Bryant

This patch adds support that enables passing of file descriptors to the QEMU monitor where they will be stored in specified file descriptor sets.

qapi-schema.json +6 -0
+##
+# @add-fd:
+#
+# Add a file descriptor, that was passed via SCM rights, to an fd set.
+#
+# @fdset_id: The ID of the fd set to add the file descriptor to.

Should this parameter be optional, in which case qemu generates the set number as the next available? The return information would include the set number whether or not this parameter was present from the caller, and allowing it to be optional makes it slightly easier for callers to generate a new set without having to make the caller track which set ids are in use.

qapi-schema.json line 1944

Quoted 8 lines
qapi-schema.json +8 -0
+##
+# @remove-fd:
+#
+# Remove a file descriptor from an fd set.
+#
+# @fdset_id: The ID of the fd set that the file descriptor belongs to.
+#
+# @fd: The file descriptor that is to be removed.

Should 'fd' be optional, as a shorthand for saying that _all_ fds belonging to the set be marked as removed at once?

Quoted 12 lines

+++ b/qmp-commands.hx

qmp-commands.hx +7 -0
@@ -926,6 +926,127 @@ Example:
 
 EQMP
 
+     {
+        .name       = "add-fd",
+        .args_type  = "fdset_id:i",
+        .params     = "add-fd fdset_id",
+        .help       = "Add a file descriptor, that was passed via SCM rights, to an fd set",
+        .mhandler.cmd_new = qmp_marshal_input_add_fd,
+    },

qmp-commands.hx Example: · line 945

Quoted 10 lines
qmp-commands.hx +10 -0
+
+SQMP
+add-fd
+-------
+
+Add a file descriptor, that was passed via SCM rights, to an fd set.
+
+Arguments:
+
+- "fdset_id": The ID of the fd set to add the file descriptor to.  (json-int)

May need tweaking, based on the answers to the above questions.

Signature · 2 lines
Eric Blake   [email protected]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#9 lore raw

Re: [Qemu-devel] [PATCH v5 4/6] block: Convert open calls to qemu_open

In reply to Corey Bryant
Quoted 4 lines · Corey Bryant

This patch converts all block layer open calls to qemu_open.

Note that this adds the O_CLOEXEC flag to the changed open paths when the O_CLOEXEC macro is defined.

Is it actually adding O_CLOEXEC, or just the ability to use O_CLOEXEC?

Or is the actual change that the end result is that the fd now has FD_CLOEXEC set unconditionally, whether by O_CLOEXEC (which the caller need not pass) or by fcntl()?

block/raw-posix.c static int raw_create(const char *filename, QEMUOptionParameter *options) · line 576

Quoted 9 lines

+++ b/block/raw-posix.c

block/raw-posix.c +2 -2
@@ -572,8 +572,8 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
-              0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
+                   0644);

After all, I don't see O_CLOEXEC used here.

block/raw-posix.c static int hdev_open(BlockDriverState *bs, const char *filename, int flags) · line 849

Quoted 9 lines
block/raw-posix.c +1 -1
     if (fd < 0) {
         result = -errno;
     } else {
@@ -846,7 +846,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
         if ( bsdPath[ 0 ] != '\0' ) {
             strcat(bsdPath,"s0");
             /* some CDs don't have a partition 0 */
-            fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
+            fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);

Also, I still stand by my earlier claim that we don't need O_LARGEFILE here (we should already be configuring for 64-bit off_t by default), although cleaning that up is probably worth an independent commit.

block/vdi.c static int vdi_create(const char *filename, QEMUOptionParameter *options) · line 658

Quoted 10 lines
block/vdi.c +4 -2
+++ b/block/vdi.c
@@ -653,8 +653,9 @@ static int vdi_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-              0644);
+    fd = qemu_open(filename,
+                   O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                   0644);

Another pointless O_LARGEFILE, and so forth.

Signature · 2 lines
Eric Blake   [email protected]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#23 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Kevin Wolf
Quoted 7 lines · Kevin Wolf
Quoted 7 lines
Quoted 4 lines

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

I agree, I don't really like it either.

Quoted 7 lines
Quoted 3 lines

We already have a list of fd -> fdset mappings (mon_fdset_fd_t -> mon_fdset_t). Would it be too costly to loop through all the fdsets/fds at the beginning of every qemu_close()?

I don't think so. qemu_close() is not a fast path and happens almost never, and the list is short enough that searching it isn't a problem anyway.

I agree - just do the loop to do the reverse lookup yourself, rather than making qemu_close() have a different signature than close().

Signature · 2 lines
Eric Blake   [email protected]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#28 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant
Quoted 19 lines · Corey Bryant

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

+++ b/monitor.c

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2560

Quoted 10 lines
monitor.c +7 -0
@@ -2551,6 +2551,91 @@ static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use)
     }
 }
 
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }

Am I reading this code right by stating that 'if there is no monitor, we don't increment the refcount'? How does a monitor reattach affect things? Or am I missing something fundamental about the cases when 'mon==NULL' will exist?

Quoted 13 lines
monitor.c +13 -0
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2611

Quoted 10 lines
monitor.c +10 -0
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
+            if (mon_fd_flags == -1) {
+                return -1;

This says we fail on the first fcntl() failure, instead of trying other fds in the set. Granted, an fcntl() failure is probably the sign of a bigger bug (such as closing an fd at the wrong point in time), so I guess trying to go on doesn't make much sense once we already know we are hosed.

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2624

Quoted 13 lines
monitor.c +13 -0
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;

Do we want to allow the case where the caller asked for O_RDONLY, but the set only has O_RDWR? After all, the caller is getting a compatible subset of what the set offers.

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2629

Quoted 5 lines
monitor.c +5 -0
+            case O_WRONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_WRONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;

Likewise, should we allow a caller asking for O_WRONLY when the set provides only O_RDWR?

Quoted 5 lines
osdep.c +4 -0
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup(int fd, int flags)

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 92

Quoted 10 lines
osdep.c +10 -0
+{
+    int i;
+    int ret;
+    int serrno;
+    int dup_flags;
+    int setfl_flags[] = { O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,
+                          O_NONBLOCK, 0 };
+
+    if (flags & O_CLOEXEC) {
+        ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);

F_DUPFD_CLOEXEC is required by POSIX but not implemented on all modern OS yet; you probably need some #ifdef and/or configure guards.

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 95

Quoted 3 lines
osdep.c +3 -0
+        if (ret == -1 && errno == EINVAL) {
+            ret = dup(fd);
+            if (ret != -1 && fcntl_setfl(ret, O_CLOEXEC) == -1) {

You _can't_ call F_SETFL with O_CLOEXEC. O_CLOEXEC only causes open() to set FD_CLOEXEC; thereafter, including in the case of this dup, what you want to do is instead set FD_CLOEXEC via F_SETFD (aka call qemu_set_cloexec, not fcntl_setfl).

Quoted 21 lines
osdep.c +21 -0
+                goto fail;
+            }
+        }
+    } else {
+        ret = dup(fd);
+    }
+
+    if (ret == -1) {
+        goto fail;
+    }
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }
+

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 126

Quoted 10 lines
osdep.c +10 -0
+    /* Set/unset flags that we can with fcntl */
+    i = 0;
+    while (setfl_flags[i] != 0) {
+        if (flags & setfl_flags[i]) {
+            dup_flags = (dup_flags | setfl_flags[i]);
+        } else {
+            dup_flags = (dup_flags & ~setfl_flags[i]);
+        }
+        i++;
+    }

Rather than looping one bit at a time, you should do this as a mask operation.

Quoted 4 lines
osdep.c +4 -0
+
+    if (fcntl(ret, F_SETFL, dup_flags) == -1) {
+        goto fail;
+    }

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 140

Quoted 10 lines
osdep.c +10 -0
+
+    /* Truncate the file in the cases that open() would truncate it */
+    if (flags & O_TRUNC ||
+            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
+        if (ftruncate(ret, 0) == -1) {
+            goto fail;
+        }
+    }
+
+    qemu_set_cloexec(ret);

If we're going to blindly set FD_CLOEXEC at the end of the day, rather than try to honor O_CLOEXEC, then why not simplify the beginning of this function:

    ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
    if (ret == -1 && errno == EINVAL) {
        ret = dup(fd);
        if (ret != -1) {
            qemu_set_cloexec(ret);
        }
    }
    if (ret == -1) {
        goto fail;
    }
Signature · 2 lines
Eric Blake   [email protected]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#6 lore raw

Re: [Qemu-devel] [PATCH v5 2/6] qapi: Introduce add-fd, remove-fd, query-fdsets

In reply to Eric Blake
Quoted 5 lines · Eric Blake
Quoted 4 lines · Corey Bryant

This patch adds support that enables passing of file descriptors to the QEMU monitor where they will be stored in specified file descriptor sets.

Quoted 14 lines

qapi-schema.json line 1927

Quoted 6 lines
qapi-schema.json +6 -0
+##
+# @add-fd:
+#
+# Add a file descriptor, that was passed via SCM rights, to an fd set.
+#
+# @fdset_id: The ID of the fd set to add the file descriptor to.

Should this parameter be optional, in which case qemu generates the set number as the next available? The return information would include the set number whether or not this parameter was present from the caller, and allowing it to be optional makes it slightly easier for callers to generate a new set without having to make the caller track which set ids are in use.

Yes, I agree, I think @fdset_id should be optional.

Quoted 12 lines

qapi-schema.json line 1944

Quoted 8 lines
qapi-schema.json +8 -0
+##
+# @remove-fd:
+#
+# Remove a file descriptor from an fd set.
+#
+# @fdset_id: The ID of the fd set that the file descriptor belongs to.
+#
+# @fd: The file descriptor that is to be removed.

Should 'fd' be optional, as a shorthand for saying that _all_ fds belonging to the set be marked as removed at once?

Yes, this makes sense.

Quoted 16 lines
Quoted 16 lines

+++ b/qmp-commands.hx

qmp-commands.hx +11 -0
@@ -926,6 +926,127 @@ Example:
 
  EQMP
 
+     {
+        .name       = "add-fd",
+        .args_type  = "fdset_id:i",
+        .params     = "add-fd fdset_id",
+        .help       = "Add a file descriptor, that was passed via SCM rights, to an fd set",
+        .mhandler.cmd_new = qmp_marshal_input_add_fd,
+    },
+
+SQMP
+add-fd
+-------
Quoted 9 lines

qmp-commands.hx Example: · line 945

Quoted 6 lines
qmp-commands.hx +6 -0
+
+Add a file descriptor, that was passed via SCM rights, to an fd set.
+
+Arguments:
+
+- "fdset_id": The ID of the fd set to add the file descriptor to.  (json-int)

May need tweaking, based on the answers to the above questions.

Ok.

Signature · 2 lines
Regards,
Corey
#10 lore raw

Re: [Qemu-devel] [PATCH v5 4/6] block: Convert open calls to qemu_open

In reply to Eric Blake
Quoted 7 lines · Eric Blake
Quoted 4 lines · Corey Bryant

This patch converts all block layer open calls to qemu_open.

Note that this adds the O_CLOEXEC flag to the changed open paths when the O_CLOEXEC macro is defined.

Is it actually adding O_CLOEXEC, or just the ability to use O_CLOEXEC?

It is adding O_CLOEXEC in qemu_open() on the open() call (as long as it is defined).

Quoted 5 lines

Or is the actual change that the end result is that the fd now has FD_CLOEXEC set unconditionally, whether by O_CLOEXEC (which the caller need not pass) or by fcntl()?

The statement in the commit message isn't referring to anything dealing with qemu_dup(). The statement is specifically talking about the open() call in qemu_open(), and the point is to alert folks that old open() calls are now being routed through qemu_open() and likely are using the O_CLOEXEC flag, which is new behavior.

Quoted 5 lines
Quoted 5 lines

+++ b/block/raw-posix.c

block/raw-posix.c +0 -0
@@ -572,8 +572,8 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
          options++;
      }
 
Quoted 7 lines

block/raw-posix.c static int raw_create(const char *filename, QEMUOptionParameter *options) · line 576

Quoted 4 lines
block/raw-posix.c +2 -2
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
-              0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
+                   0644);

After all, I don't see O_CLOEXEC used here.

That's right. qemu_open() adds O_CLOEXEC on the open() call.

Quoted 5 lines
Quoted 5 lines
block/raw-posix.c +0 -0
      if (fd < 0) {
          result = -errno;
      } else {
@@ -846,7 +846,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
          if ( bsdPath[ 0 ] != '\0' ) {
Quoted 9 lines

block/raw-posix.c static int hdev_open(BlockDriverState *bs, const char *filename, int flags) · line 849

Quoted 4 lines
block/raw-posix.c +1 -1
              strcat(bsdPath,"s0");
              /* some CDs don't have a partition 0 */
-            fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
+            fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);

Also, I still stand by my earlier claim that we don't need O_LARGEFILE here (we should already be configuring for 64-bit off_t by default), although cleaning that up is probably worth an independent commit.

I have a note to get rid of O_LARGEFILE as a separate follow-on patch.

Quoted 6 lines
Quoted 6 lines
block/raw-posix.c +1 -0
+++ b/block/vdi.c
@@ -653,8 +653,9 @@ static int vdi_create(const char *filename, QEMUOptionParameter *options)
          options++;
      }
 
Quoted 8 lines

block/vdi.c static int vdi_create(const char *filename, QEMUOptionParameter *options) · line 658

Quoted 5 lines
block/vdi.c +3 -2
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-              0644);
+    fd = qemu_open(filename,
+                   O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                   0644);

Another pointless O_LARGEFILE, and so forth.

Yep.

Signature · 2 lines
Regards,
Corey
#24 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Eric Blake
Quoted 12 lines · Eric Blake
Quoted 11 lines · Kevin Wolf
Quoted 10 lines
Quoted 4 lines

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

I agree, I don't really like it either.

We already have a list of fd -> fdset mappings (mon_fdset_fd_t -> mon_fdset_t). Would it be too costly to loop through all the fdsets/fds at the beginning of every qemu_close()?

Quoted 7 lines
Quoted 3 lines

I don't think so. qemu_close() is not a fast path and happens almost never, and the list is short enough that searching it isn't a problem anyway.

I agree - just do the loop to do the reverse lookup yourself, rather than making qemu_close() have a different signature than close().

Great, I'll do this then.

Signature · 2 lines
Regards,
Corey
#29 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Eric Blake
Quoted 23 lines · Eric Blake
Quoted 22 lines · Corey Bryant

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

+++ b/monitor.c

(quoted diff) +0 -0
@@ -2551,6 +2551,91 @@ static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use)
      }
  }
 
Quoted 13 lines

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2560

Quoted 7 lines
monitor.c +7 -0
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }

Am I reading this code right by stating that 'if there is no monitor, we don't increment the refcount'? How does a monitor reattach affect things? Or am I missing something fundamental about the cases when 'mon==NULL' will exist?

Yes you're reading this correctly.

I'm pretty sure that mon will only be NULL if QEMU is started without a monitor.

If QEMU has a monitor, and libvirt disconnects it's connection to the qemu monitor, then I believe mon will remain non-NULL.

I'll plan on testing this out to verify though. (I'm out most of this week and will be back full time starting next Tues.)

Quoted 21 lines
Quoted 21 lines
monitor.c +21 -0
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
Quoted 9 lines

Review static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2583

Quoted 2 lines
(quoted diff) +2 -0
+            if (mon_fd_flags == -1) {
+                return -1;

This says we fail on the first fcntl() failure, instead of trying other fds in the set. Granted, an fcntl() failure is probably the sign of a bigger bug (such as closing an fd at the wrong point in time), so I guess trying to go on doesn't make much sense once we already know we are hosed.

I think I'll stick with it the way it is. If fcntl() fails we might have a tainted fd set so I think we should fail.

Quoted 14 lines

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2624

Quoted 13 lines
monitor.c +13 -0
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
Quoted 4 lines

Do we want to allow the case where the caller asked for O_RDONLY, but the set only has O_RDWR? After all, the caller is getting a compatible subset of what the set offers.

I don't see a problem with it.

Quoted 9 lines

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2629

Quoted 5 lines
monitor.c +5 -0
+            case O_WRONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_WRONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;

Likewise, should we allow a caller asking for O_WRONLY when the set provides only O_RDWR?

I don't see a problem with it.

Quoted 10 lines
Quoted 10 lines
osdep.c +9 -0
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup(int fd, int flags)
+{
+    int i;
+    int ret;
+    int serrno;
+    int dup_flags;
Quoted 9 lines

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 92

Quoted 5 lines
osdep.c +5 -0
+    int setfl_flags[] = { O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,
+                          O_NONBLOCK, 0 };
+
+    if (flags & O_CLOEXEC) {
+        ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);

F_DUPFD_CLOEXEC is required by POSIX but not implemented on all modern OS yet; you probably need some #ifdef and/or configure guards.

Ok

Quoted 9 lines

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 95

Quoted 3 lines
osdep.c +3 -0
+        if (ret == -1 && errno == EINVAL) {
+            ret = dup(fd);
+            if (ret != -1 && fcntl_setfl(ret, O_CLOEXEC) == -1) {

You _can't_ call F_SETFL with O_CLOEXEC. O_CLOEXEC only causes open() to set FD_CLOEXEC; thereafter, including in the case of this dup, what you want to do is instead set FD_CLOEXEC via F_SETFD (aka call qemu_set_cloexec, not fcntl_setfl).

I know, this is a mistake. I'm planning to replace fcntl_setfl() here with qemu_set_cloexec().

Quoted 26 lines
Quoted 26 lines
osdep.c +26 -0
+                goto fail;
+            }
+        }
+    } else {
+        ret = dup(fd);
+    }
+
+    if (ret == -1) {
+        goto fail;
+    }
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }
+
+    /* Set/unset flags that we can with fcntl */
+    i = 0;
+    while (setfl_flags[i] != 0) {
+        if (flags & setfl_flags[i]) {
+            dup_flags = (dup_flags | setfl_flags[i]);
Quoted 9 lines

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 126

Quoted 5 lines
osdep.c +5 -0
+        } else {
+            dup_flags = (dup_flags & ~setfl_flags[i]);
+        }
+        i++;
+    }

Rather than looping one bit at a time, you should do this as a mask operation.

I agree.

Quoted 10 lines
Quoted 10 lines
osdep.c +10 -0
+
+    if (fcntl(ret, F_SETFL, dup_flags) == -1) {
+        goto fail;
+    }
+
+    /* Truncate the file in the cases that open() would truncate it */
+    if (flags & O_TRUNC ||
+            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
+        if (ftruncate(ret, 0) == -1) {
+            goto fail;
Quoted 8 lines

osdep.c int qemu_madvise(void *addr, size_t len, int advice) · line 140

Quoted 4 lines
osdep.c +4 -0
+        }
+    }
+
+    qemu_set_cloexec(ret);

If we're going to blindly set FD_CLOEXEC at the end of the day, rather than try to honor O_CLOEXEC, then why not simplify the beginning of this function:

This call to qemu_set_cloexec() was a mistake. I'm planning on removing it.

Quoted 12 lines
     ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
     if (ret == -1 && errno == EINVAL) {
         ret = dup(fd);
         if (ret != -1) {
             qemu_set_cloexec(ret);
         }
     }
     if (ret == -1) {
         goto fail;
     }

I'll plan on sticking with the existing code in the beginning of this function with the modifications mentioned above.

Signature · 2 lines
Regards,
Corey
#30 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

Am 26.07.2012 05:57, schrieb Corey Bryant:

Quoted 33 lines · Eric Blake
Quoted 22 lines · Corey Bryant
Quoted 21 lines
monitor.c +21 -0
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
Quoted 9 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+            if (mon_fd_flags == -1) {
+                return -1;

This says we fail on the first fcntl() failure, instead of trying other fds in the set. Granted, an fcntl() failure is probably the sign of a bigger bug (such as closing an fd at the wrong point in time), so I guess trying to go on doesn't make much sense once we already know we are hosed.

Quoted 2 lines

I think I'll stick with it the way it is. If fcntl() fails we might have a tainted fd set so I think we should fail.

The alternative would be s/return 1/continue/, right? I think either way is acceptable.

Quoted 14 lines
Quoted 14 lines
Quoted 13 lines
monitor.c +13 -0
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
Quoted 5 lines
Quoted 3 lines

Do we want to allow the case where the caller asked for O_RDONLY, but the set only has O_RDWR? After all, the caller is getting a compatible subset of what the set offers.

I don't see a problem with it.

I would require exact matches like you implemented, in order to prevent damage if we ever had a bug that writes to a read-only file. I believe it also makes the semantics clearer and the code simpler, while it shouldn't make much of a difference for clients.

Kevin

#25 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant
Quoted 20 lines · Corey Bryant
Quoted 17 lines · Eric Blake
Quoted 15 lines · Kevin Wolf
Quoted 11 lines
Quoted 4 lines

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

I agree, I don't really like it either.

We already have a list of fd -> fdset mappings (mon_fdset_fd_t -> mon_fdset_t). Would it be too costly to loop through all the fdsets/fds
at the beginning of every qemu_close()?

I don't think so. qemu_close() is not a fast path and happens almost never, and the list is short enough that searching it isn't a problem anyway.

Quoted 5 lines
Quoted 3 lines

I agree - just do the loop to do the reverse lookup yourself, rather than making qemu_close() have a different signature than close().

Great, I'll do this then.

You may want an optimization of using a bitset for tracking which fds are tracked by fdset in the first place, so that the fast path of qemu_close() will be a check against the bitset to see if you even have to waste time on the reverse lookup in the first place. The bitset will typically be small (bounded not only by the maximum possible fd, but further by the fact that we don't usually open that many fds in the first place), but I'm not sure if you can get away with static sizing.

Signature · 2 lines
Eric Blake   [email protected]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#26 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

Am 26.07.2012 15:13, schrieb Eric Blake:

Quoted 27 lines · Corey Bryant
Quoted 20 lines · Eric Blake
Quoted 17 lines · Kevin Wolf
Quoted 15 lines
Quoted 11 lines
Quoted 4 lines

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

I agree, I don't really like it either.

We already have a list of fd -> fdset mappings (mon_fdset_fd_t -> mon_fdset_t). Would it be too costly to loop through all the fdsets/fds
at the beginning of every qemu_close()?

I don't think so. qemu_close() is not a fast path and happens almost never, and the list is short enough that searching it isn't a problem anyway.

Quoted 5 lines
Quoted 3 lines

I agree - just do the loop to do the reverse lookup yourself, rather than making qemu_close() have a different signature than close().

Great, I'll do this then.

Quoted 7 lines

You may want an optimization of using a bitset for tracking which fds are tracked by fdset in the first place, so that the fast path of qemu_close() will be a check against the bitset to see if you even have to waste time on the reverse lookup in the first place. The bitset will typically be small (bounded not only by the maximum possible fd, but further by the fact that we don't usually open that many fds in the first place), but I'm not sure if you can get away with static sizing.

Premature optimisation, in my opinion. The list is really small.

Kevin

#31 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Kevin Wolf
Quoted 58 lines · Kevin Wolf

Am 26.07.2012 05:57, schrieb Corey Bryant:

Quoted 33 lines · Eric Blake
Quoted 22 lines · Corey Bryant
Quoted 21 lines
monitor.c +21 -0
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
Quoted 9 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+            if (mon_fd_flags == -1) {
+                return -1;

This says we fail on the first fcntl() failure, instead of trying other fds in the set. Granted, an fcntl() failure is probably the sign of a bigger bug (such as closing an fd at the wrong point in time), so I guess trying to go on doesn't make much sense once we already know we are hosed.

Quoted 2 lines

I think I'll stick with it the way it is. If fcntl() fails we might have a tainted fd set so I think we should fail.

The alternative would be s/return 1/continue/, right? I think either way is acceptable.

Quoted 18 lines
Quoted 17 lines

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2624

Quoted 13 lines
monitor.c +13 -0
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;

Do we want to allow the case where the caller asked for O_RDONLY, but the set only has O_RDWR? After all, the caller is getting a compatible subset of what the set offers.

Quoted 9 lines
Quoted 1 line

I don't see a problem with it.

I would require exact matches like you implemented, in order to prevent damage if we ever had a bug that writes to a read-only file. I believe it also makes the semantics clearer and the code simpler, while it shouldn't make much of a difference for clients.

Kevin

Alright, then I'll plan on requiring exact matches of access mode flags.

Signature · 2 lines
Regards,
Corey
#32 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Kevin Wolf
Quoted 36 lines · Kevin Wolf

Am 26.07.2012 05:57, schrieb Corey Bryant:

Quoted 35 lines · Eric Blake
Quoted 6 lines · Corey Bryant
Quoted 5 lines
monitor.c +5 -0
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
Quoted 8 lines

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2601

Quoted 8 lines
monitor.c +8 -0
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {

+ continue;

Quoted 16 lines

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2611

Quoted 9 lines
monitor.c +9 -0
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
+            if (mon_fd_flags == -1) {
+                return -1;

This says we fail on the first fcntl() failure, instead of trying other fds in the set. Granted, an fcntl() failure is probably the sign of a bigger bug (such as closing an fd at the wrong point in time), so I guess trying to go on doesn't make much sense once we already know we are hosed.

Quoted 6 lines
Quoted 2 lines

I think I'll stick with it the way it is. If fcntl() fails we might have a tainted fd set so I think we should fail.

The alternative would be s/return 1/continue/, right? I think either way is acceptable.

Yes, we'd continue the loop instead of returning -1. I prefer to return on the first failure, but if anyone feels strongly about continuing the loop, please let me know.

Signature · 2 lines
Regards,
Corey
#27 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Kevin Wolf
Quoted 36 lines · Kevin Wolf

Am 26.07.2012 15:13, schrieb Eric Blake:

Quoted 27 lines · Corey Bryant
Quoted 20 lines · Eric Blake
Quoted 17 lines · Kevin Wolf
Quoted 15 lines
Quoted 11 lines
Quoted 4 lines

Hm, not a nice interface where qemu_close() needs the filename and (worse) could be given a wrong filename. Maybe it would be better to maintain a list of fd -> fdset mappings in qemu_open/close?

I agree, I don't really like it either.

We already have a list of fd -> fdset mappings (mon_fdset_fd_t -> mon_fdset_t). Would it be too costly to loop through all the fdsets/fds
at the beginning of every qemu_close()?

I don't think so. qemu_close() is not a fast path and happens almost never, and the list is short enough that searching it isn't a problem anyway.

Quoted 5 lines
Quoted 3 lines

I agree - just do the loop to do the reverse lookup yourself, rather than making qemu_close() have a different signature than close().

Great, I'll do this then.

Quoted 7 lines

You may want an optimization of using a bitset for tracking which fds are tracked by fdset in the first place, so that the fast path of qemu_close() will be a check against the bitset to see if you even have to waste time on the reverse lookup in the first place. The bitset will typically be small (bounded not only by the maximum possible fd, but further by the fact that we don't usually open that many fds in the first place), but I'm not sure if you can get away with static sizing.

Quoted 4 lines

Premature optimisation, in my opinion. The list is really small.

Kevin

I'll probably hold off on any optimisation at this point, but I can revisit it in the future if it's needed.

Signature · 2 lines
Regards,
Corey
#33 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant
Quoted 41 lines · Corey Bryant
Quoted 24 lines · Eric Blake
Quoted 23 lines · Corey Bryant

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

+++ b/monitor.c

(quoted diff) +0 -0
@@ -2551,6 +2551,91 @@ static void monitor_fdsets_set_in_use(Monitor
 *mon, bool in_use)
      }
  }
 
Quoted 13 lines

monitor.c static void monitor_fdsets_set_in_use(Monitor *mon, bool in_use) · line 2560

Quoted 7 lines
monitor.c +7 -0
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }

Am I reading this code right by stating that 'if there is no monitor, we don't increment the refcount'? How does a monitor reattach affect things? Or am I missing something fundamental about the cases when 'mon==NULL' will exist?

Quoted 7 lines

Yes you're reading this correctly.

I'm pretty sure that mon will only be NULL if QEMU is started without a monitor.

If QEMU has a monitor, and libvirt disconnects it's connection to the qemu monitor, then I believe mon will remain non-NULL.

I've verified this to be true and everything is working as expected.

If libvirt's connection to the monitor fd is closed, mon will remain non-NULL and the refcount will still be incremented/decremented on qemu_open()/qemu_close(). When libvirt reconnects, any fdsets that haven't been cleaned up will still be available. query-fdsets can be used to determine what's available.

Signature · 2 lines
Regards,
Corey
#14 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

In reply to Corey Bryant
Quoted 511 lines · Corey Bryant
Quoted 508 lines · Corey Bryant

When qemu_open is passed a filename of the "/dev/fdset/nnn" format (where nnn is the fdset ID), an fd with matching access mode flags will be searched for within the specified monitor fd set. If the fd is found, a dup of the fd will be returned from qemu_open.

Each fd set has a reference count. The purpose of the reference count is to determine if an fd set contains file descriptors that have open dup() references that have not yet been closed. It is incremented on qemu_open and decremented on qemu_close. It is not until the refcount is zero that file desriptors in an fd set can be closed. If an fd set has dup() references open, then we must keep the other fds in the fd set open in case a reopen of the file occurs that requires an fd with a different access mode.

v2:
-Get rid of file_open and move dup code to qemu_open
([email protected])
-Use strtol wrapper instead of atoi ([email protected])

v3:
-Add note about fd leakage ([email protected])

v4
-Moved patch to be later in series ([email protected]) -Update qemu_open to check access mode flags and set flags that
can be set ([email protected], [email protected])

v5:
-This patch was overhauled quite a bit in this version, with
the addition of fd set and refcount support.
-Use qemu_set_cloexec() on dup'd fd ([email protected]) -Modify flags set by fcntl on dup'd fd ([email protected]) -Reduce syscalls when setting flags for dup'd fd ([email protected]) -Fix O_RDWR, O_RDONLY, O_WRONLY checks ([email protected])

---
  block/raw-posix.c |   24 +++++-----
  block/raw-win32.c |    2 +-
  block/vmdk.c      |    4 +-
  block/vpc.c       |    2 +-
  block/vvfat.c     |   12 ++---
  cutils.c          |    5 ++
  monitor.c         |   85 +++++++++++++++++++++++++++++++++
  monitor.h         |    4 ++
  osdep.c           |  138
++++++++++++++++++++++++++++++++++++++++++++++++++++-
  qemu-common.h     |    3 +-
  qemu-tool.c       |   12 +++++
  11 files changed, 267 insertions(+), 24 deletions(-)
block/raw-posix.c +3 -3
index a172de3..5d0a801 100644
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs,
 const char *filename,
  out_free_buf:
      qemu_vfree(s->aligned_buf);
  out_close:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return -errno;
  }
@@ -376,7 +376,7 @@ static void raw_close(BlockDriverState *bs)
  {
      BDRVRawState *s = bs->opaque;
      if (s->fd >= 0) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
          s->fd = -1;
          if (s->aligned_buf != NULL)
              qemu_vfree(s->aligned_buf);
@@ -580,7 +580,7 @@ static int raw_create(const char *filename,
 QEMUOptionParameter *options)
          if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
              result = -errno;
          }
-        if (qemu_close(fd) != 0) {
+        if (qemu_close(fd, filename) != 0) {
              result = -errno;
          }
      }
block/raw-posix.c +1 -1
@@ -850,7 +850,7 @@ static int hdev_open(BlockDriverState *bs, const
 char *filename, int flags)
              if (fd < 0) {
                  bsdPath[strlen(bsdPath)-1] = '1';
              } else {
-                qemu_close(fd);
+                qemu_close(fd, bsdPath);
              }
              filename = bsdPath;
          }
block/raw-posix.c +4 -4
@@ -889,7 +889,7 @@ static int fd_open(BlockDriverState *bs)
      last_media_present = (s->fd >= 0);
      if (s->fd >= 0 &&
          (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
          s->fd = -1;
  #ifdef DEBUG_FLOPPY
          printf("Floppy closed\n");
@@ -988,7 +988,7 @@ static int hdev_create(const char *filename,
 QEMUOptionParameter *options)
      else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
          ret = -ENOSPC;
 
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
@@ -1038,7 +1038,7 @@ static int floppy_open(BlockDriverState *bs,
 const char *filename, int flags)
          return ret;
 
      /* close fd so that we can reopen it as needed */
-    qemu_close(s->fd);
+    qemu_close(s->fd, filename);
      s->fd = -1;
      s->fd_media_changed = 1;
@@ -1070,7 +1070,7 @@ static int floppy_probe_device(const char
 *filename)
          prio = 100;
 
  outc:
-    qemu_close(fd);
+    qemu_close(fd, filename);
  out:
      return prio;
  }
block/raw-posix.c +4 -4
@@ -1105,14 +1105,14 @@ static void floppy_eject(BlockDriverState *bs,
 bool eject_flag)
      int fd;
 
      if (s->fd >= 0) {
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
          s->fd = -1;
      }
      fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
      if (fd >= 0) {
          if (ioctl(fd, FDEJECT, 0) < 0)
              perror("FDEJECT");
-        qemu_close(fd);
+        qemu_close(fd, bs->filename);
      }
  }
@@ -1173,7 +1173,7 @@ static int cdrom_probe_device(const char *filename)
          prio = 100;
 
  outc:
-    qemu_close(fd);
+    qemu_close(fd, filename);
  out:
      return prio;
  }
@@ -1281,7 +1281,7 @@ static int cdrom_reopen(BlockDriverState *bs)
       * FreeBSD seems to not notice sometimes...
       */
      if (s->fd >= 0)
-        qemu_close(s->fd);
+        qemu_close(s->fd, bs->filename);
      fd = qemu_open(bs->filename, s->open_flags, 0644);
      if (fd < 0) {
          s->fd = -1;
block/raw-win32.c +1 -1
index c56bf83..b795871 100644
@@ -261,7 +261,7 @@ static int raw_create(const char *filename,
 QEMUOptionParameter *options)
          return -EIO;
      set_sparse(fd);
      ftruncate(fd, total_size * 512);
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return 0;
  }
block/vmdk.c +2 -2
index daee426..7f1206b 100644
@@ -1258,7 +1258,7 @@ static int vmdk_create_extent(const char
 *filename, int64_t filesize,
 
      ret = 0;
   exit:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
@@ -1506,7 +1506,7 @@ static int vmdk_create(const char *filename,
 QEMUOptionParameter *options)
      }
      ret = 0;
  exit:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
block/vpc.c +1 -1
index c0b82c4..20f648a 100644
@@ -744,7 +744,7 @@ static int vpc_create(const char *filename,
 QEMUOptionParameter *options)
      }
 
   fail:
-    qemu_close(fd);
+    qemu_close(fd, filename);
      return ret;
  }
block/vvfat.c +1 -1
index 59d3c5b..cbc7543 100644
@@ -1105,7 +1105,7 @@ static inline void
 vvfat_close_current_file(BDRVVVFATState *s)
      if(s->current_mapping) {
      s->current_mapping = NULL;
      if (s->current_fd) {
-        qemu_close(s->current_fd);
+        qemu_close(s->current_fd, s->current_mapping->path);
          s->current_fd = 0;
      }
      }
block/vvfat.c +5 -5
@@ -2230,7 +2230,7 @@ static int commit_one_file(BDRVVVFATState* s,
      }
      if (offset > 0) {
          if (lseek(fd, offset, SEEK_SET) != offset) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
              g_free(cluster);
              return -3;
          }
@@ -2251,13 +2251,13 @@ static int commit_one_file(BDRVVVFATState* s,
          (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
 
          if (ret < 0) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
              g_free(cluster);
              return ret;
          }
 
          if (write(fd, cluster, rest_size) < 0) {
-            qemu_close(fd);
+            qemu_close(fd, mapping->path);
              g_free(cluster);
              return -2;
          }
@@ -2268,11 +2268,11 @@ static int commit_one_file(BDRVVVFATState* s,
 
      if (ftruncate(fd, size)) {
          perror("ftruncate()");
-        qemu_close(fd);
+        qemu_close(fd, mapping->path);
          g_free(cluster);
          return -4;
      }
-    qemu_close(fd);
+    qemu_close(fd, mapping->path);
      g_free(cluster);
 
      return commit_mappings(s, first_cluster, dir_index);
cutils.c +5 -0
index e2bc1b8..4e6bfdc 100644
@@ -375,3 +375,8 @@ int qemu_parse_fd(const char *param)
      }
      return fd;
  }
+
+int qemu_parse_fdset(const char *param)
+{
+    return qemu_parse_fd(param);
+}
monitor.c +85 -0
index 30b085f..fddd2b5 100644
@@ -2551,6 +2551,91 @@ static void monitor_fdsets_set_in_use(Monitor
 *mon, bool in_use)
      }
  }
 
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount++;
+            break;
+        }
+    }
+}
+
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id)
+{
+    mon_fdset_t *mon_fdset;
+
+    if (!mon) {
+        return;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id == fdset_id) {
+            mon_fdset->refcount--;
+            if (mon_fdset->refcount == 0) {
+                monitor_fdset_cleanup(mon_fdset);
+            }
+            break;
+        }
+    }
+}
+
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags)
+{
+    mon_fdset_t *mon_fdset;
+    mon_fdset_fd_t *mon_fdset_fd;
+    int mon_fd_flags;
+
+    if (!mon) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    QLIST_FOREACH(mon_fdset, &mon->fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (mon_fdset_fd->removed) {
+                continue;
+            }
+
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
+            if (mon_fd_flags == -1) {
+                return -1;
+            }
+
+            switch (flags & O_ACCMODE) {
+            case O_RDWR:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDWR) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_RDONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_RDONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            case O_WRONLY:
+                if ((mon_fd_flags & O_ACCMODE) == O_WRONLY) {
+                    return mon_fdset_fd->fd;
+                }
+                break;
+            }
+        }
+        errno = EACCES;
+        return -1;
+    }
+    errno = ENOENT;
+    return -1;
+}
+
  /* mon_cmds and info_cmds would be sorted at runtime */
  static mon_cmd_t mon_cmds[] = {
  #include "hmp-commands.h"
monitor.h +4 -0
index 5f4de1b..1efed38 100644
@@ -86,4 +86,8 @@ int qmp_qom_set(Monitor *mon, const QDict *qdict,
 QObject **ret);
 
  int qmp_qom_get(Monitor *mon, const QDict *qdict, QObject **ret);
 
+int monitor_fdset_get_fd(Monitor *mon, int64_t fdset_id, int flags);
+void monitor_fdset_increment_refcount(Monitor *mon, int64_t fdset_id);
+void monitor_fdset_decrement_refcount(Monitor *mon, int64_t fdset_id);
+
  #endif /* !MONITOR_H */
osdep.c +86 -0
index 7b09dff..0303cdd 100644
@@ -47,6 +47,7 @@ extern int madvise(caddr_t, size_t, int);
  #include "qemu-common.h"
  #include "trace.h"
  #include "qemu_socket.h"
+#include "monitor.h"
 
  static const char *qemu_version = QEMU_VERSION;
 
@@ -75,6 +76,79 @@ int qemu_madvise(void *addr, size_t len, int advice)
  #endif
  }
 
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup(int fd, int flags)
+{
+    int i;
+    int ret;
+    int serrno;
+    int dup_flags;
+    int setfl_flags[] = { O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,
+                          O_NONBLOCK, 0 };
+
+    if (flags & O_CLOEXEC) {
+        ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+        if (ret == -1 && errno == EINVAL) {
+            ret = dup(fd);
+            if (ret != -1 && fcntl_setfl(ret, O_CLOEXEC) == -1) {
+                goto fail;
+            }
+        }
+    } else {
+        ret = dup(fd);
+    }
+
+    if (ret == -1) {
+        goto fail;
+    }
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }
+
+    /* Set/unset flags that we can with fcntl */
+    i = 0;
+    while (setfl_flags[i] != 0) {
+        if (flags & setfl_flags[i]) {
+            dup_flags = (dup_flags | setfl_flags[i]);
+        } else {
+            dup_flags = (dup_flags & ~setfl_flags[i]);
+        }
+        i++;
+    }
+
+    if (fcntl(ret, F_SETFL, dup_flags) == -1) {
+        goto fail;
+    }
+
+    /* Truncate the file in the cases that open() would truncate it */
+    if (flags & O_TRUNC ||
+            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
+        if (ftruncate(ret, 0) == -1) {
+            goto fail;
+        }
+    }
+
+    qemu_set_cloexec(ret);
+
+    return ret;
+
+fail:
+    serrno = errno;
+    if (ret != -1) {
+        close(ret);
+    }
+    errno = serrno;
+    return -1;
+}
 
  /*
   * Opens a file with FD_CLOEXEC set
@@ -84,6 +158,36 @@ int qemu_open(const char *name, int flags, ...)
      int ret;
      int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
Quoted 9 lines

osdep.c int qemu_open(const char *name, int flags, ...) · line 175

Quoted 3 lines
osdep.c +3 -0
+        }
+
+        fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);

I know that use of default_mon in this patch is not correct, but I wanted to get these patches out for review. I used default_mon for testing because cur_mon wasn't pointing to the monitor I'd added fd sets to. I need to figure out why.

Does it make sense to use default_mon here? After digging into this some more, I'm thinking it makes sense, and I'll explain why.

It looks like cur_mon can't be used. cur_mon will point to the monitor object for the duration of a command, and be reset to old_mon (NULL in my case) after the command completes.

qemu_open() and qemu_close() are frequently called long after a monitor command has come and gone, so cur_mon won't work. For example, drive_add will cause qemu_open() to be called, but after the command has completed, the file will keep getting opened/closed during normal QEMU operation. I'm not sure why, I've just noticed this behavior.

Does anyone have any thoughts on this? It would require fd sets to be added to the default monitor only.

Signature · 2 lines
Regards,
Corey
#15 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

Am 03.08.2012 00:21, schrieb Corey Bryant:

Quoted 33 lines
Quoted 16 lines
Quoted 16 lines
osdep.c +12 -0
@@ -84,6 +158,36 @@ int qemu_open(const char *name, int flags, ...)
      int ret;
      int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
Quoted 9 lines

osdep.c int qemu_open(const char *name, int flags, ...) · line 175

Quoted 3 lines
osdep.c +3 -0
+        }
+
+        fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);

I know that use of default_mon in this patch is not correct, but I wanted to get these patches out for review. I used default_mon for testing because cur_mon wasn't pointing to the monitor I'd added fd sets to. I need to figure out why.

Does it make sense to use default_mon here? After digging into this some more, I'm thinking it makes sense, and I'll explain why.

It looks like cur_mon can't be used. cur_mon will point to the monitor object for the duration of a command, and be reset to old_mon (NULL in my case) after the command completes.

Quoted 8 lines

qemu_open() and qemu_close() are frequently called long after a monitor command has come and gone, so cur_mon won't work. For example, drive_add will cause qemu_open() to be called, but after the command has completed, the file will keep getting opened/closed during normal QEMU operation. I'm not sure why, I've just noticed this behavior.

Does anyone have any thoughts on this? It would require fd sets to be added to the default monitor only.

I think we have two design options that would make sense:

1. Make the file descriptors global instead of per-monitor. Is there a reason why each monitor has its own set of fds? (Also I'm wondering if they survive a monitor disconnect this way?)

2. Save a monitor reference with the fdset information.

Allowing to send file descriptors on every monitor, but making only those of the default monitor actually usable, sounds like a bad choice to me.

Kevin

#16 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

Quoted 40 lines · Kevin Wolf

Am 03.08.2012 00:21, schrieb Corey Bryant:

Quoted 39 lines
Quoted 16 lines
Quoted 16 lines
osdep.c +12 -0
@@ -84,6 +158,36 @@ int qemu_open(const char *name, int flags, ...)
       int ret;
       int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
Quoted 9 lines

osdep.c int qemu_open(const char *name, int flags, ...) · line 175

Quoted 3 lines
osdep.c +3 -0
+        }
+
+        fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);

I know that use of default_mon in this patch is not correct, but I wanted to get these patches out for review. I used default_mon for testing because cur_mon wasn't pointing to the monitor I'd added fd sets to. I need to figure out why.

Does it make sense to use default_mon here? After digging into this some more, I'm thinking it makes sense, and I'll explain why.

It looks like cur_mon can't be used. cur_mon will point to the monitor object for the duration of a command, and be reset to old_mon (NULL in my case) after the command completes.

qemu_open() and qemu_close() are frequently called long after a monitor command has come and gone, so cur_mon won't work. For example, drive_add will cause qemu_open() to be called, but after the command has completed, the file will keep getting opened/closed during normal QEMU operation. I'm not sure why, I've just noticed this behavior.

Quoted 8 lines
Quoted 2 lines

Does anyone have any thoughts on this? It would require fd sets to be added to the default monitor only.

I think we have two design options that would make sense:

1. Make the file descriptors global instead of per-monitor. Is there a reason why each monitor has its own set of fds? (Also I'm wondering if they survive a monitor disconnect this way?)

I'd prefer to have them associated with a monitor object so that we can more easily keep track of whether or not they're in use by a monitor connection.

Quoted 3 lines

2. Save a monitor reference with the fdset information.

Are you saying that each monitor would have the same copy of fdset information?

Quoted 3 lines

Allowing to send file descriptors on every monitor, but making only those of the default monitor actually usable, sounds like a bad choice to me.

What if we also allow them to be added only to the default monitor?

Signature · 2 lines
Regards,
Corey
#17 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

Am 06.08.2012 15:32, schrieb Corey Bryant:

Quoted 46 lines · Kevin Wolf
Quoted 45 lines

Am 03.08.2012 00:21, schrieb Corey Bryant:

Quoted 33 lines
Quoted 16 lines
Quoted 16 lines
osdep.c +12 -0
@@ -84,6 +158,36 @@ int qemu_open(const char *name, int flags, ...)
       int ret;
       int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
Quoted 9 lines

osdep.c int qemu_open(const char *name, int flags, ...) · line 175

Quoted 3 lines
osdep.c +3 -0
+        }
+
+        fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);

I know that use of default_mon in this patch is not correct, but I wanted to get these patches out for review. I used default_mon for testing because cur_mon wasn't pointing to the monitor I'd added fd sets to. I need to figure out why.

Does it make sense to use default_mon here? After digging into this some more, I'm thinking it makes sense, and I'll explain why.

It looks like cur_mon can't be used. cur_mon will point to the monitor object for the duration of a command, and be reset to old_mon (NULL in my case) after the command completes.

Quoted 8 lines

qemu_open() and qemu_close() are frequently called long after a monitor command has come and gone, so cur_mon won't work. For example, drive_add will cause qemu_open() to be called, but after the command has completed, the file will keep getting opened/closed during normal QEMU operation. I'm not sure why, I've just noticed this behavior.

Does anyone have any thoughts on this? It would require fd sets to be added to the default monitor only.

I think we have two design options that would make sense:

Quoted 7 lines
Quoted 3 lines

1. Make the file descriptors global instead of per-monitor. Is there a reason why each monitor has its own set of fds? (Also I'm wondering if they survive a monitor disconnect this way?)

I'd prefer to have them associated with a monitor object so that we can more easily keep track of whether or not they're in use by a monitor connection.

Hm, I see.

Quoted 5 lines
Quoted 2 lines

2. Save a monitor reference with the fdset information.

Are you saying that each monitor would have the same copy of fdset information?

This one doesn't really make sense indeed...

Quoted 6 lines
Quoted 4 lines

Allowing to send file descriptors on every monitor, but making only those of the default monitor actually usable, sounds like a bad choice to me.

What if we also allow them to be added only to the default monitor?

Would get you some kind of consistency at least, even though I don't like that secondary monitors can't use the functionality.

Can't we make the fdset information global, so that a qemu_open/close() searches all of them, but let it have a Monitor* owner for keeping track whether it's in use?

Kevin

#18 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

Quoted 70 lines · Kevin Wolf

Am 06.08.2012 15:32, schrieb Corey Bryant:

Quoted 46 lines · Kevin Wolf
Quoted 45 lines

Am 03.08.2012 00:21, schrieb Corey Bryant:

Quoted 33 lines
Quoted 16 lines
Quoted 16 lines
osdep.c +12 -0
@@ -84,6 +158,36 @@ int qemu_open(const char *name, int flags, ...)
        int ret;
        int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
Quoted 9 lines

osdep.c int qemu_open(const char *name, int flags, ...) · line 175

Quoted 3 lines
osdep.c +3 -0
+        }
+
+        fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);

I know that use of default_mon in this patch is not correct, but I wanted to get these patches out for review. I used default_mon for testing because cur_mon wasn't pointing to the monitor I'd added fd sets to. I need to figure out why.

Does it make sense to use default_mon here? After digging into this some more, I'm thinking it makes sense, and I'll explain why.

It looks like cur_mon can't be used. cur_mon will point to the monitor object for the duration of a command, and be reset to old_mon (NULL in my case) after the command completes.

Quoted 8 lines

qemu_open() and qemu_close() are frequently called long after a monitor command has come and gone, so cur_mon won't work. For example, drive_add will cause qemu_open() to be called, but after the command has completed, the file will keep getting opened/closed during normal QEMU operation. I'm not sure why, I've just noticed this behavior.

Does anyone have any thoughts on this? It would require fd sets to be added to the default monitor only.

I think we have two design options that would make sense:

Quoted 7 lines
Quoted 3 lines

1. Make the file descriptors global instead of per-monitor. Is there a reason why each monitor has its own set of fds? (Also I'm wondering if they survive a monitor disconnect this way?)

I'd prefer to have them associated with a monitor object so that we can more easily keep track of whether or not they're in use by a monitor connection.

Hm, I see.

Quoted 5 lines
Quoted 2 lines

2. Save a monitor reference with the fdset information.

Are you saying that each monitor would have the same copy of fdset information?

This one doesn't really make sense indeed...

Quoted 5 lines
Quoted 4 lines

Allowing to send file descriptors on every monitor, but making only those of the default monitor actually usable, sounds like a bad choice to me.

Quoted 8 lines
Quoted 1 line

What if we also allow them to be added only to the default monitor?

Would get you some kind of consistency at least, even though I don't like that secondary monitors can't use the functionality.

Can't we make the fdset information global, so that a qemu_open/close() searches all of them, but let it have a Monitor* owner for keeping track whether it's in use?

I think global fdsets might work (sorry I didn't think it through enough on my first reply). I think I'll need to drop the "in_use" flag and tie monitor references into the refcount. (I know I know, you suggested that a while back.. :). I'll give it a shot and see how it goes.

Signature · 2 lines
Regards,
Corey
#19 lore raw

Re: [Qemu-devel] [PATCH v5 6/6] block: Enable qemu_open/close to work with fd sets

Quoted 83 lines · Corey Bryant
Quoted 80 lines · Kevin Wolf

Am 06.08.2012 15:32, schrieb Corey Bryant:

Quoted 50 lines · Kevin Wolf
Quoted 49 lines

Am 03.08.2012 00:21, schrieb Corey Bryant:

Quoted 43 lines
Quoted 17 lines
Quoted 17 lines
(quoted diff) +13 -0
@@ -84,6 +158,36 @@ int qemu_open(const char *name, int flags, ...)
        int ret;
        int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
+        }
Quoted 9 lines

Review int qemu_open(const char *name, int flags, ...) · line 175

Quoted 2 lines
(quoted diff) +2 -0
+
+        fd = monitor_fdset_get_fd(default_mon, fdset_id, flags);

I know that use of default_mon in this patch is not correct, but I wanted to get these patches out for review. I used default_mon for testing because cur_mon wasn't pointing to the monitor I'd added fd sets
to. I need to figure out why.

Does it make sense to use default_mon here? After digging into this some more, I'm thinking it makes sense, and I'll explain why.

It looks like cur_mon can't be used. cur_mon will point to the monitor
object for the duration of a command, and be reset to old_mon (NULL in my case) after the command completes.

qemu_open() and qemu_close() are frequently called long after a monitor
command has come and gone, so cur_mon won't work. For example, drive_add will cause qemu_open() to be called, but after the command has
completed, the file will keep getting opened/closed during normal QEMU operation. I'm not sure why, I've just noticed this behavior.

Quoted 2 lines

Does anyone have any thoughts on this? It would require fd sets to be added to the default monitor only.

I think we have two design options that would make sense:

Quoted 8 lines
Quoted 4 lines

1. Make the file descriptors global instead of per-monitor. Is there a reason why each monitor has its own set of fds? (Also I'm
wondering
if they survive a monitor disconnect this way?)

I'd prefer to have them associated with a monitor object so that we can more easily keep track of whether or not they're in use by a monitor connection.

Hm, I see.

Quoted 5 lines
Quoted 2 lines

2. Save a monitor reference with the fdset information.

Are you saying that each monitor would have the same copy of fdset information?

This one doesn't really make sense indeed...

Quoted 6 lines
Quoted 4 lines

Allowing to send file descriptors on every monitor, but making only those of the default monitor actually usable, sounds like a bad choice to me.

What if we also allow them to be added only to the default monitor?

Would get you some kind of consistency at least, even though I don't like that secondary monitors can't use the functionality.

Quoted 8 lines
Quoted 3 lines

Can't we make the fdset information global, so that a qemu_open/close() searches all of them, but let it have a Monitor* owner for keeping track whether it's in use?

I think global fdsets might work (sorry I didn't think it through enough on my first reply). I think I'll need to drop the "in_use" flag and tie monitor references into the refcount. (I know I know, you suggested that a while back.. :). I'll give it a shot and see how it goes.

I just submitted the v7 patch series which makes fd sets global, rather than each Monitor object having an fd set. This allows the list of fd sets to be shared among all monitor connections.

Signature · 2 lines
Regards,
Corey