Skip to contentSkip to conversation

tools: enable xenstore-stubdom to use 9pfs

PATCH Superseded Juergen Gross 4 participants 52 messages Feb 5, 2024 – Feb 8, 2024

v4 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#0 lore raw

v4 cover tools: enable xenstore-stubdom to use 9pfs

This series is adding 9pfs support to Xenstore-stubdom, enabling it to do logging to a dom0 directory.

This is a prerequisite for the final goal to add live update support to Xenstore-stubdom, as it enables the stubdom to store its state in a dom0 file.

The 9pfs backend is a new daemon written from scratch. Using a dedicated 9pfs daemon has several advantages:

- it is using much less resources than a full blown qemu process
- it can serve multiple guests (the idea is to use it for other infrastructure domains, like qemu-stubdom or driver domains, too)
- it is designed to support several security enhancements, like limiting the number of files for a guest, or limiting the allocated file system space
- it doesn't support file links (neither hard nor soft links) or referencing parent directories via "..", minimizing the risk that a guest can "escape" from its home directory

Note that for now the daemon only contains the minimal needed functionality to do logging from Xenstore-stubdom. I didn't want to add all the 9pfs commands and security add-ons in the beginning, in order to avoid needless efforts in case the idea of the daemon is being rejected.

Changes in V4:
- patch 2 of V3 was applied
- added support of reading directories
- addressed review comments

Changes in V3:
- new patches 1, 23-25
- addressed review comments

Changes in V2:
- support of multiple rings per device
- xenlogd->xen-9pfsd rename
- addressed review comments
- fixed some bugs

Juergen Gross (32):
tools: add access macros for unaligned data
tools: add a new xen logging daemon
tools/xen-9pfsd: connect to frontend
tools/xen-9pfsd: add transport layer
tools/xen-9pfsd: add 9pfs response generation support tools/xen-9pfsd: add 9pfs version request support tools/xen-9pfsd: add 9pfs attach request support tools/xen-9pfsd: add 9pfs walk request support tools/xen-9pfsd: add 9pfs open request support tools/xen-9pfsd: add 9pfs clunk request support tools/xen-9pfsd: add 9pfs create request support tools/xen-9pfsd: add 9pfs stat request support tools/xen-9pfsd: add 9pfs write request support tools/xen-9pfsd: add 9pfs read request support tools/libs/light: add backend type for 9pfs PV devices tools/xl: support new 9pfs backend xen_9pfsd tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
stubdom: extend xenstore stubdom configs
tools: add 9pfs device to xenstore-stubdom tools/xenstored: add early_init() function tools/xenstored: move systemd handling to posix.c tools/xenstored: move all log-pipe handling into posix.c tools/xenstored: move all socket handling into posix.c tools/xenstored: get own domid in stubdom case tools/xenstored: rework ring page (un)map functions tools/xenstored: split domain_init()
tools/xenstored: map stubdom interface
tools/xenstored: mount 9pfs device in stubdom tools/xenstored: add helpers for filename handling tools/xenstored: support complete log capabilities in stubdom tools/xenstored: have a single do_control_memreport()

 docs/man/xl.cfg.5.pod.in                      |   36 +-
 stubdom/xenstore-minios.cfg                   |    2 +-
 stubdom/xenstorepvh-minios.cfg                |    2 +-
 tools/Makefile                                |    1 +
 tools/golang/xenlight/helpers.gen.go          |   16 +
 tools/golang/xenlight/types.gen.go            |   13 +
 tools/helpers/init-xenstore-domain.c          |   14 +
 .../Linux/init.d/sysconfig.xencommons.in      |    1 -
 tools/hotplug/Linux/launch-xenstore.in        |    1 +
 tools/include/libxl.h                         |   22 +
 tools/include/xen-tools/common-macros.h       |   17 +
 tools/libs/light/libxl_9pfs.c                 |  193 ++-
 tools/libs/light/libxl_create.c               |    4 +-
 tools/libs/light/libxl_dm.c                   |    2 +-
 tools/libs/light/libxl_types.idl              |   11 +
 tools/libs/light/libxl_types_internal.idl     |    1 +
 tools/xen-9pfsd/.gitignore                    |    1 +
 tools/xen-9pfsd/Makefile                      |   38 +
 tools/xen-9pfsd/io.c                          | 1510 +++++++++++++++++
 tools/xen-9pfsd/xen-9pfsd.c                   |  800 +++++++++
 tools/xen-9pfsd/xen-9pfsd.h                   |   99 ++
 tools/xenstored/Makefile.common               |    4 -
 tools/xenstored/control.c                     |   29 +-
 tools/xenstored/core.c                        |  274 +--
 tools/xenstored/core.h                        |   36 +-
 tools/xenstored/domain.c                      |   81 +-
 tools/xenstored/domain.h                      |    2 +
 tools/xenstored/lu_daemon.c                   |    4 +-
 tools/xenstored/minios.c                      |  102 +-
 tools/xenstored/posix.c                       |  263 ++-
 tools/xl/xl_parse.c                           |   23 +-
 31 files changed, 3261 insertions(+), 341 deletions(-)
 create mode 100644 tools/xen-9pfsd/.gitignore
 create mode 100644 tools/xen-9pfsd/Makefile
 create mode 100644 tools/xen-9pfsd/io.c
 create mode 100644 tools/xen-9pfsd/xen-9pfsd.c
 create mode 100644 tools/xen-9pfsd/xen-9pfsd.h
Signature · 1 line
2.35.3
#1 lore raw

PATCH v4 1/32 tools: add access macros for unaligned data

Add the basic access macros for unaligned data to common-macros.h.

---
V3:
- new patch

---
 tools/include/xen-tools/common-macros.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
tools/include/xen-tools/common-macros.h +17 -0
index e5ed603904..81fba2e9f5 100644
@@ -79,6 +79,10 @@
 #define __must_check __attribute__((__warn_unused_result__))
 #endif
 
+#ifndef __packed
+#define __packed __attribute__((__packed__))
+#endif
+
 #define container_of(ptr, type, member) ({              \
     typeof(((type *)0)->member) *mptr__ = (ptr);        \
     (type *)((char *)mptr__ - offsetof(type, member));  \
@@ -87,4 +91,17 @@
 #define __AC(X, Y)   (X ## Y)
 #define _AC(X, Y)    __AC(X, Y)
 
+#define get_unaligned_t(type, ptr) ({                               \
+    const struct { type x; } __packed *ptr_ = (typeof(ptr_))(ptr);  \
+    ptr_->x;                                                        \
+})
+
+#define put_unaligned_t(type, val, ptr) do {                        \
+    struct { type x; } __packed *ptr_ = (typeof(ptr_))(ptr);        \
+    ptr_->x = val;                                                  \
+} while (0)
+
+#define get_unaligned(ptr)      get_unaligned_t(typeof(*(ptr)), ptr)
+#define put_unaligned(val, ptr) put_unaligned_t(typeof(*(ptr)), val, ptr)
+
 #endif	/* __XEN_TOOLS_COMMON_MACROS__ */
Signature · 1 line
2.35.3
#2 lore raw

PATCH v4 2/32 tools: add a new xen logging daemon

In reply to Juergen Gross

Add "xen-9pfsd", a new logging daemon meant to support infrastructure domains (e.g. xenstore-stubdom) to access files in dom0.

For now only add the code needed for starting the daemon and registering it with Xenstore via a new "libxl/xen-9pfs/state" node by writing the "running" state to it.

---
V2:
- rename from xenlogd to xen-9pfsd (Andrew Cooper)
- use a backend domain local Xenstore node (Jason Andryuk)
- use "volatile" for stop_me (Andrew Cooper)
V3:
- fix SPDX Identifier (Andrew Cooper)
V4:
- add strerror() test to error logging (Andrew Cooper)
- don't handle "daemon already running" as error (Anthony Perard)

---
 tools/Makefile              |   1 +
 tools/xen-9pfsd/.gitignore  |   1 +
 tools/xen-9pfsd/Makefile    |  38 ++++++++++
 tools/xen-9pfsd/xen-9pfsd.c | 147 ++++++++++++++++++++++++++++++++++++
 4 files changed, 187 insertions(+)
 create mode 100644 tools/xen-9pfsd/.gitignore
 create mode 100644 tools/xen-9pfsd/Makefile
 create mode 100644 tools/xen-9pfsd/xen-9pfsd.c
tools/Makefile +1 -0
index 3a510663a0..f8faa3a902 100644
@@ -32,6 +32,7 @@ SUBDIRS-y += xenpmd
 SUBDIRS-$(CONFIG_GOLANG) += golang
 SUBDIRS-y += xl
 SUBDIRS-y += helpers
+SUBDIRS-y += xen-9pfsd
 SUBDIRS-$(CONFIG_X86) += xenpaging
 SUBDIRS-$(CONFIG_X86) += debugger
 SUBDIRS-$(CONFIG_TESTS) += tests
tools/xen-9pfsd/.gitignore new file +1 -0
new file mode 100644
index 0000000000..d0c2d223ef
@@ -0,0 +1 @@
+/xen-9pfsd
tools/xen-9pfsd/Makefile new file +38 -0
new file mode 100644
index 0000000000..4e35202f08
@@ -0,0 +1,38 @@
+#
+# tools/xen-9pfsd/Makefile
+#
+
+XEN_ROOT = $(CURDIR)/../..
+include $(XEN_ROOT)/tools/Rules.mk
+
+CFLAGS += $(PTHREAD_CFLAGS)
+LDFLAGS += $(PTHREAD_LDFLAGS)
+
+TARGETS := xen-9pfsd
+
+XEN-9PFSD_OBJS = xen-9pfsd.o
+$(XEN-9PFSD_OBJS): CFLAGS += $(CFLAGS_libxenstore)
+$(XEN-9PFSD_OBJS): CFLAGS += $(CFLAGS_libxenevtchn)
+$(XEN-9PFSD_OBJS): CFLAGS += $(CFLAGS_libxengnttab)
+xen-9pfsd: LDLIBS += $(call xenlibs-ldlibs,store evtchn gnttab)
+
+.PHONY: all
+all: $(TARGETS)
+
+xen-9pfsd: $(XEN-9PFSD_OBJS)
+	$(CC) $(LDFLAGS) -o $@ $(XEN-9PFSD_OBJS) $(LDLIBS) $(APPEND_LDFLAGS)
+
+.PHONY: install
+install: all
+	$(INSTALL_DIR) $(DESTDIR)$(LIBEXEC_BIN)
+	for i in $(TARGETS); do $(INSTALL_PROG) $$i $(DESTDIR)$(LIBEXEC_BIN); done
+
+.PHONY: uninstall
+uninstall:
+	for i in $(TARGETS); do rm -f $(DESTDIR)$(LIBEXEC_BIN)/$$i; done
+
+.PHONY: clean
+clean:
+	$(RM) *.o $(TARGETS) $(DEPS_RM)
+
+distclean: clean
tools/xen-9pfsd/xen-9pfsd.c new file +147 -0

147 lines not on this page · raw message

Signature · 1 line
2.35.3
#3 lore raw

Re: [PATCH v4 02/32] tools: add a new xen logging daemon

Quoted 2 lines · Juergen Gross

Add "xen-9pfsd", a new logging daemon meant to support infrastructure domains (e.g. xenstore-stubdom) to access files in dom0.

I was still expecting for "logging" to disappear from this.

In both cases it could just be deleted the sentences still work, although the subject ought to gain a xen-9pfsd part.

Happy to fix on commit.

Quoted 4 lines
 tools/Makefile              |   1 +
 tools/xen-9pfsd/.gitignore  |   1 +
 tools/xen-9pfsd/Makefile    |  38 ++++++++++
 tools/xen-9pfsd/xen-9pfsd.c | 147 ++++++++++++++++++++++++++++++++++++

Asking just in case...  Do we really want the "xen-" in the directory? tools/9pfsd is still perfectly descriptive, and more amenable to tab completion given what else is in tools/

~Andrew

#4 lore raw

Re: [PATCH v4 02/32] tools: add a new xen logging daemon

Quoted 11 lines · Andrew Cooper
Quoted 2 lines · Juergen Gross

Add "xen-9pfsd", a new logging daemon meant to support infrastructure domains (e.g. xenstore-stubdom) to access files in dom0.

I was still expecting for "logging" to disappear from this.

In both cases it could just be deleted the sentences still work, although the subject ought to gain a xen-9pfsd part.

Happy to fix on commit.

Quoted 8 lines
Quoted 4 lines
  tools/Makefile              |   1 +
  tools/xen-9pfsd/.gitignore  |   1 +
  tools/xen-9pfsd/Makefile    |  38 ++++++++++
  tools/xen-9pfsd/xen-9pfsd.c | 147 ++++++++++++++++++++++++++++++++++++

Asking just in case...  Do we really want the "xen-" in the directory? tools/9pfsd is still perfectly descriptive, and more amenable to tab completion given what else is in tools/

I'll change it.

Juergen

#5 lore raw

PATCH v4 3/32 tools/xen-9pfsd: connect to frontend

In reply to Juergen Gross

Add the code for connecting to frontends to xenlogd.

---
V2:
- support multiple rings per device (Jason Andryuk)
- don't set .revents initially (Jason Andryuk)
- call poll() with infinite timeout (Jason Andryuk)
- take mutex before calling pthread_cond_signal() V3:
- fix SPDX indentifier (Andrew Cooper)
- better validation of host path (Jason Andryuk)
- don't hard-code dom0 in backend nodes (Jason Andryuk)
- use bool instead of int for some functions' return types
- open root directory (Jason Andryuk)

---
 tools/xen-9pfsd/Makefile    |   2 +-
 tools/xen-9pfsd/io.c        |  45 +++
 tools/xen-9pfsd/xen-9pfsd.c | 653 +++++++++++++++++++++++++++++++++++-
 tools/xen-9pfsd/xen-9pfsd.h |  61 ++++
 4 files changed, 757 insertions(+), 4 deletions(-)
 create mode 100644 tools/xen-9pfsd/io.c
 create mode 100644 tools/xen-9pfsd/xen-9pfsd.h
tools/xen-9pfsd/Makefile +1 -1
index 4e35202f08..2023b19c62 100644
@@ -10,7 +10,7 @@ LDFLAGS += $(PTHREAD_LDFLAGS)
 
 TARGETS := xen-9pfsd
 
-XEN-9PFSD_OBJS = xen-9pfsd.o
+XEN-9PFSD_OBJS = xen-9pfsd.o io.o
 $(XEN-9PFSD_OBJS): CFLAGS += $(CFLAGS_libxenstore)
 $(XEN-9PFSD_OBJS): CFLAGS += $(CFLAGS_libxenevtchn)
 $(XEN-9PFSD_OBJS): CFLAGS += $(CFLAGS_libxengnttab)
tools/xen-9pfsd/io.c new file +45 -0

45 lines not on this page · raw message

tools/xen-9pfsd/xen-9pfsd.c +650 -3

705 lines not on this page · raw message

tools/xen-9pfsd/xen-9pfsd.h new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
2.35.3
#6 lore raw

PATCH v4 4/32 tools/xen-9pfsd: add transport layer

In reply to Juergen Gross

Add the transport layer of 9pfs. This is basically the infrastructure to receive requests from the frontend and to send the related answers via the rings.

---
V2:
- rename put_request_bytes() (Jason Andryuk)
- rename get_request_bytes() and put_response_bytes() len parameter (Jason Andryuk)
- don't unmask event channel if error indicator is set (Jason Andryuk)

---
 tools/xen-9pfsd/io.c        | 143 +++++++++++++++++++++++++++++++++++-
 tools/xen-9pfsd/xen-9pfsd.h |  16 ++++
 2 files changed, 156 insertions(+), 3 deletions(-)
tools/xen-9pfsd/io.c +140 -3
index eb7c136e09..4312a62dfe 100644
@@ -6,39 +6,176 @@
  * Copyright (C) 2024 Juergen Gross <[email protected]>
  *
  * I/O thread handling.
+ *
+ * Only handle one request at a time, pushing out the complete response
+ * before looking for the next request.
  */
 
 #include <stdbool.h>
+#include <stdlib.h>
 #include <string.h>
 #include <syslog.h>
+#include <xenctrl.h>           /* For cpu barriers. */
+#include <xen-tools/common-macros.h>
 
 #include "xen-9pfsd.h"
 
+/*
+ * Note that the ring names "in" and "out" are from the frontend's
+ * perspective, so the "in" ring will be used for responses to the frontend,
+ * while the "out" ring is used for requests from the frontend to the
+ * backend.
+ */
+static unsigned int ring_in_free(struct ring *ring)
+{
+    unsigned int queued;
+
+    queued = xen_9pfs_queued(ring->prod_pvt_in, ring->intf->in_cons,
+                             ring->ring_size);
+    xen_rmb();
+
+    return ring->ring_size - queued;
+}
+
+static unsigned int ring_out_data(struct ring *ring)
+{
+    unsigned int queued;
+
+    queued = xen_9pfs_queued(ring->intf->out_prod, ring->cons_pvt_out,
+                             ring->ring_size);
+    xen_rmb();
+
+    return queued;
+}
+
+static unsigned int get_request_bytes(struct ring *ring, unsigned int off,
+                                      unsigned int total_len)
+{
+    unsigned int size;
+    unsigned int out_data = ring_out_data(ring);
+    RING_IDX prod, cons;
+
+    size = min(total_len - off, out_data);
+    prod = xen_9pfs_mask(ring->intf->out_prod, ring->ring_size);
+    cons = xen_9pfs_mask(ring->cons_pvt_out, ring->ring_size);
+    xen_9pfs_read_packet(ring->buffer + off, ring->data.out, size,
+                         prod, &cons, ring->ring_size);
+
+    xen_rmb();           /* Read data out before setting visible consumer. */
+    ring->cons_pvt_out += size;
+    ring->intf->out_cons = ring->cons_pvt_out;
+
+    /* Signal that more space is available now. */
+    xenevtchn_notify(xe, ring->evtchn);
+
+    return size;
+}
+
+static unsigned int put_response_bytes(struct ring *ring, unsigned int off,
+                                       unsigned int total_len)
+{
+    unsigned int size;
+    unsigned int in_data = ring_in_free(ring);
+    RING_IDX prod, cons;
+
+    size = min(total_len - off, in_data);
+    prod = xen_9pfs_mask(ring->prod_pvt_in, ring->ring_size);
+    cons = xen_9pfs_mask(ring->intf->in_cons, ring->ring_size);
+    xen_9pfs_write_packet(ring->data.in, ring->buffer + off, size,
+                          &prod, cons, ring->ring_size);
+
+    xen_wmb();           /* Write data out before setting visible producer. */
+    ring->prod_pvt_in += size;
+    ring->intf->in_prod = ring->prod_pvt_in;
+
+    return size;
+}
+
 static bool io_work_pending(struct ring *ring)
 {
     if ( ring->stop_thread )
         return true;
-    return false;
+    if ( ring->error )
+        return false;
+    return ring->handle_response ? ring_in_free(ring) : ring_out_data(ring);
 }
 
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
+    unsigned int count = 0;
+    struct p9_header hdr;
+    bool in_hdr = true;
+
+    ring->max_size = ring->ring_size;
+    ring->buffer = malloc(ring->max_size);
+    if ( !ring->buffer )
+    {
+        syslog(LOG_CRIT, "memory allocation failure!");
+        return NULL;
+    }
 
     while ( !ring->stop_thread )
     {
         pthread_mutex_lock(&ring->mutex);
         if ( !io_work_pending(ring) )
         {
-            if ( xenevtchn_unmask(xe, ring->evtchn) < 0 )
+            if ( !ring->error && xenevtchn_unmask(xe, ring->evtchn) < 0 )
                 syslog(LOG_WARNING, "xenevtchn_unmask() failed");
             pthread_cond_wait(&ring->cond, &ring->mutex);
         }
         pthread_mutex_unlock(&ring->mutex);
 
-        /* TODO: I/O handling. */
+        if ( ring->stop_thread || ring->error )
+            continue;
+
+        if ( !ring->handle_response )
+        {
+            if ( in_hdr )
+            {
+                count += get_request_bytes(ring, count, sizeof(hdr));
+                if ( count != sizeof(hdr) )
+                    continue;
+                hdr = *(struct p9_header *)ring->buffer;
+                if ( hdr.size > ring->max_size || hdr.size < sizeof(hdr) )
+                {
+                    syslog(LOG_ERR, "%u.%u specified illegal request length %u",
+                           ring->device->domid, ring->device->devid, hdr.size);
+                    ring->error = true;
+                    continue;
+                }
+                in_hdr = false;
+            }
+
+            count += get_request_bytes(ring, count, hdr.size);
+            if ( count < hdr.size )
+                continue;
+
+            /* TODO: handle request (will rewrite hdr.size). */
+
+            ring->handle_response = true;
+            hdr.size = ((struct p9_header *)ring->buffer)->size;
+            count = 0;
+        }
+
+        if ( ring->handle_response )
+        {
+            count += put_response_bytes(ring, count, hdr.size);
+
+            if ( count == hdr.size )
+            {
+                /* Signal presence of response. */
+                xenevtchn_notify(xe, ring->evtchn);
+
+                ring->handle_response = false;
+                in_hdr = true;
+                count = 0;
+            }
+        }
     }
 
+    free(ring->buffer);
+
     ring->thread_active = false;
 
     return NULL;
tools/xen-9pfsd/xen-9pfsd.h +16 -0
index ff3562164a..d587f59a32 100644
@@ -15,6 +15,12 @@
 #define MAX_RING_ORDER           9
 #define MAX_OPEN_FILES_DEFAULT   5
 
+struct p9_header {
+    uint32_t size;
+    uint8_t cmd;
+    uint16_t tag;
+} __attribute__((packed));
+
 typedef struct device device;
 
 struct ring {
@@ -29,7 +35,17 @@ struct ring {
     struct xen_9pfs_data_intf *intf;
     unsigned int ring_order;
     RING_IDX ring_size;
+
+    /* Transport layer data. */
     struct xen_9pfs_data data;
+    RING_IDX prod_pvt_in;
+    RING_IDX cons_pvt_out;
+
+    /* Request and response handling. */
+    uint32_t max_size;
+    bool error;             /* Protocol error - stop processing. */
+    bool handle_response;   /* Main loop now handling response. */
+    void *buffer;           /* Request/response buffer. */
 };
 
 struct device {
Signature · 1 line
2.35.3
#7 lore raw

PATCH v4 5/32 tools/xen-9pfsd: add 9pfs response generation support

In reply to Juergen Gross

Add support for generation a 9pfs protocol response via a format based approach.

Strings are stored in a per device string buffer and they are referenced via their offset in this buffer. This allows to avoid having to dynamically allocate memory for each single string.

As a first user of the response handling add a generic p9_error() function which will be used to return any error to the client.

Add all format parsing variants in order to avoid additional code churn later when adding the users of those variants. Prepare a special case for the "read" case already (format character 'D'): in order to avoid adding another buffer for read data support doing the read I/O directly into the response buffer.

---
V2:
- check parameter size limits (Jason Andryuk)
V3:
- use new unaligned access macros (Jason Andryuk)
V4:
- use recursion in fill_buffer() as a preparation for reading dirs

---
 tools/xen-9pfsd/io.c        | 217 +++++++++++++++++++++++++++++++++++-
 tools/xen-9pfsd/xen-9pfsd.h |   3 +
 2 files changed, 219 insertions(+), 1 deletion(-)
tools/xen-9pfsd/io.c +216 -1
index 4312a62dfe..4a44c70c4d 100644
@@ -11,6 +11,7 @@
  * before looking for the next request.
  */
 
+#include <errno.h>
 #include <stdbool.h>
 #include <stdlib.h>
 #include <string.h>
@@ -20,6 +21,16 @@
 
 #include "xen-9pfsd.h"
 
+/* P9 protocol commands (response is either cmd+1 or P9_CMD_ERROR). */
+#define P9_CMD_ERROR      107
+
+struct p9_qid {
+    uint8_t type;
+#define QID_TYPE_DIR      0x80
+    uint32_t version;
+    uint64_t path;
+};
+
 /*
  * Note that the ring names "in" and "out" are from the frontend's
  * perspective, so the "in" ring will be used for responses to the frontend,
@@ -100,6 +111,200 @@ static bool io_work_pending(struct ring *ring)
     return ring->handle_response ? ring_in_free(ring) : ring_out_data(ring);
 }
 
+static void fmt_err(const char *fmt)
+{
+    syslog(LOG_CRIT, "illegal format %s passed to fill_buffer()", fmt);
+    exit(1);
+}
+
+/*
+ * Fill buffer with response data.
+ * fmt is a sequence of format characters. Supported characters are:
+ * a: an array (2 bytes number of elements + the following format as elements)
+ *    The number of elements is passed in the first unsigned int parameter, the
+ *    next parameter is a pointer to an array of elements as denoted by the next
+ *    format character.
+ * b: 1 byte unsigned integer
+ * u: 2 byte unsigned integer
+ *    The parameter is a pointer to a uint16_t value
+ * D: Data blob (4 byte length + <length> bytes)
+ *    2 parameters are consumed, first an unsigned int for the length, then a
+ *    pointer to the first uint8_t value.
+ *    No array support.
+ * L: 8 byte unsigned integer
+ *    The parameter is a pointer to a uint64_t value
+ * Q: Qid (struct p9_qid)
+ * S: String (2 byte length + <length> characters)
+ *    The length is obtained via strlen() of the parameter, being a pointer
+ *    to the first character of the string
+ * U: 4 byte unsigned integer
+ *    The parameter is a pointer to a uint32_t value
+ */
+static void fill_buffer_at(void **data, const char *fmt, ...);
+static void vfill_buffer_at(void **data, const char *fmt, va_list ap)
+{
+    const char *f;
+    const void *par;
+    const char *str_val;
+    const struct p9_qid *qid;
+    unsigned int len;
+    unsigned int array_sz = 0;
+    unsigned int elem_sz = 0;
+
+    for ( f = fmt; *f; f++ )
+    {
+        if ( !array_sz )
+            par = va_arg(ap, const void *);
+        else
+        {
+            par += elem_sz;
+            array_sz--;
+        }
+
+        switch ( *f )
+        {
+        case 'a':
+            f++;
+            if ( !*f || array_sz )
+                fmt_err(fmt);
+            array_sz = *(const unsigned int *)par;
+            if ( array_sz > 0xffff )
+            {
+                syslog(LOG_CRIT, "array size %u in fill_buffer()", array_sz);
+                exit(1);
+            }
+            put_unaligned(array_sz, (uint16_t *)*data);
+            *data += sizeof(uint16_t);
+            par = va_arg(ap, const void *);
+            elem_sz = 0;
+            break;
+
+        case 'b':
+            put_unaligned(*(const uint8_t *)par, (uint8_t *)*data);
+            elem_sz = sizeof(uint8_t);
+            *data += sizeof(uint8_t);
+            break;
+
+        case 'u':
+            put_unaligned(*(const uint16_t *)par, (uint16_t *)*data);
+            elem_sz = sizeof(uint16_t);
+            *data += sizeof(uint16_t);
+            break;
+
+        case 'D':
+            if ( array_sz )
+                fmt_err(fmt);
+            len = *(const unsigned int *)par;
+            put_unaligned(len, (uint32_t *)*data);
+            *data += sizeof(uint32_t);
+            par = va_arg(ap, const void *);
+            if ( *data != par )
+                memcpy(*data, par, len);
+            *data += len;
+            break;
+
+        case 'L':
+            put_unaligned(*(const uint64_t *)par, (uint64_t *)*data);
+            elem_sz = sizeof(uint64_t);
+            *data += sizeof(uint64_t);
+            break;
+
+        case 'Q':
+            qid = par;
+            elem_sz = sizeof(*qid);
+            fill_buffer_at(data, "bUL", &qid->type, &qid->version, &qid->path);
+            break;
+
+        case 'S':
+            str_val = par;
+            elem_sz = sizeof(str_val);
+            len = strlen(str_val);
+            if ( len > 0xffff )
+            {
+                syslog(LOG_CRIT, "string length %u in fill_buffer()", len);
+                exit(1);
+            }
+            put_unaligned(len, (uint16_t *)*data);
+            *data += sizeof(uint16_t);
+            memcpy(*data, str_val, len);
+            *data += len;
+            break;
+
+        case 'U':
+            put_unaligned(*(const uint32_t *)par, (uint32_t *)*data);
+            elem_sz = sizeof(uint32_t);
+            *data += sizeof(uint32_t);
+            break;
+
+        default:
+            fmt_err(fmt);
+        }
+
+        if ( array_sz )
+            f--;
+    }
+}
+
+static void fill_buffer_at(void **data, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    vfill_buffer_at(data, fmt, ap);
+    va_end(ap);
+}
+
+static void fill_buffer(struct ring *ring, uint8_t cmd, uint16_t tag,
+                        const char *fmt, ...)
+{
+    struct p9_header *hdr = ring->buffer;
+    void *data = hdr + 1;
+    va_list ap;
+
+    hdr->cmd = cmd;
+    hdr->tag = tag;
+
+    va_start(ap, fmt);
+    vfill_buffer_at(&data, fmt, ap);
+    va_end(ap);
+
+    hdr->size = data - ring->buffer;
+}
+
+static unsigned int add_string(struct ring *ring, const char *str,
+                               unsigned int len)
+{
+    char *tmp;
+    unsigned int ret;
+
+    if ( ring->str_used + len + 1 > ring->str_size )
+    {
+        tmp = realloc(ring->str, ring->str_used + len + 1);
+        if ( !tmp )
+            return ~0;
+        ring->str = tmp;
+        ring->str_size = ring->str_used + len + 1;
+    }
+
+    ret = ring->str_used;
+    memcpy(ring->str + ret, str, len);
+    ring->str_used += len;
+    ring->str[ring->str_used++] = 0;
+
+    return ret;
+}
+
+static void p9_error(struct ring *ring, uint16_t tag, uint32_t err)
+{
+    unsigned int erroff;
+
+    strerror_r(err, ring->buffer, ring->ring_size);
+    erroff = add_string(ring, ring->buffer, strlen(ring->buffer));
+    fill_buffer(ring, P9_CMD_ERROR, tag, "SU",
+                erroff != ~0 ? ring->str + erroff : "cannot allocate memory",
+                &err);
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -151,7 +356,16 @@ void *io_thread(void *arg)
             if ( count < hdr.size )
                 continue;
 
-            /* TODO: handle request (will rewrite hdr.size). */
+            ring->str_used = 0;
+
+            switch ( hdr.cmd )
+            {
+            default:
+                syslog(LOG_DEBUG, "%u.%u sent unhandled command %u\n",
+                       ring->device->domid, ring->device->devid, hdr.cmd);
+                p9_error(ring, hdr.tag, EOPNOTSUPP);
+                break;
+            }
 
             ring->handle_response = true;
             hdr.size = ((struct p9_header *)ring->buffer)->size;
@@ -174,6 +388,7 @@ void *io_thread(void *arg)
         }
     }
 
+    free(ring->str);
     free(ring->buffer);
 
     ring->thread_active = false;
tools/xen-9pfsd/xen-9pfsd.h +3 -0
index d587f59a32..0cde0d2bb8 100644
@@ -46,6 +46,9 @@ struct ring {
     bool error;             /* Protocol error - stop processing. */
     bool handle_response;   /* Main loop now handling response. */
     void *buffer;           /* Request/response buffer. */
+    char *str;              /* String work space. */
+    unsigned int str_size;  /* Size of *str. */
+    unsigned int str_used;  /* Currently used size of *str. */
 };
 
 struct device {
Signature · 1 line
2.35.3
Reviewed-by on v4 5/32
#8 lore raw

Re: [PATCH v4 05/32] tools/xen-9pfsd: add 9pfs response generation support

Quoted 11 lines · Juergen Gross

Add support for generation a 9pfs protocol response via a format based approach.

Strings are stored in a per device string buffer and they are referenced via their offset in this buffer. This allows to avoid having to dynamically allocate memory for each single string.

As a first user of the response handling add a generic p9_error() function which will be used to return any error to the client.

Quoted 8 lines

Add all format parsing variants in order to avoid additional code churn later when adding the users of those variants. Prepare a special case for the "read" case already (format character 'D'): in order to avoid adding another buffer for read data support doing the read I/O directly into the response buffer.

#9 lore raw

PATCH v4 6/32 tools/xen-9pfsd: add 9pfs version request support

In reply to Juergen Gross

Add the version request of the 9pfs protocol. For the version use the "9P2000.u" variant, as it is supported by Mini-OS and Linux.

For the request parsing add all format items needed even in future in order to avoid code churn for those additions later.

---
V3:
- use unaligned helper macros (Jason Andryuk)

---
 tools/xen-9pfsd/io.c | 201 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 201 insertions(+)
tools/xen-9pfsd/io.c +201 -0
index 4a44c70c4d..839dd1112c 100644
@@ -22,8 +22,12 @@
 #include "xen-9pfsd.h"
 
 /* P9 protocol commands (response is either cmd+1 or P9_CMD_ERROR). */
+#define P9_CMD_VERSION    100
 #define P9_CMD_ERROR      107
 
+#define P9_MIN_MSIZE      2048
+#define P9_VERSION        "9P2000.u"
+
 struct p9_qid {
     uint8_t type;
 #define QID_TYPE_DIR      0x80
@@ -294,6 +298,169 @@ static unsigned int add_string(struct ring *ring, const char *str,
     return ret;
 }
 
+static bool chk_data(struct ring *ring, void *data, unsigned int len)
+{
+    struct p9_header *hdr = ring->buffer;
+
+    if ( data + len <= ring->buffer + hdr->size )
+        return true;
+
+    errno = E2BIG;
+
+    return false;
+}
+
+static bool fill_data_elem(void **par, void **array, unsigned int *array_sz,
+                           unsigned int elem_sz, void *data)
+{
+    if ( *array_sz && !*array )
+    {
+        *array = calloc(*array_sz, elem_sz);
+        if ( !*array )
+            return false;
+        *par = *array;
+    }
+
+    memcpy(*par, data, elem_sz);
+
+    if ( *array_sz )
+    {
+        *par += elem_sz;
+        *array_sz -= 1;
+    }
+
+    return true;
+}
+
+/*
+ * Fill variables with request data.
+ * fmt is a sequence of format characters. Supported characters are:
+ * a: an array (2 bytes number of elements + the following format as elements)
+ *    The number of elements is stored in the first unsigned int parameter, the
+ *    next parameter is a pointer to an array of elements as denoted by the next
+ *    format character. The array is allocated dynamically.
+ * b: 1 byte unsigned integer
+ *    The value is stored in the next parameter with type uint8_t.
+ * D: Data blob (4 byte length + <length> bytes)
+ *    2 parameters are consumed, first an unsigned int for the length, then a
+ *    pointer to the first uint8_t value.
+ *    No array support.
+ * L: 8 byte unsigned integer
+ *    The value is stored in the next parameter with type uint64_t.
+ * S: String (2 byte length + <length> characters)
+ *    The 0-terminated string is stored in device->str + off, off is stored in
+ *    the next parameter with type unsigned int.
+ * U: 4 byte unsigned integer
+ *    The value is stored in the next parameter with type uint32_t.
+ *
+ * Return value: number of filled variables, errno will be set in case of
+ *   error.
+ */
+static int fill_data(struct ring *ring, const char *fmt, ...)
+{
+    struct p9_header *hdr = ring->buffer;
+    void *data = hdr + 1;
+    void *par;
+    unsigned int pars = 0;
+    const char *f;
+    va_list ap;
+    unsigned int len;
+    unsigned int str_off;
+    unsigned int array_sz = 0;
+    void **array = NULL;
+
+    va_start(ap, fmt);
+
+    for ( f = fmt; *f; f++ )
+    {
+        if ( !array_sz )
+            par = va_arg(ap, void *);
+
+        switch ( *f )
+        {
+        case 'a':
+            f++;
+            if ( !*f || array_sz )
+                fmt_err(fmt);
+            if ( !chk_data(ring, data, sizeof(uint16_t)) )
+                return pars;
+            array_sz = get_unaligned((uint16_t *)data);
+            data += sizeof(uint16_t);
+            *(unsigned int *)par = array_sz;
+            array = va_arg(ap, void **);
+            *array = NULL;
+            break;
+
+        case 'b':
+            if ( !chk_data(ring, data, sizeof(uint8_t)) )
+                return pars;
+            if ( !fill_data_elem(&par, array, &array_sz, sizeof(uint8_t),
+                                 data) )
+                return pars;
+            data += sizeof(uint8_t);
+            break;
+
+        case 'D':
+            if ( array_sz )
+                fmt_err(fmt);
+            if ( !chk_data(ring, data, sizeof(uint32_t)) )
+                return pars;
+            len = get_unaligned((uint32_t *)data);
+            data += sizeof(uint32_t);
+            *(unsigned int *)par = len;
+            par = va_arg(ap, void *);
+            if ( !chk_data(ring, data, len) )
+                return pars;
+            memcpy(par, data, len);
+            data += len;
+            break;
+
+        case 'L':
+            if ( !chk_data(ring, data, sizeof(uint64_t)) )
+                return pars;
+            if ( !fill_data_elem(&par, array, &array_sz, sizeof(uint64_t),
+                                 data) )
+                return pars;
+            data += sizeof(uint64_t);
+            break;
+
+        case 'S':
+            if ( !chk_data(ring, data, sizeof(uint16_t)) )
+                return pars;
+            len = get_unaligned((uint16_t *)data);
+            data += sizeof(uint16_t);
+            if ( !chk_data(ring, data, len) )
+                return pars;
+            str_off = add_string(ring, data, len);
+            if ( str_off == ~0 )
+                return pars;
+            if ( !fill_data_elem(&par, array, &array_sz, sizeof(unsigned int),
+                                 &str_off) )
+                return pars;
+            data += len;
+            break;
+
+        case 'U':
+            if ( !chk_data(ring, data, sizeof(uint32_t)) )
+                return pars;
+            if ( !fill_data_elem(&par, array, &array_sz, sizeof(uint32_t),
+                                 data) )
+                return pars;
+            data += sizeof(uint32_t);
+            break;
+
+        default:
+            fmt_err(fmt);
+        }
+
+        if ( array_sz )
+            f--;
+        pars++;
+    }
+
+    return pars;
+}
+
 static void p9_error(struct ring *ring, uint16_t tag, uint32_t err)
 {
     unsigned int erroff;
@@ -305,6 +472,36 @@ static void p9_error(struct ring *ring, uint16_t tag, uint32_t err)
                 &err);
 }
 
+static void p9_version(struct ring *ring, struct p9_header *hdr)
+{
+    uint32_t max_size;
+    unsigned int off;
+    char *version;
+    int ret;
+
+    ret = fill_data(ring, "US", &max_size, &off);
+    if ( ret != 2 )
+    {
+        p9_error(ring, hdr->tag, errno);
+        return;
+    }
+
+    if ( max_size < P9_MIN_MSIZE )
+    {
+        p9_error(ring, hdr->tag, EMSGSIZE);
+        return;
+    }
+
+    if ( max_size < ring->max_size )
+        ring->max_size = max_size;
+
+    version = ring->str + off;
+    if ( strcmp(version, P9_VERSION) )
+        version = "unknown";
+
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "US", &ring->max_size, version);
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -360,6 +557,10 @@ void *io_thread(void *arg)
 
             switch ( hdr.cmd )
             {
+            case P9_CMD_VERSION:
+                p9_version(ring, &hdr);
+                break;
+
             default:
                 syslog(LOG_DEBUG, "%u.%u sent unhandled command %u\n",
                        ring->device->domid, ring->device->devid, hdr.cmd);
Signature · 1 line
2.35.3
#10 lore raw

PATCH v4 7/32 tools/xen-9pfsd: add 9pfs attach request support

In reply to Juergen Gross

Add the attach request of the 9pfs protocol. This introduces the "fid" scheme of the 9pfs protocol.

As this will be needed later, use a dedicated memory allocation function in alloc_fid() and prepare a fid reference count.

For filling the qid data take the approach from the qemu 9pfs backend implementation.

---
V2:
- make fill_qid() parameter stbuf const (Jason Andryuk)
- free fids after disconnecting guest (Jason Andryuk)
V3:
- only store relative path in fid (Jason Andryuk)
V4:
- store a path directly usable by *at() functions in fid (Jason Andryuk)

---
 tools/xen-9pfsd/io.c        | 164 ++++++++++++++++++++++++++++++++++++
 tools/xen-9pfsd/xen-9pfsd.c |   6 ++
 tools/xen-9pfsd/xen-9pfsd.h |  14 +++
 3 files changed, 184 insertions(+)
tools/xen-9pfsd/io.c +164 -0
index 839dd1112c..4f6acefc87 100644
@@ -11,11 +11,14 @@
  * before looking for the next request.
  */
 
+#include <assert.h>
 #include <errno.h>
 #include <stdbool.h>
 #include <stdlib.h>
 #include <string.h>
 #include <syslog.h>
+#include <sys/types.h>
+#include <sys/stat.h>
 #include <xenctrl.h>           /* For cpu barriers. */
 #include <xen-tools/common-macros.h>
 
@@ -23,6 +26,7 @@
 
 /* P9 protocol commands (response is either cmd+1 or P9_CMD_ERROR). */
 #define P9_CMD_VERSION    100
+#define P9_CMD_ATTACH     104
 #define P9_CMD_ERROR      107
 
 #define P9_MIN_MSIZE      2048
@@ -461,6 +465,126 @@ static int fill_data(struct ring *ring, const char *fmt, ...)
     return pars;
 }
 
+static struct p9_fid *find_fid(device *device, unsigned int fid)
+{
+    struct p9_fid *fidp;
+
+    XEN_TAILQ_FOREACH(fidp, &device->fids, list)
+    {
+        if ( fidp->fid == fid )
+            return fidp;
+    }
+
+    return NULL;
+}
+
+static struct p9_fid *alloc_fid_mem(device *device, unsigned int fid,
+                                    const char *path)
+{
+    struct p9_fid *fidp;
+    size_t pathlen;
+
+    pathlen = strlen(path);
+    fidp = calloc(sizeof(*fidp) + pathlen + 1, 1);
+    if ( !fidp )
+        return NULL;
+
+    fidp->fid = fid;
+    strncpy(fidp->path, path, pathlen);
+
+    return fidp;
+}
+
+static struct p9_fid *alloc_fid(device *device, unsigned int fid,
+                                const char *path)
+{
+    struct p9_fid *fidp = NULL;
+
+    pthread_mutex_lock(&device->fid_mutex);
+
+    if ( find_fid(device, fid) )
+    {
+        errno = EBADFD;
+        goto out;
+    }
+
+    if ( device->n_fids >= device->max_open_files )
+    {
+        errno = EMFILE;
+        goto out;
+    }
+
+    fidp = alloc_fid_mem(device, fid, path);
+    if ( !fidp )
+        goto out;
+
+    fidp->ref = 1;
+    XEN_TAILQ_INSERT_HEAD(&device->fids, fidp, list);
+    device->n_fids++;
+
+ out:
+    pthread_mutex_unlock(&device->fid_mutex);
+
+    return fidp;
+}
+
+static void free_fid(device *device, struct p9_fid *fidp)
+{
+    if ( !fidp )
+        return;
+
+    pthread_mutex_lock(&device->fid_mutex);
+
+    fidp->ref--;
+    if ( !fidp->ref )
+    {
+        device->n_fids--;
+        XEN_TAILQ_REMOVE(&device->fids, fidp, list);
+        free(fidp);
+    }
+
+    pthread_mutex_unlock(&device->fid_mutex);
+}
+
+void free_fids(device *device)
+{
+    struct p9_fid *fidp;
+
+    while ( (fidp = XEN_TAILQ_FIRST(&device->fids)) != NULL )
+    {
+        XEN_TAILQ_REMOVE(&device->fids, fidp, list);
+        free(fidp);
+    }
+}
+
+static const char *relpath_from_path(const char *path)
+{
+    if (!strcmp(path, "/"))
+        return ".";
+
+    return (path[0] == '/') ? path + 1 : path;
+}
+
+static int fill_qid(device *device, const char *path, struct p9_qid *qid,
+                    const struct stat *stbuf)
+{
+    struct stat st;
+
+    if ( !stbuf )
+    {
+        if ( fstatat(device->root_fd, path, &st, 0) )
+            return errno;
+
+        stbuf = &st;
+    }
+
+    qid->type = S_ISDIR(stbuf->st_mode) ? QID_TYPE_DIR : 0;
+    qid->version = stbuf->st_mtime ^ (stbuf->st_size << 8);
+    qid->path = stbuf->st_ino;
+
+    return 0;
+}
+
 static void p9_error(struct ring *ring, uint16_t tag, uint32_t err)
 {
     unsigned int erroff;
@@ -502,6 +626,42 @@ static void p9_version(struct ring *ring, struct p9_header *hdr)
     fill_buffer(ring, hdr->cmd + 1, hdr->tag, "US", &ring->max_size, version);
 }
 
+static void p9_attach(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    uint32_t dummy_u32;
+    unsigned int dummy_uint;
+    struct p9_qid qid;
+    int ret;
+
+    ret = fill_data(ring, "UUSSU", &fid, &dummy_u32, &dummy_uint, &dummy_uint,
+                    &dummy_u32);
+    if ( ret != 5 )
+    {
+        p9_error(ring, hdr->tag, errno);
+        return;
+    }
+
+    device->root_fid = alloc_fid(device, fid, relpath_from_path("/"));
+    if ( !device->root_fid )
+    {
+        p9_error(ring, hdr->tag, errno);
+        return;
+    }
+
+    ret = fill_qid(device, device->root_fid->path, &qid, NULL);
+    if ( ret )
+    {
+        free_fid(device, device->root_fid);
+        device->root_fid = NULL;
+        p9_error(ring, hdr->tag, ret);
+        return;
+    }
+
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "Q", &qid);
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -561,6 +721,10 @@ void *io_thread(void *arg)
                 p9_version(ring, &hdr);
                 break;
 
+            case P9_CMD_ATTACH:
+                p9_attach(ring, &hdr);
+                break;
+
             default:
                 syslog(LOG_DEBUG, "%u.%u sent unhandled command %u\n",
                        ring->device->domid, ring->device->devid, hdr.cmd);
tools/xen-9pfsd/xen-9pfsd.c +6 -0
index 73b6c3a30e..b83b896bcc 100644
@@ -304,6 +304,9 @@ static device *new_device(unsigned int domid, unsigned int devid)
         return NULL;
     }
 
+    pthread_mutex_init(&device->fid_mutex, NULL);
+    XEN_TAILQ_INIT(&device->fids);
+
     val = read_backend_node(device, "security_model");
     if ( !val || strcmp(val, "none") )
     {
@@ -399,6 +402,8 @@ static void disconnect_guest(device *device)
     }
 
     device->num_rings = 0;
+
+    free_fids(device);
 }
 
 static void close_device(device *device, enum xenbus_state state)
@@ -482,6 +487,7 @@ static void remove_device(device *device)
     XEN_TAILQ_REMOVE(&devs, device, list);
 
     disconnect_guest(device);
+    pthread_mutex_destroy(&device->fid_mutex);
     free_device(device);
 }
 
tools/xen-9pfsd/xen-9pfsd.h +14 -0
index 0cde0d2bb8..6c755411a7 100644
@@ -21,6 +21,13 @@ struct p9_header {
     uint16_t tag;
 } __attribute__((packed));
 
+struct p9_fid {
+    XEN_TAILQ_ENTRY(struct p9_fid) list;
+    unsigned int fid;
+    unsigned int ref;
+    char path[];
+};
+
 typedef struct device device;
 
 struct ring {
@@ -71,10 +78,17 @@ struct device {
     unsigned int num_rings;
     struct ring *ring[MAX_RINGS];
     int root_fd;
+
+    /* File system handling. */
+    pthread_mutex_t fid_mutex;
+    XEN_TAILQ_HEAD(fidhead, struct p9_fid) fids;
+    struct p9_fid *root_fid;
+    unsigned int n_fids;
 };
 
 extern xenevtchn_handle *xe;
 
 void *io_thread(void *arg);
+void free_fids(device *device);
 
 #endif /* XEN_9PFSD_H */
Signature · 1 line
2.35.3
Reviewed-by on v4 7/32
#11 lore raw

Re: [PATCH v4 07/32] tools/xen-9pfsd: add 9pfs attach request support

Quoted 4 lines · Juergen Gross

Add the attach request of the 9pfs protocol. This introduces the "fid" scheme of the 9pfs protocol.

Quoted 8 lines

As this will be needed later, use a dedicated memory allocation function in alloc_fid() and prepare a fid reference count.

For filling the qid data take the approach from the qemu 9pfs backend implementation.

#12 lore raw

PATCH v4 8/32 tools/xen-9pfsd: add 9pfs walk request support

In reply to Juergen Gross

Add the walk request of the 9pfs protocol.

---
V2:
- don't allow walking across symbolic links

---
 tools/xen-9pfsd/io.c        | 171 ++++++++++++++++++++++++++++++++++++
 tools/xen-9pfsd/xen-9pfsd.h |   1 +
 2 files changed, 172 insertions(+)
tools/xen-9pfsd/io.c +171 -0
index 4f6acefc87..5b827706b7 100644
@@ -28,9 +28,11 @@
 #define P9_CMD_VERSION    100
 #define P9_CMD_ATTACH     104
 #define P9_CMD_ERROR      107
+#define P9_CMD_WALK       110
 
 #define P9_MIN_MSIZE      2048
 #define P9_VERSION        "9P2000.u"
+#define P9_WALK_MAXELEM   16
 
 struct p9_qid {
     uint8_t type;
@@ -478,6 +480,21 @@ static struct p9_fid *find_fid(device *device, unsigned int fid)
     return NULL;
 }
 
+static struct p9_fid *get_fid_ref(device *device, unsigned int fid)
+{
+    struct p9_fid *fidp;
+
+    pthread_mutex_lock(&device->fid_mutex);
+
+    fidp = find_fid(device, fid);
+    if ( fidp )
+        fidp->ref++;
+
+    pthread_mutex_unlock(&device->fid_mutex);
+
+    return fidp;
+}
+
 static struct p9_fid *alloc_fid_mem(device *device, unsigned int fid,
                                     const char *path)
 {
@@ -578,6 +595,10 @@ static int fill_qid(device *device, const char *path, struct p9_qid *qid,
         stbuf = &st;
     }
 
+    /* Don't allow symbolic links. */
+    if ( S_ISLNK(stbuf->st_mode) )
+        return EMLINK;
+
     qid->type = S_ISDIR(stbuf->st_mode) ? QID_TYPE_DIR : 0;
     qid->version = stbuf->st_mtime ^ (stbuf->st_size << 8);
     qid->path = stbuf->st_ino;
@@ -585,6 +606,20 @@ static int fill_qid(device *device, const char *path, struct p9_qid *qid,
     return 0;
 }
 
+static bool name_ok(const char *str)
+{
+    if ( !*str )
+        return false;
+
+    if ( strchr(str, '/' ) )
+        return false;
+
+    if ( !strcmp(str, "..") || !strcmp(str, ".") )
+        return false;
+
+    return true;
+}
+
 static void p9_error(struct ring *ring, uint16_t tag, uint32_t err)
 {
     unsigned int erroff;
@@ -662,6 +697,138 @@ static void p9_attach(struct ring *ring, struct p9_header *hdr)
     fill_buffer(ring, hdr->cmd + 1, hdr->tag, "Q", &qid);
 }
 
+static void p9_walk(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    uint32_t newfid;
+    struct p9_fid *fidp = NULL;
+    struct p9_qid *qids = NULL;
+    unsigned int n_names = 0;
+    unsigned int *names = NULL;
+    unsigned int walked = 0;
+    unsigned int i;
+    char *path = NULL;
+    unsigned int path_len;
+    int ret;
+
+    ret = fill_data(ring, "UUaS", &fid, &newfid, &n_names, &names);
+    if ( n_names > P9_WALK_MAXELEM )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        goto out;
+    }
+    if ( ret != 3 + n_names )
+    {
+        p9_error(ring, hdr->tag, errno);
+        goto out;
+    }
+
+    fidp = get_fid_ref(device, fid);
+    if ( !fidp )
+    {
+        p9_error(ring, hdr->tag, ENOENT);
+        goto out;
+    }
+    if ( fidp->opened )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        goto out;
+    }
+
+    path_len = strlen(fidp->path) + 1;
+    for ( i = 0; i < n_names; i++ )
+    {
+        if ( !name_ok(ring->str + names[i]) )
+        {
+            p9_error(ring, hdr->tag, ENOENT);
+            goto out;
+        }
+        path_len += strlen(ring->str + names[i]) + 1;
+    }
+    path = calloc(path_len + 1, 1);
+    if ( !path )
+    {
+        p9_error(ring, hdr->tag, ENOMEM);
+        goto out;
+    }
+    strcpy(path, fidp->path);
+
+    if ( n_names )
+    {
+        qids = calloc(n_names, sizeof(*qids));
+        if ( !qids )
+        {
+            p9_error(ring, hdr->tag, ENOMEM);
+            goto out;
+        }
+        for ( i = 0; i < n_names; i++ )
+        {
+            strcat(path, "/");
+            strcat(path, ring->str + names[i]);
+            ret = fill_qid(device, path, qids + i, NULL);
+            if ( ret )
+            {
+                if ( !walked )
+                {
+                    p9_error(ring, hdr->tag, errno);
+                    goto out;
+                }
+                break;
+            }
+            walked++;
+        }
+    }
+
+    if ( walked == n_names )
+    {
+        bool ok = false;
+
+        if ( fid == newfid )
+        {
+            struct p9_fid *new_fidp;
+
+            pthread_mutex_lock(&device->fid_mutex);
+
+            if ( fidp->ref != 2 )
+            {
+                errno = EBUSY;
+            }
+            else
+            {
+                new_fidp = alloc_fid_mem(device, fid, path);
+                if ( new_fidp )
+                {
+                    new_fidp->ref = 2;
+                    XEN_TAILQ_REMOVE(&device->fids, fidp, list);
+                    XEN_TAILQ_INSERT_HEAD(&device->fids, new_fidp, list);
+                    free(fidp);
+                    fidp = new_fidp;
+                    ok = true;
+                }
+            }
+
+            pthread_mutex_unlock(&device->fid_mutex);
+        }
+        else
+            ok = alloc_fid(device, newfid, path);
+
+        if ( !ok )
+        {
+            p9_error(ring, hdr->tag, errno);
+            goto out;
+        }
+    }
+
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "aQ", &walked, qids);
+
+ out:
+    free_fid(device, fidp);
+    free(qids);
+    free(path);
+    free(names);
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -725,6 +892,10 @@ void *io_thread(void *arg)
                 p9_attach(ring, &hdr);
                 break;
 
+            case P9_CMD_WALK:
+                p9_walk(ring, &hdr);
+                break;
+
             default:
                 syslog(LOG_DEBUG, "%u.%u sent unhandled command %u\n",
                        ring->device->domid, ring->device->devid, hdr.cmd);
tools/xen-9pfsd/xen-9pfsd.h +1 -0
index 6c755411a7..f01fffb0bb 100644
@@ -25,6 +25,7 @@ struct p9_fid {
     XEN_TAILQ_ENTRY(struct p9_fid) list;
     unsigned int fid;
     unsigned int ref;
+    bool opened;
     char path[];
 };
 
Signature · 1 line
2.35.3
#14 lore raw

PATCH v4 9/32 tools/xen-9pfsd: add 9pfs open request support

In reply to Juergen Gross

Add the open request of the 9pfs protocol.

---
V2:
- don't allow to open symbolic link
V3:
- use openat() (Jason Andryuk)
- use common error handling in p9_open()

---
 tools/xen-9pfsd/io.c        | 137 ++++++++++++++++++++++++++++++++++++
 tools/xen-9pfsd/xen-9pfsd.h |   4 ++
 2 files changed, 141 insertions(+)
tools/xen-9pfsd/io.c +137 -0
index 5b827706b7..2e2275e8ab 100644
@@ -19,6 +19,8 @@
 #include <syslog.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <dirent.h>
+#include <fcntl.h>
 #include <xenctrl.h>           /* For cpu barriers. */
 #include <xen-tools/common-macros.h>
 
@@ -29,6 +31,15 @@
 #define P9_CMD_ATTACH     104
 #define P9_CMD_ERROR      107
 #define P9_CMD_WALK       110
+#define P9_CMD_OPEN       112
+
+/* P9 protocol open flags. */
+#define P9_OREAD            0   /* read */
+#define P9_OWRITE           1   /* write */
+#define P9_ORDWR            2   /* read and write */
+#define P9_OMODEMASK     0x03
+#define P9_OTRUNC        0x10   /* or'ed in, truncate file first */
+#define P9_OREMOVE       0x40   /* or'ed in, remove file after clunk */
 
 #define P9_MIN_MSIZE      2048
 #define P9_VERSION        "9P2000.u"
@@ -829,6 +840,128 @@ static void p9_walk(struct ring *ring, struct p9_header *hdr)
     free(names);
 }
 
+static int open_flags_from_mode(uint8_t mode)
+{
+    int flags;
+
+    switch ( mode & P9_OMODEMASK )
+    {
+    case P9_OREAD:
+        flags = O_RDONLY;
+        break;
+
+    case P9_OWRITE:
+        flags = O_WRONLY;
+        break;
+
+    case P9_ORDWR:
+        flags = O_RDWR;
+        break;
+
+    default:
+        errno = EINVAL;
+        return -1;
+    }
+
+    if ( mode & P9_OTRUNC )
+        flags |= O_TRUNC;
+
+    return flags;
+}
+
+static unsigned int get_iounit(struct ring *ring, struct stat *st)
+{
+    return (ring->max_size - st->st_blksize) & ~(st->st_blksize - 1);
+}
+
+static void p9_open(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    uint8_t mode;
+    struct p9_fid *fidp;
+    struct stat st;
+    struct p9_qid qid;
+    uint32_t iounit;
+    int flags;
+    int ret;
+
+    ret = fill_data(ring, "Ub", &fid, &mode);
+    if ( ret != 2 )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+    if ( mode & ~(P9_OMODEMASK | P9_OTRUNC | P9_OREMOVE) )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+
+    fidp = get_fid_ref(device, fid);
+    if ( !fidp )
+    {
+        p9_error(ring, hdr->tag, ENOENT);
+        return;
+    }
+    if ( fidp->opened )
+    {
+        errno = EINVAL;
+        goto err;
+    }
+
+    if ( fstatat(device->root_fd, fidp->path, &st, 0) < 0 )
+    {
+        errno = ENOENT;
+        goto err;
+    }
+
+    if ( S_ISLNK(st.st_mode) )
+    {
+        errno = EMLINK;
+        goto err;
+    }
+
+    fidp->isdir = S_ISDIR(st.st_mode);
+    fidp->mode = mode;
+    if ( fidp->isdir )
+    {
+        if ( mode != P9_OREAD )
+        {
+            errno = EINVAL;
+            goto err;
+        }
+        fidp->fd = openat(device->root_fd, fidp->path, O_RDONLY);
+        if ( fidp->fd < 0 )
+            goto err;
+        fidp->data = fdopendir(fidp->fd);
+        if ( !fidp->data )
+            goto err;
+    }
+    else
+    {
+        flags = open_flags_from_mode(mode);
+        if ( flags < 0 )
+            goto err;
+
+        fidp->fd = openat(device->root_fd, fidp->path, flags);
+        if ( fidp->fd < 0 )
+            goto err;
+    }
+
+    fill_qid(device, fidp->path, &qid, &st);
+    iounit = get_iounit(ring, &st);
+    fidp->opened = true;
+
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "QU", &qid, &iounit);
+
+    return;
+
+ err:
+    free_fid(device, fidp);
+    p9_error(ring, hdr->tag, errno);
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -896,6 +1029,10 @@ void *io_thread(void *arg)
                 p9_walk(ring, &hdr);
                 break;
 
+            case P9_CMD_OPEN:
+                p9_open(ring, &hdr);
+                break;
+
             default:
                 syslog(LOG_DEBUG, "%u.%u sent unhandled command %u\n",
                        ring->device->domid, ring->device->devid, hdr.cmd);
tools/xen-9pfsd/xen-9pfsd.h +4 -0
index f01fffb0bb..757be2da4b 100644
@@ -25,7 +25,11 @@ struct p9_fid {
     XEN_TAILQ_ENTRY(struct p9_fid) list;
     unsigned int fid;
     unsigned int ref;
+    int fd;
+    uint8_t mode;
     bool opened;
+    bool isdir;
+    void *data;    /* File type specific. */
     char path[];
 };
 
Signature · 1 line
2.35.3
#16 lore raw

PATCH v4 10/32 tools/xen-9pfsd: add 9pfs clunk request support

In reply to Juergen Gross

Add the clunk request of the 9pfs protocol.

---
V3:
- use unlinkat() (Jason Andryuk)

---
 tools/xen-9pfsd/io.c | 43 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 43 insertions(+)
tools/xen-9pfsd/io.c +43 -0
index 2e2275e8ab..74efd21c10 100644
@@ -32,6 +32,7 @@
 #define P9_CMD_ERROR      107
 #define P9_CMD_WALK       110
 #define P9_CMD_OPEN       112
+#define P9_CMD_CLUNK      120
 
 /* P9 protocol open flags. */
 #define P9_OREAD            0   /* read */
@@ -962,6 +963,44 @@ static void p9_open(struct ring *ring, struct p9_header *hdr)
     p9_error(ring, hdr->tag, errno);
 }
 
+static void p9_clunk(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    struct p9_fid *fidp;
+    int ret;
+
+    ret = fill_data(ring, "U", &fid);
+    if ( ret != 1 )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+
+    fidp = get_fid_ref(device, fid);
+    if ( !fidp )
+    {
+        p9_error(ring, hdr->tag, ENOENT);
+        return;
+    }
+
+    if ( fidp->opened )
+    {
+        fidp->opened = false;
+        free_fid(device, fidp);
+        close(fidp->fd);
+        if ( fidp->mode & P9_OREMOVE )
+            unlinkat(device->root_fd, fidp->path,
+                     fidp->isdir ? AT_REMOVEDIR : 0);
+    }
+
+    /* 2 calls of free_fid(): one for our reference, and one to free it. */
+    free_fid(device, fidp);
+    free_fid(device, fidp);
+
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "");
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -1033,6 +1072,10 @@ void *io_thread(void *arg)
                 p9_open(ring, &hdr);
                 break;
 
+            case P9_CMD_CLUNK:
+                p9_clunk(ring, &hdr);
+                break;
+
             default:
                 syslog(LOG_DEBUG, "%u.%u sent unhandled command %u\n",
                        ring->device->domid, ring->device->devid, hdr.cmd);
Signature · 1 line
2.35.3
#18 lore raw

PATCH v4 11/32 tools/xen-9pfsd: add 9pfs create request support

In reply to Juergen Gross

Add the create request of the 9pfs protocol.

---
V2:
- set permissions correctly (Jason Andryuk)
V3:
- use opendirat() etc. (Jason Andryuk)
- rework error handling a little bit

---
 tools/xen-9pfsd/io.c | 151 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 151 insertions(+)
tools/xen-9pfsd/io.c +151 -0
index 74efd21c10..583eea6059 100644
@@ -32,6 +32,7 @@
 #define P9_CMD_ERROR      107
 #define P9_CMD_WALK       110
 #define P9_CMD_OPEN       112
+#define P9_CMD_CREATE     114
 #define P9_CMD_CLUNK      120
 
 /* P9 protocol open flags. */
@@ -42,6 +43,12 @@
 #define P9_OTRUNC        0x10   /* or'ed in, truncate file first */
 #define P9_OREMOVE       0x40   /* or'ed in, remove file after clunk */
 
+/* P9 protocol create permission masks. */
+#define P9_CREATE_PERM_DIR        0x80000000
+#define P9_CREATE_PERM_NOTSUPP    0x03b00000   /* link, symlink, ... */
+#define P9_CREATE_PERM_DIR_MASK   0777
+#define P9_CREATE_PERM_FILE_MASK  0666
+
 #define P9_MIN_MSIZE      2048
 #define P9_VERSION        "9P2000.u"
 #define P9_WALK_MAXELEM   16
@@ -963,6 +970,146 @@ static void p9_open(struct ring *ring, struct p9_header *hdr)
     p9_error(ring, hdr->tag, errno);
 }
 
+static void p9_create(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    unsigned int name_off;
+    uint32_t perm;
+    uint8_t mode;
+    unsigned int ext_off;
+    struct p9_fid *fidp;
+    struct p9_fid *new_fidp;
+    char *path;
+    struct stat st;
+    struct p9_qid qid;
+    uint32_t iounit;
+    int flags;
+    int ret;
+
+    ret = fill_data(ring, "USUbS", &fid, &name_off, &perm, &mode, &ext_off);
+    if ( ret != 5 )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+
+    if ( !name_ok(ring->str + name_off) )
+    {
+        p9_error(ring, hdr->tag, ENOENT);
+        return;
+    }
+
+    if ( perm & P9_CREATE_PERM_NOTSUPP )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+
+    fidp = get_fid_ref(device, fid);
+    if ( !fidp || fidp->opened )
+    {
+        free_fid(device, fidp);
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+    if ( fstatat(device->root_fd, fidp->path, &st, 0) < 0 )
+    {
+        free_fid(device, fidp);
+        p9_error(ring, hdr->tag, errno);
+        return;
+    }
+
+    path = malloc(strlen(fidp->path) + strlen(ring->str + name_off) + 2);
+    if ( !path )
+    {
+        free_fid(device, fidp);
+        p9_error(ring, hdr->tag, ENOMEM);
+        return;
+    }
+    sprintf(path, "%s/%s", fidp->path, ring->str + name_off);
+    new_fidp = alloc_fid_mem(device, fid, path);
+    free(path);
+    if ( !new_fidp )
+    {
+        free_fid(device, fidp);
+        p9_error(ring, hdr->tag, ENOMEM);
+        return;
+    }
+
+    pthread_mutex_lock(&device->fid_mutex);
+
+    new_fidp->ref = fidp->ref;
+
+    if ( perm & P9_CREATE_PERM_DIR )
+    {
+        perm &= P9_CREATE_PERM_DIR_MASK & st.st_mode;
+        if ( mode != P9_OREAD )
+        {
+            errno = EINVAL;
+            goto err;
+        }
+        if ( mkdirat(device->root_fd, new_fidp->path, perm) < 0 )
+            goto err;
+
+        XEN_TAILQ_REMOVE(&device->fids, fidp, list);
+        XEN_TAILQ_INSERT_HEAD(&device->fids, new_fidp, list);
+        free(fidp);
+        fidp = new_fidp;
+        new_fidp = NULL;
+
+        fidp->fd = openat(device->root_fd, fidp->path, O_RDONLY);
+        if ( fidp->fd < 0 )
+            goto err;
+        fidp->data = fdopendir(fidp->fd);
+        if ( !fidp->data )
+            goto err;
+    }
+    else
+    {
+        flags = open_flags_from_mode(mode);
+        if ( flags < 0 )
+        {
+            errno = EINVAL;
+            goto err;
+        }
+        perm &= P9_CREATE_PERM_FILE_MASK & st.st_mode;
+
+        XEN_TAILQ_REMOVE(&device->fids, fidp, list);
+        XEN_TAILQ_INSERT_HEAD(&device->fids, new_fidp, list);
+        free(fidp);
+        fidp = new_fidp;
+        new_fidp = NULL;
+
+        fidp->fd = openat(device->root_fd, fidp->path, flags | O_CREAT | O_EXCL,
+                          perm);
+        if ( fidp->fd < 0 )
+            goto err;
+    }
+
+    if ( fstatat(device->root_fd, fidp->path, &st, 0) < 0 )
+        goto err;
+
+    fill_qid(device, fidp->path, &qid, &st);
+    iounit = get_iounit(ring, &st);
+    fidp->opened = true;
+    fidp->mode = mode;
+
+    pthread_mutex_unlock(&device->fid_mutex);
+
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "QU", &qid, &iounit);
+
+    return;
+
+ err:
+    p9_error(ring, hdr->tag, errno);
+
+    pthread_mutex_unlock(&device->fid_mutex);
+
+    free(new_fidp);
+    free_fid(device, fidp);
+}
+
 static void p9_clunk(struct ring *ring, struct p9_header *hdr)
 {
     device *device = ring->device;
@@ -1072,6 +1219,10 @@ void *io_thread(void *arg)
                 p9_open(ring, &hdr);
                 break;
 
+            case P9_CMD_CREATE:
+                p9_create(ring, &hdr);
+                break;
+
             case P9_CMD_CLUNK:
                 p9_clunk(ring, &hdr);
                 break;
Signature · 1 line
2.35.3
#20 lore raw

PATCH v4 12/32 tools/xen-9pfsd: add 9pfs stat request support

In reply to Juergen Gross

Add the stat request of the 9pfs protocol.

---
V3:
- use fstatat() (Jason Andryuk)
V4:
- add "s" format to fill_buffer() as a preparation for reading dirs

---
 tools/xen-9pfsd/io.c | 102 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 102 insertions(+)
tools/xen-9pfsd/io.c +102 -0
index 583eea6059..031cff9f0e 100644
@@ -34,6 +34,7 @@
 #define P9_CMD_OPEN       112
 #define P9_CMD_CREATE     114
 #define P9_CMD_CLUNK      120
+#define P9_CMD_STAT       124
 
 /* P9 protocol open flags. */
 #define P9_OREAD            0   /* read */
@@ -60,6 +61,25 @@ struct p9_qid {
     uint64_t path;
 };
 
+struct p9_stat {
+    uint16_t size;
+    uint16_t type;
+    uint32_t dev;
+    struct p9_qid qid;
+    uint32_t mode;
+    uint32_t atime;
+    uint32_t mtime;
+    uint64_t length;
+    const char *name;
+    const char *uid;
+    const char *gid;
+    const char *muid;
+    const char *extension;
+    uint32_t n_uid;
+    uint32_t n_gid;
+    uint32_t n_muid;
+};
+
 /*
  * Note that the ring names "in" and "out" are from the frontend's
  * perspective, so the "in" ring will be used for responses to the frontend,
@@ -166,6 +186,7 @@ static void fmt_err(const char *fmt)
  * S: String (2 byte length + <length> characters)
  *    The length is obtained via strlen() of the parameter, being a pointer
  *    to the first character of the string
+ * s: stat (struct p9_stat)
  * U: 4 byte unsigned integer
  *    The parameter is a pointer to a uint32_t value
  */
@@ -176,6 +197,8 @@ static void vfill_buffer_at(void **data, const char *fmt, va_list ap)
     const void *par;
     const char *str_val;
     const struct p9_qid *qid;
+    const struct p9_stat *stat;
+    uint16_t tlen;
     unsigned int len;
     unsigned int array_sz = 0;
     unsigned int elem_sz = 0;
@@ -259,6 +282,18 @@ static void vfill_buffer_at(void **data, const char *fmt, va_list ap)
             *data += len;
             break;
 
+        case 's':
+            stat = par;
+            elem_sz = sizeof(*stat);
+            tlen = stat->size + sizeof(stat->size);
+            fill_buffer_at(data, "uuuUQUUULSSSSSUUU", &tlen, &stat->size,
+                           &stat->type, &stat->dev, &stat->qid, &stat->mode,
+                           &stat->atime, &stat->mtime, &stat->length,
+                           stat->name, stat->uid, stat->gid, stat->muid,
+                           stat->extension, &stat->n_uid, &stat->n_gid,
+                           &stat->n_muid);
+            break;
+
         case 'U':
             put_unaligned(*(const uint32_t *)par, (uint32_t *)*data);
             elem_sz = sizeof(uint32_t);
@@ -1148,6 +1183,69 @@ static void p9_clunk(struct ring *ring, struct p9_header *hdr)
     fill_buffer(ring, hdr->cmd + 1, hdr->tag, "");
 }
 
+static void fill_p9_stat(device *device, struct p9_stat *p9s, struct stat *st,
+                         const char *name)
+{
+    memset(p9s, 0, sizeof(*p9s));
+    fill_qid(device, NULL, &p9s->qid, st);
+    p9s->mode = st->st_mode & 0777;
+    if ( S_ISDIR(st->st_mode) )
+        p9s->mode |= P9_CREATE_PERM_DIR;
+    p9s->atime = st->st_atime;
+    p9s->mtime = st->st_mtime;
+    p9s->length = st->st_size;
+    p9s->name = name;
+    p9s->uid = "";
+    p9s->gid = "";
+    p9s->muid = "";
+    p9s->extension = "";
+    p9s->n_uid = 0;
+    p9s->n_gid = 0;
+    p9s->n_muid = 0;
+
+    /*
+     * Size of individual fields without the size field, including 5 2-byte
+     * string length fields.
+     */
+    p9s->size = 71 + strlen(p9s->name);
+}
+
+static void p9_stat(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    struct p9_fid *fidp;
+    struct p9_stat p9s;
+    struct stat st;
+    int ret;
+
+    ret = fill_data(ring, "U", &fid);
+    if ( ret != 1 )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+
+    fidp = get_fid_ref(device, fid);
+    if ( !fidp )
+    {
+        p9_error(ring, hdr->tag, ENOENT);
+        return;
+    }
+
+    if ( fstatat(device->root_fd, fidp->path, &st, 0) < 0 )
+    {
+        p9_error(ring, hdr->tag, errno);
+        goto out;
+    }
+    fill_p9_stat(device, &p9s, &st, strrchr(fidp->path, '/') + 1);
+
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "s", &p9s);
+
+ out:
+    free_fid(device, fidp);
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -1227,6 +1325,10 @@ void *io_thread(void *arg)
                 p9_clunk(ring, &hdr);
                 break;
 
+            case P9_CMD_STAT:
+                p9_stat(ring, &hdr);
+                break;
+
             default:
                 syslog(LOG_DEBUG, "%u.%u sent unhandled command %u\n",
                        ring->device->domid, ring->device->devid, hdr.cmd);
Signature · 1 line
2.35.3
#22 lore raw
In reply to Juergen Gross

Hi Juergen,

Quoted 66 lines · Juergen Gross

This series is adding 9pfs support to Xenstore-stubdom, enabling it to do logging to a dom0 directory.

This is a prerequisite for the final goal to add live update support to Xenstore-stubdom, as it enables the stubdom to store its state in a dom0 file.

The 9pfs backend is a new daemon written from scratch. Using a dedicated 9pfs daemon has several advantages:

- it is using much less resources than a full blown qemu process
- it can serve multiple guests (the idea is to use it for other infrastructure domains, like qemu-stubdom or driver domains, too)
- it is designed to support several security enhancements, like limiting the number of files for a guest, or limiting the allocated file system space
- it doesn't support file links (neither hard nor soft links) or referencing parent directories via "..", minimizing the risk that a guest can "escape" from its home directory

Note that for now the daemon only contains the minimal needed functionality to do logging from Xenstore-stubdom. I didn't want to add all the 9pfs commands and security add-ons in the beginning, in order to avoid needless efforts in case the idea of the daemon is being rejected.

Changes in V4:
- patch 2 of V3 was applied
- added support of reading directories
- addressed review comments

Changes in V3:
- new patches 1, 23-25
- addressed review comments

Changes in V2:
- support of multiple rings per device
- xenlogd->xen-9pfsd rename
- addressed review comments
- fixed some bugs

Juergen Gross (32):
tools: add access macros for unaligned data
tools: add a new xen logging daemon
tools/xen-9pfsd: connect to frontend
tools/xen-9pfsd: add transport layer
tools/xen-9pfsd: add 9pfs response generation support tools/xen-9pfsd: add 9pfs version request support tools/xen-9pfsd: add 9pfs attach request support tools/xen-9pfsd: add 9pfs walk request support tools/xen-9pfsd: add 9pfs open request support tools/xen-9pfsd: add 9pfs clunk request support tools/xen-9pfsd: add 9pfs create request support tools/xen-9pfsd: add 9pfs stat request support tools/xen-9pfsd: add 9pfs write request support tools/xen-9pfsd: add 9pfs read request support tools/libs/light: add backend type for 9pfs PV devices tools/xl: support new 9pfs backend xen_9pfsd tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
stubdom: extend xenstore stubdom configs
tools: add 9pfs device to xenstore-stubdom tools/xenstored: add early_init() function tools/xenstored: move systemd handling to posix.c tools/xenstored: move all log-pipe handling into posix.c tools/xenstored: move all socket handling into posix.c

Quoted 8 lines

tools/xenstored: get own domid in stubdom case tools/xenstored: rework ring page (un)map functions tools/xenstored: split domain_init() tools/xenstored: map stubdom interface tools/xenstored: mount 9pfs device in stubdom tools/xenstored: add helpers for filename handling tools/xenstored: support complete log capabilities in stubdom tools/xenstored: have a single do_control_memreport()

I haven't checked what's the state of the 9PFS patches. Can part of the xenstored changes be committed without the 9PFS changes?

Cheers,

Signature · 1 line
Julien Grall
#23 lore raw
Quoted 78 lines · Julien Grall

Hi Juergen,

Quoted 66 lines · Juergen Gross

This series is adding 9pfs support to Xenstore-stubdom, enabling it to do logging to a dom0 directory.

This is a prerequisite for the final goal to add live update support to Xenstore-stubdom, as it enables the stubdom to store its state in a dom0 file.

The 9pfs backend is a new daemon written from scratch. Using a dedicated 9pfs daemon has several advantages:

- it is using much less resources than a full blown qemu process
- it can serve multiple guests (the idea is to use it for other infrastructure domains, like qemu-stubdom or driver domains, too)
- it is designed to support several security enhancements, like limiting the number of files for a guest, or limiting the allocated file system space
- it doesn't support file links (neither hard nor soft links) or referencing parent directories via "..", minimizing the risk that a guest can "escape" from its home directory

Note that for now the daemon only contains the minimal needed functionality to do logging from Xenstore-stubdom. I didn't want to add all the 9pfs commands and security add-ons in the beginning, in order to avoid needless efforts in case the idea of the daemon is being rejected.

Changes in V4:
- patch 2 of V3 was applied
- added support of reading directories
- addressed review comments

Changes in V3:
- new patches 1, 23-25
- addressed review comments

Changes in V2:
- support of multiple rings per device
- xenlogd->xen-9pfsd rename
- addressed review comments
- fixed some bugs

Juergen Gross (32):
   tools: add access macros for unaligned data
   tools: add a new xen logging daemon
   tools/xen-9pfsd: connect to frontend
   tools/xen-9pfsd: add transport layer
   tools/xen-9pfsd: add 9pfs response generation support tools/xen-9pfsd: add 9pfs version request support tools/xen-9pfsd: add 9pfs attach request support tools/xen-9pfsd: add 9pfs walk request support tools/xen-9pfsd: add 9pfs open request support tools/xen-9pfsd: add 9pfs clunk request support tools/xen-9pfsd: add 9pfs create request support tools/xen-9pfsd: add 9pfs stat request support tools/xen-9pfsd: add 9pfs write request support tools/xen-9pfsd: add 9pfs read request support tools/libs/light: add backend type for 9pfs PV devices tools/xl: support new 9pfs backend xen_9pfsd tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
   stubdom: extend xenstore stubdom configs
   tools: add 9pfs device to xenstore-stubdom tools/xenstored: add early_init() function tools/xenstored: move systemd handling to posix.c tools/xenstored: move all log-pipe handling into posix.c tools/xenstored: move all socket handling into posix.c

Quoted 8 lines

   tools/xenstored: get own domid in stubdom case tools/xenstored: rework ring page (un)map functions tools/xenstored: split domain_init() tools/xenstored: map stubdom interface tools/xenstored: mount 9pfs device in stubdom tools/xenstored: add helpers for filename handling tools/xenstored: support complete log capabilities in stubdom tools/xenstored: have a single do_control_memreport()

Quoted 1 line

I haven't checked what's the state of the 9PFS patches. Can part of the xenstored changes be committed without the 9PFS changes?

The following patches can go in without the 9pfs daemon:

tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
stubdom: extend xenstore stubdom configs tools/xenstored: add early_init() function tools/xenstored: move systemd handling to posix.c tools/xenstored: move all log-pipe handling into posix.c tools/xenstored: move all socket handling into posix.c tools/xenstored: get own domid in stubdom case tools/xenstored: rework ring page (un)map functions tools/xenstored: split domain_init()
tools/xenstored: map stubdom interface

Juergen

#24 lore raw

Hi Juergen,

Quoted 79 lines · Jürgen Groß
Quoted 78 lines · Julien Grall

Hi Juergen,

Quoted 74 lines · Juergen Gross

This series is adding 9pfs support to Xenstore-stubdom, enabling it to do logging to a dom0 directory.

This is a prerequisite for the final goal to add live update support to Xenstore-stubdom, as it enables the stubdom to store its state in a dom0 file.

The 9pfs backend is a new daemon written from scratch. Using a dedicated 9pfs daemon has several advantages:

- it is using much less resources than a full blown qemu process
- it can serve multiple guests (the idea is to use it for other infrastructure domains, like qemu-stubdom or driver domains, too)
- it is designed to support several security enhancements, like limiting the number of files for a guest, or limiting the allocated file system space
- it doesn't support file links (neither hard nor soft links) or referencing parent directories via "..", minimizing the risk that a guest can "escape" from its home directory

Note that for now the daemon only contains the minimal needed functionality to do logging from Xenstore-stubdom. I didn't want to add all the 9pfs commands and security add-ons in the beginning, in order to avoid needless efforts in case the idea of the daemon is being rejected.

Changes in V4:
- patch 2 of V3 was applied
- added support of reading directories
- addressed review comments

Changes in V3:
- new patches 1, 23-25
- addressed review comments

Changes in V2:
- support of multiple rings per device
- xenlogd->xen-9pfsd rename
- addressed review comments
- fixed some bugs

Juergen Gross (32):
   tools: add access macros for unaligned data
   tools: add a new xen logging daemon
   tools/xen-9pfsd: connect to frontend
   tools/xen-9pfsd: add transport layer
   tools/xen-9pfsd: add 9pfs response generation support tools/xen-9pfsd: add 9pfs version request support tools/xen-9pfsd: add 9pfs attach request support tools/xen-9pfsd: add 9pfs walk request support tools/xen-9pfsd: add 9pfs open request support tools/xen-9pfsd: add 9pfs clunk request support tools/xen-9pfsd: add 9pfs create request support tools/xen-9pfsd: add 9pfs stat request support tools/xen-9pfsd: add 9pfs write request support tools/xen-9pfsd: add 9pfs read request support tools/libs/light: add backend type for 9pfs PV devices tools/xl: support new 9pfs backend xen_9pfsd tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
   stubdom: extend xenstore stubdom configs
   tools: add 9pfs device to xenstore-stubdom tools/xenstored: add early_init() function tools/xenstored: move systemd handling to posix.c tools/xenstored: move all log-pipe handling into posix.c tools/xenstored: move all socket handling into posix.c tools/xenstored: get own domid in stubdom case tools/xenstored: rework ring page (un)map functions tools/xenstored: split domain_init()
   tools/xenstored: map stubdom interface
   tools/xenstored: mount 9pfs device in stubdom tools/xenstored: add helpers for filename handling tools/xenstored: support complete log capabilities in stubdom tools/xenstored: have a single do_control_memreport()

Quoted 3 lines
Quoted 1 line

I haven't checked what's the state of the 9PFS patches. Can part of the xenstored changes be committed without the 9PFS changes?

The following patches can go in without the 9pfs daemon:

It looks like the gitalb CI is not happy with the following patches [1]:

In function ‘free_stat’,
inlined from ‘write_9pfs’ at 9pfront.c:935:9:
9pfront.c:120:14: error: ‘stat.name’ may be used uninitialized [-Werror=maybe-uninitialized]

  120 |     free(stat->name);
      |          ~~~~^~~~~~

9pfront.c: In function ‘write_9pfs’:
9pfront.c:929:20: note: ‘stat’ declared here
929 | struct p9_stat stat;
| ^~~~

I think...

Quoted 4 lines

tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
stubdom: extend xenstore stubdom configs

.. this is related to this patch. Can you have a look?

I have just pushed a new branch without this patch. Let see if the CI [2] will pass this time.

Quoted 8 lines

tools/xenstored: add early_init() function tools/xenstored: move systemd handling to posix.c tools/xenstored: move all log-pipe handling into posix.c tools/xenstored: move all socket handling into posix.c tools/xenstored: get own domid in stubdom case tools/xenstored: rework ring page (un)map functions tools/xenstored: split domain_init() tools/xenstored: map stubdom interface

Cheers,

[1] https://gitlab.com/xen-project/people/julieng/xen/-/pipelines/1165147815
[2] https://gitlab.com/xen-project/people/julieng/xen/-/pipelines/1165166977

Signature · 1 line
Julien Grall
#25 lore raw
Quoted 101 lines · Julien Grall

Hi Juergen,

Quoted 79 lines · Jürgen Groß
Quoted 78 lines · Julien Grall

Hi Juergen,

Quoted 74 lines · Juergen Gross

This series is adding 9pfs support to Xenstore-stubdom, enabling it to do logging to a dom0 directory.

This is a prerequisite for the final goal to add live update support to Xenstore-stubdom, as it enables the stubdom to store its state in a dom0 file.

The 9pfs backend is a new daemon written from scratch. Using a dedicated 9pfs daemon has several advantages:

- it is using much less resources than a full blown qemu process
- it can serve multiple guests (the idea is to use it for other infrastructure domains, like qemu-stubdom or driver domains, too)
- it is designed to support several security enhancements, like limiting the number of files for a guest, or limiting the allocated file system space
- it doesn't support file links (neither hard nor soft links) or referencing parent directories via "..", minimizing the risk that a guest can "escape" from its home directory

Note that for now the daemon only contains the minimal needed functionality to do logging from Xenstore-stubdom. I didn't want to add all the 9pfs commands and security add-ons in the beginning, in order to avoid needless efforts in case the idea of the daemon is being rejected.

Changes in V4:
- patch 2 of V3 was applied
- added support of reading directories
- addressed review comments

Changes in V3:
- new patches 1, 23-25
- addressed review comments

Changes in V2:
- support of multiple rings per device
- xenlogd->xen-9pfsd rename
- addressed review comments
- fixed some bugs

Juergen Gross (32):
   tools: add access macros for unaligned data
   tools: add a new xen logging daemon
   tools/xen-9pfsd: connect to frontend
   tools/xen-9pfsd: add transport layer
   tools/xen-9pfsd: add 9pfs response generation support tools/xen-9pfsd: add 9pfs version request support tools/xen-9pfsd: add 9pfs attach request support tools/xen-9pfsd: add 9pfs walk request support tools/xen-9pfsd: add 9pfs open request support tools/xen-9pfsd: add 9pfs clunk request support tools/xen-9pfsd: add 9pfs create request support tools/xen-9pfsd: add 9pfs stat request support tools/xen-9pfsd: add 9pfs write request support tools/xen-9pfsd: add 9pfs read request support tools/libs/light: add backend type for 9pfs PV devices tools/xl: support new 9pfs backend xen_9pfsd tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
   stubdom: extend xenstore stubdom configs
   tools: add 9pfs device to xenstore-stubdom tools/xenstored: add early_init() function tools/xenstored: move systemd handling to posix.c tools/xenstored: move all log-pipe handling into posix.c tools/xenstored: move all socket handling into posix.c tools/xenstored: get own domid in stubdom case tools/xenstored: rework ring page (un)map functions tools/xenstored: split domain_init()
   tools/xenstored: map stubdom interface
   tools/xenstored: mount 9pfs device in stubdom tools/xenstored: add helpers for filename handling tools/xenstored: support complete log capabilities in stubdom tools/xenstored: have a single do_control_memreport()

Quoted 3 lines
Quoted 1 line

I haven't checked what's the state of the 9PFS patches. Can part of the xenstored changes be committed without the 9PFS changes?

The following patches can go in without the 9pfs daemon:

It looks like the gitalb CI is not happy with the following patches [1]:

In function ‘free_stat’,
    inlined from ‘write_9pfs’ at 9pfront.c:935:9:
9pfront.c:120:14: error: ‘stat.name’ may be used uninitialized [-Werror=maybe-uninitialized]
  120 |     free(stat->name);
      |          ~~~~^~~~~~
9pfront.c: In function ‘write_9pfs’:
9pfront.c:929:20: note: ‘stat’ declared here
  929 |     struct p9_stat stat;
      |                    ^~~~

I think...

Quoted 1 line
Quoted 7 lines
Quoted 3 lines

tools/helpers: allocate xenstore event channel for xenstore stubdom tools/xenstored: rename xenbus_evtchn()
stubdom: extend xenstore stubdom configs

.. this is related to this patch. Can you have a look?

I have just pushed a new branch without this patch. Let see if the CI [2] will pass this time.

It passed. So I committed all the patches you mentionned but "stubdom: extend xenstore stubdom configs".

Cheers,

Signature · 1 line
Julien Grall
#26 lore raw

PATCH v4 13/32 tools/xen-9pfsd: add 9pfs write request support

In reply to Juergen Gross

Add the write request of the 9pfs protocol.

---
 tools/xen-9pfsd/io.c | 54 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 54 insertions(+)
tools/xen-9pfsd/io.c +54 -0
index 031cff9f0e..b763e3d8d9 100644
@@ -33,6 +33,7 @@
 #define P9_CMD_WALK       110
 #define P9_CMD_OPEN       112
 #define P9_CMD_CREATE     114
+#define P9_CMD_WRITE      118
 #define P9_CMD_CLUNK      120
 #define P9_CMD_STAT       124
 
@@ -1246,6 +1247,55 @@ static void p9_stat(struct ring *ring, struct p9_header *hdr)
     free_fid(device, fidp);
 }
 
+static void p9_write(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    uint64_t off;
+    unsigned int len;
+    uint32_t written;
+    void *buf;
+    struct p9_fid *fidp;
+    int ret;
+
+    ret = fill_data(ring, "ULD", &fid, &off, &len, ring->buffer);
+    if ( ret != 3 )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+
+    fidp = get_fid_ref(device, fid);
+    if ( !fidp || !fidp->opened || fidp->isdir )
+    {
+        p9_error(ring, hdr->tag, EBADF);
+        goto out;
+    }
+
+    buf = ring->buffer;
+
+    while ( len != 0 )
+    {
+        ret = pwrite(fidp->fd, buf, len, off);
+        if ( ret < 0 )
+            break;
+        len -= ret;
+        buf += ret;
+        off += ret;
+    }
+
+    written = buf - ring->buffer;
+    if ( written == 0 )
+    {
+        p9_error(ring, hdr->tag, errno);
+        goto out;
+    }
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "U", &written);
+
+ out:
+    free_fid(device, fidp);
+}
+
 void *io_thread(void *arg)
 {
     struct ring *ring = arg;
@@ -1321,6 +1371,10 @@ void *io_thread(void *arg)
                 p9_create(ring, &hdr);
                 break;
 
+            case P9_CMD_WRITE:
+                p9_write(ring, &hdr);
+                break;
+
             case P9_CMD_CLUNK:
                 p9_clunk(ring, &hdr);
                 break;
Signature · 1 line
2.35.3
#27 lore raw

PATCH v4 14/32 tools/xen-9pfsd: add 9pfs read request support

In reply to Juergen Gross

Add the read request of the 9pfs protocol.

---
V2:
- make error check more readable (Jason Andryuk)
V4:
- add directory read support

---
 tools/xen-9pfsd/io.c | 90 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 90 insertions(+)
tools/xen-9pfsd/io.c +90 -0
index b763e3d8d9..cfbf3bef59 100644
@@ -33,6 +33,7 @@
 #define P9_CMD_WALK       110
 #define P9_CMD_OPEN       112
 #define P9_CMD_CREATE     114
+#define P9_CMD_READ       116
 #define P9_CMD_WRITE      118
 #define P9_CMD_CLUNK      120
 #define P9_CMD_STAT       124
@@ -1247,6 +1248,91 @@ static void p9_stat(struct ring *ring, struct p9_header *hdr)
     free_fid(device, fidp);
 }
 
+static void p9_read(struct ring *ring, struct p9_header *hdr)
+{
+    device *device = ring->device;
+    uint32_t fid;
+    uint64_t off;
+    unsigned int len;
+    uint32_t count;
+    void *buf;
+    struct p9_fid *fidp;
+    int ret;
+
+    ret = fill_data(ring, "ULU", &fid, &off, &count);
+    if ( ret != 3 )
+    {
+        p9_error(ring, hdr->tag, EINVAL);
+        return;
+    }
+
+    fidp = get_fid_ref(device, fid);
+    if ( !fidp || !fidp->opened )
+    {
+        errno = EBADF;
+        goto err;
+    }
+
+    len = count;
+    buf = ring->buffer + sizeof(*hdr) + sizeof(uint32_t);
+
+    if ( fidp->isdir )
+    {
+        struct dirent *dirent;
+        struct stat st;
+        struct p9_stat p9s;
+
+        while ( len != 0 )
+        {
+            errno = 0;
+            dirent = readdir(fidp->data);
+            if ( !dirent )
+            {
+                if ( errno )
+                    goto err;
+                break;
+            }
+            if ( fstatat(fidp->fd, dirent->d_name, &st, 0) < 0 )
+                goto err;
+            fill_p9_stat(device, &p9s, &st, dirent->d_name);
+            if ( p9s.size + sizeof(p9s.size) > len )
+            {
+                seekdir(fidp->data, dirent->d_off);
+                break;
+            }
+            fill_buffer_at(&buf, "s", &p9s);
+            len -= p9s.size + sizeof(p9s.size);
+        }
+    }
+    else
+    {
+        while ( len != 0 )
+        {
+            ret = pread(fidp->fd, buf, len, off);
+            if ( ret <= 0 )
+                break;
+            len -= ret;
+            buf += ret;
+            off += ret;
+        }
+        if ( ret < 0 && len == count )
+            goto err;
+    }
+
+    buf = ring->buffer + sizeof(*hdr) + sizeof(uint32_t);
+    len = count - len;
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "D", &len, buf);
+
+ out:
+    free_fid(device, fidp);
+
+    return;
+
+ err:
+    p9_error(ring, hdr->tag, errno);
+    goto out;
+}
+
 static void p9_write(struct ring *ring, struct p9_header *hdr)
 {
     device *device = ring->device;
@@ -1371,6 +1457,10 @@ void *io_thread(void *arg)
                 p9_create(ring, &hdr);
                 break;
 
+            case P9_CMD_READ:
+                p9_read(ring, &hdr);
+                break;
+
             case P9_CMD_WRITE:
                 p9_write(ring, &hdr);
                 break;
Signature · 1 line
2.35.3
#28 lore raw

Re: [PATCH v4 14/32] tools/xen-9pfsd: add 9pfs read request support

Quoted 20 lines · Juergen Gross

Add the read request of the 9pfs protocol.

---
V2:
- make error check more readable (Jason Andryuk)
V4:
- add directory read support

---
 tools/xen-9pfsd/io.c | 90 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 90 insertions(+)
tools/xen-9pfsd/io.c +0 -0
index b763e3d8d9..cfbf3bef59 100644
 

tools/xen-9pfsd/io.c static void p9_stat(struct ring *ring, struct p9_header *hdr) · line 1284

Quoted 10 lines
tools/xen-9pfsd/io.c +10 -0
+
+    len = count;
+    buf = ring->buffer + sizeof(*hdr) + sizeof(uint32_t);
+
+    if ( fidp->isdir )
+    {
+        struct dirent *dirent;
+        struct stat st;
+        struct p9_stat p9s;
+

"""
For directories, read returns an integral number of direc- tory entries exactly as in stat (see stat(5)), one for each member of the directory. The read request message must have offset equal to zero or the value of offset in the previous read on the directory, plus the number of bytes returned in the previous read. In other words, seeking other than to the beginning is illegal in a directory (see seek(2)). """

I think you need to check off. Looks like QEMU only checks for off == 0 and rewinds in that case. QEMU ignores other values.

Regards,
Jason

Quoted 51 lines
tools/xen-9pfsd/io.c +51 -0
+        while ( len != 0 )
+        {
+            errno = 0;
+            dirent = readdir(fidp->data);
+            if ( !dirent )
+            {
+                if ( errno )
+                    goto err;
+                break;
+            }
+            if ( fstatat(fidp->fd, dirent->d_name, &st, 0) < 0 )
+                goto err;
+            fill_p9_stat(device, &p9s, &st, dirent->d_name);
+            if ( p9s.size + sizeof(p9s.size) > len )
+            {
+                seekdir(fidp->data, dirent->d_off);
+                break;
+            }
+            fill_buffer_at(&buf, "s", &p9s);
+            len -= p9s.size + sizeof(p9s.size);
+        }
+    }
+    else
+    {
+        while ( len != 0 )
+        {
+            ret = pread(fidp->fd, buf, len, off);
+            if ( ret <= 0 )
+                break;
+            len -= ret;
+            buf += ret;
+            off += ret;
+        }
+        if ( ret < 0 && len == count )
+            goto err;
+    }
+
+    buf = ring->buffer + sizeof(*hdr) + sizeof(uint32_t);
+    len = count - len;
+    fill_buffer(ring, hdr->cmd + 1, hdr->tag, "D", &len, buf);
+
+ out:
+    free_fid(device, fidp);
+
+    return;
+
+ err:
+    p9_error(ring, hdr->tag, errno);
+    goto out;
+}
+
#29 lore raw

Re: [PATCH v4 14/32] tools/xen-9pfsd: add 9pfs read request support

Quoted 41 lines · Jason Andryuk
Quoted 20 lines · Juergen Gross

Add the read request of the 9pfs protocol.

---
V2:
- make error check more readable (Jason Andryuk)
V4:
- add directory read support

---
  tools/xen-9pfsd/io.c | 90 ++++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 90 insertions(+)
tools/xen-9pfsd/io.c +0 -0
index b763e3d8d9..cfbf3bef59 100644
 

tools/xen-9pfsd/io.c static void p9_stat(struct ring *ring, struct p9_header *hdr) · line 1284

Quoted 10 lines
tools/xen-9pfsd/io.c +10 -0
+
+    len = count;
+    buf = ring->buffer + sizeof(*hdr) + sizeof(uint32_t);
+
+    if ( fidp->isdir )
+    {
+        struct dirent *dirent;
+        struct stat st;
+        struct p9_stat p9s;
+

"""
For directories, read returns an integral number of direc- tory entries exactly as in stat (see stat(5)), one for each member of the directory. The read request message must have offset equal to zero or the value of offset in the previous read on the directory, plus the number of bytes returned in the previous read. In other words, seeking other than to the beginning is illegal in a directory (see seek(2)). """

Quoted 2 lines

I think you need to check off. Looks like QEMU only checks for off == 0 and rewinds in that case. QEMU ignores other values.

Oh, indeed. Thanks for noticing. I'll use the same approach as qemu.

Juergen

#30 lore raw

PATCH v4 15/32 tools/libs/light: add backend type for 9pfs PV devices

In reply to Juergen Gross

Make the backend type of 9pfs PV devices configurable. The default is "qemu" with the related Xenstore backend-side directory being "9pfs".

Add another type "xen_9pfsd" with the related Xenstore backend-side directory "xen_9pfs".

As additional security features it is possible to specify:
- "max-space" for limiting the maximum space consumed on the filesystem in MBs
- "max-files" for limiting the maximum number of files in the filesystem
- "max-open-files" for limiting the maximum number of concurrent open files

For convenience "auto-delete" is available to let the backend delete the oldest file of the guest in case otherwise "max-space" or "max-files" would be violated.

The xen-9pfsd daemon will be started by libxenlight automatically when the first "xen_9pfs" device is being created.

---
V3:
- regenerate go bindings
V4:
- rename libxl_device_p9_dm_needed() to libxl__device_p9_dm_needed() (Anthony Perard)
- reorder span related functions (Anthony Perard)
- add comment for xen9pfsd_spawn() return values (Anthony Perard)
- add LIBXL_HAVE_XEN_9PFS to libxl.h (Anthony Perard)
- use a copy of 'p9' in xen9pfsd_spawn() (Anthony Perard)

---
 tools/golang/xenlight/helpers.gen.go      |  16 +++
 tools/golang/xenlight/types.gen.go        |  13 ++
 tools/include/libxl.h                     |   7 +
 tools/libs/light/libxl_9pfs.c             | 159 +++++++++++++++++++++-
 tools/libs/light/libxl_create.c           |   4 +-
 tools/libs/light/libxl_dm.c               |   2 +-
 tools/libs/light/libxl_types.idl          |  11 ++
 tools/libs/light/libxl_types_internal.idl |   1 +
 8 files changed, 206 insertions(+), 7 deletions(-)
tools/golang/xenlight/helpers.gen.go +16 -0
index 35e209ff1b..8f44397a4e 100644
@@ -1280,6 +1280,9 @@ return fmt.Errorf("converting field Rdm: %v", err)
 }
 x.RdmMemBoundaryMemkb = uint64(tmp.rdm_mem_boundary_memkb)
 x.McaCaps = uint64(tmp.mca_caps)
+if err := x.Pirq.fromC(&tmp.pirq);err != nil {
+return fmt.Errorf("converting field Pirq: %v", err)
+}
 return nil
 }
 
@@ -1613,6 +1616,9 @@ return fmt.Errorf("converting field Rdm: %v", err)
 }
 hvm.rdm_mem_boundary_memkb = C.uint64_t(tmp.RdmMemBoundaryMemkb)
 hvm.mca_caps = C.uint64_t(tmp.McaCaps)
+if err := tmp.Pirq.toC(&hvm.pirq); err != nil {
+return fmt.Errorf("converting field Pirq: %v", err)
+}
 hvmBytes := C.GoBytes(unsafe.Pointer(&hvm),C.sizeof_libxl_domain_build_info_type_union_hvm)
 copy(xc.u[:],hvmBytes)
 case DomainTypePv:
@@ -2434,6 +2440,11 @@ x.Tag = C.GoString(xc.tag)
 x.Path = C.GoString(xc.path)
 x.SecurityModel = C.GoString(xc.security_model)
 x.Devid = Devid(xc.devid)
+x.Type = P9Type(xc._type)
+x.MaxSpace = int(xc.max_space)
+x.MaxFiles = int(xc.max_files)
+x.MaxOpenFiles = int(xc.max_open_files)
+x.AutoDelete = bool(xc.auto_delete)
 
  return nil}
 
@@ -2452,6 +2463,11 @@ xc.path = C.CString(x.Path)}
 if x.SecurityModel != "" {
 xc.security_model = C.CString(x.SecurityModel)}
 xc.devid = C.libxl_devid(x.Devid)
+xc._type = C.libxl_p9_type(x.Type)
+xc.max_space = C.int(x.MaxSpace)
+xc.max_files = C.int(x.MaxFiles)
+xc.max_open_files = C.int(x.MaxOpenFiles)
+xc.auto_delete = C.bool(x.AutoDelete)
 
  return nil
  }
tools/golang/xenlight/types.gen.go +13 -0
index 7907aa8999..d31722407a 100644
@@ -122,6 +122,13 @@ NicTypeVifIoemu NicType = 1
 NicTypeVif NicType = 2
 )
 
+type P9Type int
+const(
+P9TypeUnknown P9Type = 0
+P9TypeQemu P9Type = 1
+P9TypeXen9Pfsd P9Type = 2
+)
+
 type ActionOnShutdown int
 const(
 ActionOnShutdownDestroy ActionOnShutdown = 1
@@ -651,6 +658,7 @@ SerialList StringList
 Rdm RdmReserve
 RdmMemBoundaryMemkb uint64
 McaCaps uint64
+Pirq Defbool
 }
 
 func (x DomainBuildInfoTypeUnionHvm) isDomainBuildInfoTypeUnion(){}
@@ -888,6 +896,11 @@ Tag string
 Path string
 SecurityModel string
 Devid Devid
+Type P9Type
+MaxSpace int
+MaxFiles int
+MaxOpenFiles int
+AutoDelete bool
 }
 
 type DevicePvcallsif struct {
tools/include/libxl.h +7 -0
index f1652b1664..a554f2ccd6 100644
@@ -615,6 +615,13 @@
  */
 #define LIBXL_HAVE_HVM_PIRQ 1
 
+/*
+ * LIBXL_HAVE_XEN_9PFS indicates the presence of the xen-9pfsd related
+ * fields in libxl_device_p9: type, max_space, max_files, max_open_files and
+ * auto_delete.
+ */
+#define LIBXL_HAVE_XEN_9PFS 1
+
 /*
  * libxl memory management
  *
tools/libs/light/libxl_9pfs.c +156 -3

176 lines not on this page · raw message

tools/libs/light/libxl_create.c +1 -3
index 0008fac607..5546335973 100644
@@ -1761,9 +1761,6 @@ static void domcreate_launch_dm(libxl__egc *egc, libxl__multidev *multidev,
         libxl__device_console_dispose(&console);
     }
 
-    for (i = 0; i < d_config->num_p9s; i++)
-        libxl__device_add(gc, domid, &libxl__p9_devtype, &d_config->p9s[i]);
-
     for (i = 0; i < d_config->num_pvcallsifs; i++)
         libxl__device_add(gc, domid, &libxl__pvcallsif_devtype,
                           &d_config->pvcallsifs[i]);
@@ -1900,6 +1897,7 @@ const libxl__device_type *device_type_tbl[] = {
     &libxl__vdispl_devtype,
     &libxl__vsnd_devtype,
     &libxl__virtio_devtype,
+    &libxl__p9_devtype,
     NULL
 };
 
tools/libs/light/libxl_dm.c +1 -1
index 14b593110f..2aaaeb5aa7 100644
@@ -3761,7 +3761,7 @@ int libxl__need_xenpv_qemu(libxl__gc *gc, libxl_domain_config *d_config)
         goto out;
     }
 
-    if (d_config->num_vfbs > 0 || d_config->num_p9s > 0) {
+    if (d_config->num_vfbs > 0) {
         ret = 1;
         goto out;
     }
tools/libs/light/libxl_types.idl +11 -0
index 899ad30969..682092a058 100644
@@ -150,6 +150,12 @@ libxl_nic_type = Enumeration("nic_type", [
     (2, "VIF"),
     ])
 
+libxl_p9_type = Enumeration("p9_type", [
+    (0, "unknown"),
+    (1, "qemu"),
+    (2, "xen_9pfsd"),
+    ])
+
 libxl_action_on_shutdown = Enumeration("action_on_shutdown", [
     (1, "DESTROY"),
 
@@ -943,6 +949,11 @@ libxl_device_p9 = Struct("device_p9", [
     ("path",             string),
     ("security_model",   string),
     ("devid",            libxl_devid),
+    ("type",             libxl_p9_type),
+    ("max_space",        integer),
+    ("max_files",        integer),
+    ("max_open_files",   integer),
+    ("auto_delete",      bool),
 ])
 
 libxl_device_pvcallsif = Struct("device_pvcallsif", [
tools/libs/light/libxl_types_internal.idl +1 -0
index e24288f1a5..39da71cef5 100644
@@ -34,6 +34,7 @@ libxl__device_kind = Enumeration("device_kind", [
     (16, "VINPUT"),
     (17, "VIRTIO_DISK"),
     (18, "VIRTIO"),
+    (19, "XEN_9PFS"),
     ])
 
 libxl__console_backend = Enumeration("console_backend", [
Signature · 1 line
2.35.3
#31 lore raw

PATCH v4 16/32 tools/xl: support new 9pfs backend xen_9pfsd

In reply to Juergen Gross

Add support for the new 9pfs backend "xen_9pfsd". For this backend type the tag defaults to "Xen" and the host side path to "/var/log/xen/guests/<dom-name>".

Do most of the default settings in libxl. Unfortunately the default path can't easily be set in libxl, as the domain name isn't available in the related 9pfs specific function.

Settings the defaults in libxl requires to move the sanity checking of 9pfs parameters from xl to libxl, too.

---
V2:
- test max_files and max_open_files, too (Jason Andryuk) V4:
- fix man page to use the "xen_9pfsd" type due to idl limitation (Jason Andryuk)
- set (most of) the defaults in libxl (Anthony Perard)

---
 docs/man/xl.cfg.5.pod.in      | 36 +++++++++++++++++++++++++++++++++--
 tools/libs/light/libxl_9pfs.c | 18 ++++++++++++++++++
 tools/xl/xl_parse.c           | 23 +++++++++++++++++++---
 3 files changed, 72 insertions(+), 5 deletions(-)
docs/man/xl.cfg.5.pod.in +34 -2
index ea8d41727d..039e057318 100644
@@ -772,10 +772,16 @@ settings, from the following list:
 
 =over 4
 
+=item B<type=TYPE>
+
+The backendtype for the PV device. Supported values are B<qemu> and
+B<xen_9pfsd>.  The default is B<qemu>.
+
 =item B<tag=STRING>
 
 9pfs tag to identify the filesystem share. The tag is needed on the
-guest side to mount it.
+guest side to mount it. For the backendtype of B<xen_9pfsd> the tag defaults to
+"Xen".
 
 =item B<security_model="none">
 
@@ -785,12 +791,38 @@ squash or remap).
 
 =item B<path=STRING>
 
-Filesystem path on the backend to export.
+Filesystem path on the backend to export. For the backendtype of B<xen_9pfsd>
+the path defaults to "@XEN_LOG_DIR@/guests/<guest-name>".
 
 =item B<backend=domain-id>
 
 Specify the backend domain name or id, defaults to dom0.
 
+=item B<max-files=NUMBER>
+
+Specify the maximum number of files below B<path>. A value of 0 (which
+is the default) doesn't limit the number of files. Only valid for
+B<type=xen_9pfsd>.
+
+=item B<max-open-files=NUMBER>
+
+Specify the maximum number of concurrently opened files below B<path>.
+Multiple opens of the same file are counted individually. Only valid for
+B<type=xen_9pfsd>, which has a default of B<max-open-files=5>.
+
+=item B<max-space=NUMBER>
+
+Specify the maximum used disk space in MiB below B<path>. A value of 0 (which
+is the default) doesn't limit the usable disk space. Only valid for
+B<type=xen_9pfsd>.
+
+=item B<auto-delete=BOOLEAN>
+
+When set the backend will delete the oldest file which is currently not
+opened by the guest in case the disk space limit set via B<max-space> or the
+file limit set via B<max-files> is being reached. Only valid for
+B<type=xen_9pfsd>.
+
 =back
 
 =item B<pvcalls=[ "backend=domain-id", ... ]>
tools/libs/light/libxl_9pfs.c +18 -0
index 68fa9947ad..7593686a90 100644
@@ -20,6 +20,24 @@
 static int libxl__device_p9_setdefault(libxl__gc *gc, uint32_t domid,
                                        libxl_device_p9 *p9, bool hotplug)
 {
+    if (p9->type == LIBXL_P9_TYPE_UNKNOWN) {
+        p9->type = LIBXL_P9_TYPE_QEMU;
+    }
+    if (p9->type == LIBXL_P9_TYPE_QEMU &&
+        (p9->max_files || p9->max_open_files || p9->max_space ||
+         p9->auto_delete)) {
+        LOGD(ERROR, domid, "Illegal 9pfs parameter combination");
+        return ERROR_INVAL;
+    }
+    if (p9->type == LIBXL_P9_TYPE_XEN_9PFSD && !p9->tag) {
+        p9->tag = libxl__strdup(NOGC, "Xen");
+    }
+
+    if (!p9->path || !p9->security_model || !p9->tag) {
+        LOGD(ERROR, domid, "9pfs spec missing required field!");
+        return ERROR_INVAL;
+    }
+
     return libxl__resolve_domid(gc, p9->backend_domname, &p9->backend_domid);
 }
 
tools/xl/xl_parse.c +20 -3
index 9b358f11b8..80ffe85f5e 100644
@@ -2233,6 +2233,20 @@ void parse_config_data(const char *config_source,
                     replace_string(&p9->tag, value);
                 } else if (!strcmp(key, "backend")) {
                     replace_string(&p9->backend_domname, value);
+                } else if (!strcmp(key, "type")) {
+                    if (libxl_p9_type_from_string(value, &p9->type)) {
+                        fprintf(stderr, "failed to parse 9pfs type: %s\n",
+                                value);
+                        exit(1);
+                    }
+                } else if (!strcmp(key, "max-files")) {
+                    p9->max_files = parse_ulong(value);
+                } else if (!strcmp(key, "max-open-files")) {
+                    p9->max_open_files = parse_ulong(value);
+                } else if (!strcmp(key, "max-space")) {
+                    p9->max_space = parse_ulong(value);
+                } else if (!strcmp(key, "auto-delete")) {
+                    p9->auto_delete = strtoul(value, NULL, 0);
                 } else {
                     fprintf(stderr, "Unknown 9pfs parameter '%s'\n", key);
                     exit(1);
@@ -2243,9 +2257,12 @@ void parse_config_data(const char *config_source,
 
             libxl_string_list_dispose(&pairs);
 
-            if (!p9->path || !p9->security_model || !p9->tag) {
-                fprintf(stderr, "9pfs spec missing required field!\n");
-                exit(1);
+            if (p9->type == LIBXL_P9_TYPE_XEN_9PFSD && !p9->path) {
+                char *path;
+
+                xasprintf(&path, XEN_LOG_DIR "/guests/%s", c_info->name);
+                replace_string(&p9->path, path);
+                free(path);
             }
         }
     }
Signature · 1 line
2.35.3
#32 lore raw

PATCH v4 17/32 tools/helpers: allocate xenstore event channel for xenstore stubdom

In reply to Juergen Gross

In order to prepare support of PV frontends in xenstore-stubdom, add allocation of a Xenstore event channel to init-xenstore-domain.c.

---
 tools/helpers/init-xenstore-domain.c | 7 +++++++
 1 file changed, 7 insertions(+)
tools/helpers/init-xenstore-domain.c +7 -0
index b2d5df8ba5..140ed610ae 100644
@@ -248,6 +248,13 @@ static int build(xc_interface *xch)
     dom->cmdline = xc_dom_strdup(dom, cmdline);
     dom->xenstore_domid = domid;
     dom->console_evtchn = console_evtchn;
+    rv = xc_evtchn_alloc_unbound(xch, domid, domid);
+    if ( rv < 0 )
+    {
+        fprintf(stderr, "xc_evtchn_alloc_unbound failed\n");
+        goto err;
+    }
+    dom->xenstore_evtchn = rv;
 
     rv = xc_dom_mem_init(dom, memory);
     if ( rv )
Signature · 1 line
2.35.3
#33 lore raw

PATCH v4 18/32 tools/xenstored: rename xenbus_evtchn()

In reply to Juergen Gross

Rename the xenbus_evtchn() function to get_xenbus_evtchn() in order to avoid two externally visible symbols with the same name when Xenstore- stubdom is being built with a Mini-OS with CONFIG_XENBUS set.

---
 tools/xenstored/core.h   | 2 +-
 tools/xenstored/domain.c | 2 +-
 tools/xenstored/minios.c | 2 +-
 tools/xenstored/posix.c  | 2 +-
 4 files changed, 4 insertions(+), 4 deletions(-)
tools/xenstored/core.h +1 -1
index ad87199042..480b0f5f7b 100644
@@ -383,7 +383,7 @@ static inline bool domain_is_unprivileged(const struct connection *conn)
 }
 
 /* Return the event channel used by xenbus. */
-evtchn_port_t xenbus_evtchn(void);
+evtchn_port_t get_xenbus_evtchn(void);
 
 /* Write out the pidfile */
 void write_pidfile(const char *pidfile);
tools/xenstored/domain.c +1 -1
index 409b53acf9..6ef136e01f 100644
@@ -1208,7 +1208,7 @@ void dom0_init(void)
 	evtchn_port_t port;
 	struct domain *dom0;
 
-	port = xenbus_evtchn();
+	port = get_xenbus_evtchn();
 	if (port == -1)
 		barf_perror("Failed to initialize dom0 port");
 
tools/xenstored/minios.c +1 -1
index b5c3a205e6..0779efbf91 100644
@@ -38,7 +38,7 @@ void init_pipe(int reopen_log_pipe[2])
 	reopen_log_pipe[1] = -1;
 }
 
-evtchn_port_t xenbus_evtchn(void)
+evtchn_port_t get_xenbus_evtchn(void)
 {
 	return dom0_event;
 }
tools/xenstored/posix.c +1 -1
index 6ac45fdb45..7e03dd982d 100644
@@ -111,7 +111,7 @@ void unmap_xenbus(void *interface)
 	munmap(interface, getpagesize());
 }
 
-evtchn_port_t xenbus_evtchn(void)
+evtchn_port_t get_xenbus_evtchn(void)
 {
 	int fd;
 	int rc;
Signature · 1 line
2.35.3
#34 lore raw

PATCH v4 19/32 stubdom: extend xenstore stubdom configs

In reply to Juergen Gross

Extend the config files of the Xenstore stubdoms to include XENBUS and 9PFRONT items in order to support file based logging.

---
 stubdom/xenstore-minios.cfg    | 2 +-
 stubdom/xenstorepvh-minios.cfg | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
stubdom/xenstore-minios.cfg +1 -1
index a41704bb6b..239da519b9 100644
@@ -3,7 +3,7 @@ CONFIG_NETFRONT=n
 CONFIG_FBFRONT=n
 CONFIG_KBDFRONT=n
 CONFIG_CONSFRONT=n
-CONFIG_XENBUS=n
 CONFIG_LWIP=n
+CONFIG_9PFRONT=y
 CONFIG_BALLOON=y
 XEN_INTERFACE_VERSION=__XEN_LATEST_INTERFACE_VERSION__
stubdom/xenstorepvh-minios.cfg +1 -1
index 6af51f5753..752b90d7d3 100644
@@ -4,7 +4,7 @@ CONFIG_NETFRONT=n
 CONFIG_FBFRONT=n
 CONFIG_KBDFRONT=n
 CONFIG_CONSFRONT=n
-CONFIG_XENBUS=n
 CONFIG_LWIP=n
+CONFIG_9PFRONT=y
 CONFIG_BALLOON=y
 XEN_INTERFACE_VERSION=__XEN_LATEST_INTERFACE_VERSION__
Signature · 1 line
2.35.3
#35 lore raw

PATCH v4 20/32 tools: add 9pfs device to xenstore-stubdom

In reply to Juergen Gross

Add a 9pfs device to Xenstore stubdom in order to allow it to do e.g. logging into a dom0 file.

Use the following parameters for the new device:

- tag = "Xen"
- type = "xen_9pfsd"
- path = "/var/lib/xen/xenstore"
- security-model = "none"

For now don't limit allowed file space or number of files.

Add a new libxl function for adding it similar to the function for adding the console device.

---
V2:
- add security_model parameter to new libxl function (Jason Andryuk) V4:
- rename function to libxl_device_9pfs_add() (Anthony Perard)
- use a libxl_device_p9 pointer as parameter (Anthony Perard)

---
 tools/helpers/init-xenstore-domain.c |  7 +++++++
 tools/include/libxl.h                | 15 +++++++++++++++
 tools/libs/light/libxl_9pfs.c        | 16 ++++++++++++++++
 3 files changed, 38 insertions(+)
tools/helpers/init-xenstore-domain.c +7 -0
index 140ed610ae..1683438c5c 100644
@@ -433,6 +433,12 @@ int main(int argc, char** argv)
     int rv, fd;
     char *maxmem_str = NULL;
     libxl_ctx *ctx;
+    libxl_device_p9 p9 = { .backend_domid = 0,
+                           .tag = "Xen",
+                           .path = XEN_LIB_DIR"/xenstore",
+                           .security_model = "none",
+                           .type = LIBXL_P9_TYPE_XEN_9PFSD,
+    };
 
     while ( (opt = getopt_long(argc, argv, "v", options, NULL)) != -1 )
     {
@@ -543,6 +549,7 @@ int main(int argc, char** argv)
     }
     libxl_console_add_xenstore(ctx, domid, 0, console_evtchn, console_gfn,
                                NULL);
+    libxl_device_9pfs_add(ctx, domid, &p9, NULL);
     libxl_ctx_free(ctx);
 
     fd = creat(XEN_RUN_DIR "/xenstored.pid", 0666);
tools/include/libxl.h +15 -0
index a554f2ccd6..e6ab5ddb94 100644
@@ -583,6 +583,13 @@
  * libxl_console_add_xenstore() in libxl.
  */
 #define LIBXL_HAVE_CONSOLE_ADD_XENSTORE 1
+
+/*
+ * LIBXL_HAVE_P9_ADD_XENSTORE indicates presence of the function
+ * libxl_device_9pfs_add() in libxl.
+ */
+#define LIBXL_HAVE_P9_ADD_XENSTORE 1
+
 /*
  * libxl ABI compatibility
  *
@@ -2074,6 +2081,14 @@ int libxl_console_add_xenstore(libxl_ctx *ctx, uint32_t domid, uint32_t backend,
                                const libxl_asyncop_how *ao_how)
                                LIBXL_EXTERNAL_CALLERS_ONLY;
 
+/* libxl_device_9pfs_add writes the Xenstore entries for a domain's
+ * primary 9pfs device based on domid, and device parameters.
+ * If needed it will start the backend daemon.
+ */
+int libxl_device_9pfs_add(libxl_ctx *ctx, uint32_t domid, libxl_device_p9 *p9,
+                          const libxl_asyncop_how *ao_how)
+                          LIBXL_EXTERNAL_CALLERS_ONLY;
+
 /* May be called with info_r == NULL to check for domain's existence.
  * Returns ERROR_DOMAIN_NOTFOUND if domain does not exist (used to return
  * ERROR_INVAL for this scenario). */
tools/libs/light/libxl_9pfs.c +16 -0
index 7593686a90..8f5d475322 100644
@@ -208,6 +208,22 @@ static void libxl__device_p9_add(libxl__egc *egc, uint32_t domid,
         aodev->callback(egc, aodev);
 }
 
+int libxl_device_9pfs_add(libxl_ctx *ctx, uint32_t domid, libxl_device_p9 *p9,
+                          const libxl_asyncop_how *ao_how)
+{
+    AO_CREATE(ctx, domid, ao_how);
+    libxl__ao_device *aodev;
+
+    GCNEW(aodev);
+    libxl__prepare_ao_device(ao, aodev);
+    aodev->action = LIBXL__DEVICE_ACTION_ADD;
+    aodev->callback = device_addrm_aocomplete;
+
+    libxl__device_p9_add(egc, domid, p9, aodev);
+
+    return AO_INPROGRESS;
+}
+
 #define libxl_device_p9_list NULL
 #define libxl_device_p9_compare NULL
 
Signature · 1 line
2.35.3
#36 lore raw

PATCH v4 21/32 tools/xenstored: add early_init() function

In reply to Juergen Gross

Some xenstored initialization needs to be done in the daemon case only, so split it out into a new early_init() function being a stub in the stubdom case.

Remove the call of talloc_enable_leak_report_full(), as it serves no real purpose: the daemon only ever exits due to a crash, in which case a log of talloc()ed memory hardly has any value.

---
V2:
- rename function
- move patch earlier in the series
V3:
- add more init code for the daemon to early_init()
- move mkdir(XENSTORE_LIB_DIR) into a later patch (Julien Grall)
- remove stale stubs in minios.c

---
 tools/xenstored/core.c   | 30 +++---------------------------
 tools/xenstored/core.h   |  7 +++----
 tools/xenstored/minios.c | 11 +++--------
 tools/xenstored/posix.c  | 31 +++++++++++++++++++++++++++++--
 4 files changed, 38 insertions(+), 41 deletions(-)
tools/xenstored/core.c +3 -27
index d4c76d71dc..eba7744fde 100644
@@ -79,7 +79,7 @@ char **orig_argv;
 LIST_HEAD(connections);
 int tracefd = -1;
 bool keep_orphans = false;
-static int reopen_log_pipe[2];
+int reopen_log_pipe[2];
 static int reopen_log_pipe0_pollfd_idx = -1;
 char *tracefile = NULL;
 static struct hashtable *nodes;
@@ -2612,7 +2612,7 @@ static void destroy_fds(void)
 		close(sock);
 }
 
-static void init_sockets(void)
+void init_sockets(void)
 {
 	struct sockaddr_un addr;
 	const char *soc_str = xenstore_daemon_path();
@@ -2903,34 +2903,10 @@ int main(int argc, char *argv[])
 	if (optind != argc)
 		barf("%s: No arguments desired", argv[0]);
 
-	reopen_log();
-
-	/* Make sure xenstored directory exists. */
-	/* Errors ignored here, will be reported when we open files */
-	mkdir(xenstore_daemon_rundir(), 0755);
-
-	if (dofork) {
-		openlog("xenstored", 0, LOG_DAEMON);
-		if (!live_update)
-			daemonize();
-	}
-	if (pidfile)
-		write_pidfile(pidfile);
-
-	/* Talloc leak reports go to stderr, which is closed if we fork. */
-	if (!dofork)
-		talloc_enable_leak_report_full();
-
-	/* Don't kill us with SIGPIPE. */
-	signal(SIGPIPE, SIG_IGN);
+	early_init(live_update, dofork, pidfile);
 
 	talloc_enable_null_tracking();
 
-#ifndef NO_SOCKETS
-	if (!live_update)
-		init_sockets();
-#endif
-
 	init_pipe(reopen_log_pipe);
 
 	/* Listen to hypervisor. */
tools/xenstored/core.h +3 -4
index 480b0f5f7b..72173f1684 100644
@@ -384,12 +384,11 @@ static inline bool domain_is_unprivileged(const struct connection *conn)
 
 /* Return the event channel used by xenbus. */
 evtchn_port_t get_xenbus_evtchn(void);
+void early_init(bool live_update, bool dofork, const char *pidfile);
 
-/* Write out the pidfile */
-void write_pidfile(const char *pidfile);
+void init_sockets(void);
+extern int reopen_log_pipe[2];
 
-/* Fork but do not close terminal FDs */
-void daemonize(void);
 /* Close stdin/stdout/stderr to complete daemonize */
 void finish_daemonize(void);
 
tools/xenstored/minios.c +3 -8
index 0779efbf91..4f48f63083 100644
@@ -20,14 +20,6 @@
 #include "core.h"
 #include <xen/grant_table.h>
 
-void write_pidfile(const char *pidfile)
-{
-}
-
-void daemonize(void)
-{
-}
-
 void finish_daemonize(void)
 {
 }
@@ -54,3 +46,6 @@ void unmap_xenbus(void *interface)
 	xengnttab_unmap(*xgt_handle, interface, 1);
 }
 
+void early_init(bool live_update, bool dofork, const char *pidfile)
+{
+}
tools/xenstored/posix.c +29 -2
index 7e03dd982d..9463ef5c8d 100644
@@ -20,14 +20,17 @@
 #include <sys/stat.h>
 #include <unistd.h>
 #include <fcntl.h>
+#include <signal.h>
 #include <stdlib.h>
+#include <syslog.h>
 #include <sys/mman.h>
+#include <xen-tools/xenstore-common.h>
 
 #include "utils.h"
 #include "core.h"
 #include "osdep.h"
 
-void write_pidfile(const char *pidfile)
+static void write_pidfile(const char *pidfile)
 {
 	char buf[100];
 	int len;
@@ -49,7 +52,7 @@ void write_pidfile(const char *pidfile)
 }
 
 /* Stevens. */
-void daemonize(void)
+static void daemonize(void)
 {
 	pid_t pid;
 
@@ -157,3 +160,27 @@ void *xenbus_map(void)
 
 	return addr;
 }
+
+void early_init(bool live_update, bool dofork, const char *pidfile)
+{
+	reopen_log();
+
+	/* Make sure xenstored directory exists. */
+	/* Errors ignored here, will be reported when we open files */
+	mkdir(xenstore_daemon_rundir(), 0755);
+
+	if (dofork) {
+		openlog("xenstored", 0, LOG_DAEMON);
+		if (!live_update)
+			daemonize();
+	}
+
+	if (pidfile)
+		write_pidfile(pidfile);
+
+	/* Don't kill us with SIGPIPE. */
+	signal(SIGPIPE, SIG_IGN);
+
+	if (!live_update)
+		init_sockets();
+}
Signature · 1 line
2.35.3
#37 lore raw

PATCH v4 22/32 tools/xenstored: move systemd handling to posix.c

In reply to Juergen Gross

Move systemd handling to a new late_init() function in posix.c.

This prepares a future removal of the NO_SOCKETS macro.

---
V3:
- new patch

---
 tools/xenstored/core.c   | 17 +----------------
 tools/xenstored/core.h   |  1 +
 tools/xenstored/minios.c |  4 ++++
 tools/xenstored/posix.c  | 13 +++++++++++++
 4 files changed, 19 insertions(+), 16 deletions(-)
tools/xenstored/core.c +1 -16
index eba7744fde..7b5e1d0c0f 100644
@@ -54,16 +54,6 @@
 #include "control.h"
 #include "lu.h"
 
-#ifndef NO_SOCKETS
-#if defined(HAVE_SYSTEMD)
-#define XEN_SYSTEMD_ENABLED 1
-#endif
-#endif
-
-#if defined(XEN_SYSTEMD_ENABLED)
-#include <systemd/sd-daemon.h>
-#endif
-
 extern xenevtchn_handle *xce_handle; /* in domain.c */
 static int xce_pollfd_idx = -1;
 static struct pollfd *fds;
@@ -2938,12 +2928,7 @@ int main(int argc, char *argv[])
 	/* Get ready to listen to the tools. */
 	initialize_fds(&sock_pollfd_idx, &timeout);
 
-#if defined(XEN_SYSTEMD_ENABLED)
-	if (!live_update) {
-		sd_notify(1, "READY=1");
-		fprintf(stderr, SD_NOTICE "xenstored is ready\n");
-	}
-#endif
+	late_init(live_update);
 
 	/* Main loop. */
 	for (;;) {
tools/xenstored/core.h +1 -0
index 72173f1684..0de2d8a26e 100644
@@ -385,6 +385,7 @@ static inline bool domain_is_unprivileged(const struct connection *conn)
 /* Return the event channel used by xenbus. */
 evtchn_port_t get_xenbus_evtchn(void);
 void early_init(bool live_update, bool dofork, const char *pidfile);
+void late_init(bool live_update);
 
 void init_sockets(void);
 extern int reopen_log_pipe[2];
tools/xenstored/minios.c +4 -0
index 4f48f63083..45bb0440be 100644
@@ -49,3 +49,7 @@ void unmap_xenbus(void *interface)
 void early_init(bool live_update, bool dofork, const char *pidfile)
 {
 }
+
+void late_init(bool live_update)
+{
+}
tools/xenstored/posix.c +13 -0
index 9463ef5c8d..97c8dcaba3 100644
@@ -24,6 +24,9 @@
 #include <stdlib.h>
 #include <syslog.h>
 #include <sys/mman.h>
+#if defined(HAVE_SYSTEMD)
+#include <systemd/sd-daemon.h>
+#endif
 #include <xen-tools/xenstore-common.h>
 
 #include "utils.h"
@@ -184,3 +187,13 @@ void early_init(bool live_update, bool dofork, const char *pidfile)
 	if (!live_update)
 		init_sockets();
 }
+
+void late_init(bool live_update)
+{
+#if defined(HAVE_SYSTEMD)
+	if (!live_update) {
+		sd_notify(1, "READY=1");
+		fprintf(stderr, SD_NOTICE "xenstored is ready\n");
+	}
+#endif
+}
Signature · 1 line
2.35.3
#38 lore raw

PATCH v4 23/32 tools/xenstored: move all log-pipe handling into posix.c

In reply to Juergen Gross

All of the log-pipe handling is needed only when running as daemon.

Move it into posix.c. This requires to have a service function in the main event loop for handling the related requests and one for setting the fds[] array. Use a generic name for those functions, as socket handling can be added to them later, too.

---
V3:
- new patch
V4:
- rename fds to poll_fds (Julien Grall)

---
 tools/xenstored/core.c   | 69 +++++++++++-----------------------------
 tools/xenstored/core.h   | 11 ++++---
 tools/xenstored/minios.c | 14 ++++----
 tools/xenstored/posix.c  | 47 ++++++++++++++++++++++++++-
 4 files changed, 79 insertions(+), 62 deletions(-)
tools/xenstored/core.c +18 -51
index 7b5e1d0c0f..86ab330eaf 100644
@@ -56,7 +56,7 @@
 
 extern xenevtchn_handle *xce_handle; /* in domain.c */
 static int xce_pollfd_idx = -1;
-static struct pollfd *fds;
+struct pollfd *poll_fds;
 static unsigned int current_array_size;
 static unsigned int nr_fds;
 static unsigned int delayed_requests;
@@ -69,8 +69,6 @@ char **orig_argv;
 LIST_HEAD(connections);
 int tracefd = -1;
 bool keep_orphans = false;
-int reopen_log_pipe[2];
-static int reopen_log_pipe0_pollfd_idx = -1;
 char *tracefile = NULL;
 static struct hashtable *nodes;
 unsigned int trace_flags = TRACE_OBJ | TRACE_IO;
@@ -145,18 +143,6 @@ void trace_destroy(const void *data, const char *type)
 		trace("obj: DESTROY %s %p\n", type, data);
 }
 
-/**
- * Signal handler for SIGHUP, which requests that the trace log is reopened
- * (in the main loop).  A single byte is written to reopen_log_pipe, to awaken
- * the poll() in the main loop.
- */
-static void trigger_reopen_log(int signal __attribute__((unused)))
-{
-	char c = 'A';
-	int dummy;
-	dummy = write(reopen_log_pipe[1], &c, 1);
-}
-
 void close_log(void)
 {
 	if (tracefd >= 0)
@@ -467,7 +453,7 @@ static bool conn_can_write(struct connection *conn)
 }
 
 /* This function returns index inside the array if succeed, -1 if fail */
-static int set_fd(int fd, short events)
+int set_fd(int fd, short events)
 {
 	int ret;
 	if (current_array_size < nr_fds + 1) {
@@ -479,18 +465,18 @@ static int set_fd(int fd, short events)
 		 */
 		newsize = ROUNDUP(nr_fds + 1, 8);
 
-		new_fds = realloc(fds, sizeof(struct pollfd)*newsize);
+		new_fds = realloc(poll_fds, sizeof(struct pollfd)*newsize);
 		if (!new_fds)
 			goto fail;
-		fds = new_fds;
+		poll_fds = new_fds;
 
-		memset(&fds[0] + current_array_size, 0,
+		memset(&poll_fds[0] + current_array_size, 0,
 		       sizeof(struct pollfd ) * (newsize-current_array_size));
 		current_array_size = newsize;
 	}
 
-	fds[nr_fds].fd = fd;
-	fds[nr_fds].events = events;
+	poll_fds[nr_fds].fd = fd;
+	poll_fds[nr_fds].events = events;
 	ret = nr_fds;
 	nr_fds++;
 
@@ -505,18 +491,16 @@ static void initialize_fds(int *p_sock_pollfd_idx, int *ptimeout)
 	struct connection *conn;
 	uint64_t msecs;
 
-	if (fds)
-		memset(fds, 0, sizeof(struct pollfd) * current_array_size);
+	if (poll_fds)
+		memset(poll_fds, 0, sizeof(struct pollfd) * current_array_size);
 	nr_fds = 0;
 
 	/* In case of delayed requests pause for max 1 second. */
 	*ptimeout = delayed_requests ? 1000 : -1;
 
+	set_special_fds();
 	if (sock != -1)
 		*p_sock_pollfd_idx = set_fd(sock, POLLIN|POLLPRI);
-	if (reopen_log_pipe[0] != -1)
-		reopen_log_pipe0_pollfd_idx =
-			set_fd(reopen_log_pipe[0], POLLIN|POLLPRI);
 
 	if (xce_handle != NULL)
 		xce_pollfd_idx = set_fd(xenevtchn_fd(xce_handle),
@@ -2324,12 +2308,12 @@ static bool socket_can_process(struct connection *conn, int mask)
 	if (conn->pollfd_idx == -1)
 		return false;
 
-	if (fds[conn->pollfd_idx].revents & ~(POLLIN | POLLOUT)) {
+	if (poll_fds[conn->pollfd_idx].revents & ~(POLLIN | POLLOUT)) {
 		talloc_free(conn);
 		return false;
 	}
 
-	return (fds[conn->pollfd_idx].revents & mask);
+	return (poll_fds[conn->pollfd_idx].revents & mask);
 }
 
 static bool socket_can_write(struct connection *conn)
@@ -2897,8 +2881,6 @@ int main(int argc, char *argv[])
 
 	talloc_enable_null_tracking();
 
-	init_pipe(reopen_log_pipe);
-
 	/* Listen to hypervisor. */
 	if (!live_update) {
 		domain_init(-1);
@@ -2913,7 +2895,6 @@ int main(int argc, char *argv[])
 		xprintf = trace;
 #endif
 
-	signal(SIGHUP, trigger_reopen_log);
 	if (tracefile)
 		tracefile = talloc_strdup(NULL, tracefile);
 
@@ -2934,43 +2915,29 @@ int main(int argc, char *argv[])
 	for (;;) {
 		struct connection *conn, *next;
 
-		if (poll(fds, nr_fds, timeout) < 0) {
+		if (poll(poll_fds, nr_fds, timeout) < 0) {
 			if (errno == EINTR)
 				continue;
 			barf_perror("Poll failed");
 		}
 
-		if (reopen_log_pipe0_pollfd_idx != -1) {
-			if (fds[reopen_log_pipe0_pollfd_idx].revents
-			    & ~POLLIN) {
-				close(reopen_log_pipe[0]);
-				close(reopen_log_pipe[1]);
-				init_pipe(reopen_log_pipe);
-			} else if (fds[reopen_log_pipe0_pollfd_idx].revents
-				   & POLLIN) {
-				char c;
-				if (read(reopen_log_pipe[0], &c, 1) != 1)
-					barf_perror("read failed");
-				reopen_log();
-			}
-			reopen_log_pipe0_pollfd_idx = -1;
-		}
+		handle_special_fds();
 
 		if (sock_pollfd_idx != -1) {
-			if (fds[sock_pollfd_idx].revents & ~POLLIN) {
+			if (poll_fds[sock_pollfd_idx].revents & ~POLLIN) {
 				barf_perror("sock poll failed");
 				break;
-			} else if (fds[sock_pollfd_idx].revents & POLLIN) {
+			} else if (poll_fds[sock_pollfd_idx].revents & POLLIN) {
 				accept_connection(sock);
 				sock_pollfd_idx = -1;
 			}
 		}
 
 		if (xce_pollfd_idx != -1) {
-			if (fds[xce_pollfd_idx].revents & ~POLLIN) {
+			if (poll_fds[xce_pollfd_idx].revents & ~POLLIN) {
 				barf_perror("xce_handle poll failed");
 				break;
-			} else if (fds[xce_pollfd_idx].revents & POLLIN) {
+			} else if (poll_fds[xce_pollfd_idx].revents & POLLIN) {
 				handle_event();
 				xce_pollfd_idx = -1;
 			}
tools/xenstored/core.h +7 -4
index 0de2d8a26e..44c4d0f8b8 100644
@@ -25,6 +25,7 @@
 #include <sys/types.h>
 #include <dirent.h>
 #include <fcntl.h>
+#include <poll.h>
 #include <stdbool.h>
 #include <stdint.h>
 #include <time.h>
@@ -361,6 +362,8 @@ extern int dom0_event;
 extern int priv_domid;
 extern bool keep_orphans;
 
+extern struct pollfd *poll_fds;
+
 extern unsigned int timeout_watch_event_msec;
 
 /* Get internal time in milliseconds. */
@@ -387,15 +390,15 @@ evtchn_port_t get_xenbus_evtchn(void);
 void early_init(bool live_update, bool dofork, const char *pidfile);
 void late_init(bool live_update);
 
+int set_fd(int fd, short events);
+void set_special_fds(void);
+void handle_special_fds(void);
+
 void init_sockets(void);
-extern int reopen_log_pipe[2];
 
 /* Close stdin/stdout/stderr to complete daemonize */
 void finish_daemonize(void);
 
-/* Open a pipe for signal handling */
-void init_pipe(int reopen_log_pipe[2]);
-
 #ifndef NO_SOCKETS
 extern const struct interface_funcs socket_funcs;
 #endif
tools/xenstored/minios.c +8 -6
index 45bb0440be..3208169187 100644
@@ -24,12 +24,6 @@ void finish_daemonize(void)
 {
 }
 
-void init_pipe(int reopen_log_pipe[2])
-{
-	reopen_log_pipe[0] = -1;
-	reopen_log_pipe[1] = -1;
-}
-
 evtchn_port_t get_xenbus_evtchn(void)
 {
 	return dom0_event;
@@ -53,3 +47,11 @@ void early_init(bool live_update, bool dofork, const char *pidfile)
 void late_init(bool live_update)
 {
 }
+
+void set_special_fds(void)
+{
+}
+
+void handle_special_fds(void)
+{
+}
tools/xenstored/posix.c +46 -1

74 lines not on this page · raw message

Signature · 1 line
2.35.3
Reviewed-by on v4 23/32
#39 lore raw

Re: [PATCH v4 23/32] tools/xenstored: move all log-pipe handling into posix.c

Hi Juergen,

Quoted 6 lines · Juergen Gross

All of the log-pipe handling is needed only when running as daemon.

Move it into posix.c. This requires to have a service function in the main event loop for handling the related requests and one for setting the fds[] array. Use a generic name for those functions, as socket handling can be added to them later, too.

I would mention the rename in the commit message. With that:

Quoted 2 lines

Cheers,

Signature · 1 line
Julien Grall
#40 lore raw

Re: [PATCH v4 23/32] tools/xenstored: move all log-pipe handling into posix.c

Quoted 11 lines · Julien Grall

Hi Juergen,

Quoted 6 lines · Juergen Gross

All of the log-pipe handling is needed only when running as daemon.

Move it into posix.c. This requires to have a service function in the main event loop for handling the related requests and one for setting the fds[] array. Use a generic name for those functions, as socket handling can be added to them later, too.

I would mention the rename in the commit message. With that:

I have modified the commit message to:

tools/xenstored: move all log-pipe handling into posix.c

All of the log-pipe handling is needed only when running as daemon.

Move it into posix.c. This requires to have a service function in the main event loop for handling the related requests and one for setting the fds[] array, which is renamed to poll_fds to have a more specific name. Use a generic name for those functions, as socket handling can be added to them later, too.

Quoted 5 lines
Quoted 3 lines

Thanks,

Juergen

#41 lore raw

Re: [PATCH v4 23/32] tools/xenstored: move all log-pipe handling into posix.c

Hi Juergen,

Quoted 17 lines · Jürgen Groß
Quoted 11 lines · Julien Grall

Hi Juergen,

Quoted 6 lines · Juergen Gross

All of the log-pipe handling is needed only when running as daemon.

Move it into posix.c. This requires to have a service function in the main event loop for handling the related requests and one for setting the fds[] array. Use a generic name for those functions, as socket handling can be added to them later, too.

I would mention the rename in the commit message. With that:

I have modified the commit message to:

tools/xenstored: move all log-pipe handling into posix.c

Quoted 7 lines

All of the log-pipe handling is needed only when running as daemon.

Move it into posix.c. This requires to have a service function in the main event loop for handling the related requests and one for setting the fds[] array, which is renamed to poll_fds to have a more specific name. Use a generic name for those functions, as socket handling can be added to them later, too.

AFAICT, the rest of the patches have been reviewed by either Jason or I. So I will update the commit message while committing.

Cheers,

Signature · 1 line
Julien Grall
#42 lore raw

PATCH v4 24/32 tools/xenstored: move all socket handling into posix.c

In reply to Juergen Gross

All of the socket handling is needed only when running as daemon.

Move it into posix.c, allowing to remove the NO_SOCKETS macro.

---
V3:
- new patch
V4:
- make sock local to posix.c (Julien Grall)

---
 tools/xenstored/Makefile.common |   4 -
 tools/xenstored/core.c          | 160 +------------------------------
 tools/xenstored/core.h          |   7 +-
 tools/xenstored/domain.c        |   9 +-
 tools/xenstored/minios.c        |  15 +++
 tools/xenstored/posix.c         | 164 ++++++++++++++++++++++++++++++++
 6 files changed, 188 insertions(+), 171 deletions(-)
tools/xenstored/Makefile.common +0 -4
index 189ab81b8d..ef63ef650c 100644
@@ -16,10 +16,6 @@ CFLAGS += $(CFLAGS_libxenctrl)
 CFLAGS += $(CFLAGS_libxenguest)
 CFLAGS += $(CFLAGS_libxentoolcore)
 
-ifdef CONFIG_STUBDOM
-CFLAGS += -DNO_SOCKETS=1
-endif
-
 $(XENSTORED_OBJS-y): CFLAGS += $(CFLAGS_libxengnttab)
 
 xenstored.a: $(XENSTORED_OBJS-y)
tools/xenstored/core.c +5 -155

232 lines not on this page · raw message

tools/xenstored/core.h +3 -4
index 44c4d0f8b8..6180ec8b5c 100644
@@ -301,6 +301,7 @@ int rm_node(struct connection *conn, const void *ctx, const char *name);
 
 void setup_structure(bool live_update);
 struct connection *new_connection(const struct interface_funcs *funcs);
+struct connection *add_socket_connection(int fd);
 struct connection *get_connection_by_id(unsigned int conn_id);
 void check_store(void);
 void corrupt(struct connection *conn, const char *fmt, ...);
@@ -394,14 +395,12 @@ int set_fd(int fd, short events);
 void set_special_fds(void);
 void handle_special_fds(void);
 
-void init_sockets(void);
+int get_socket_fd(void);
+void set_socket_fd(int fd);
 
 /* Close stdin/stdout/stderr to complete daemonize */
 void finish_daemonize(void);
 
-#ifndef NO_SOCKETS
-extern const struct interface_funcs socket_funcs;
-#endif
 extern xengnttab_handle **xgt_handle;
 
 int remember_string(struct hashtable *hash, const char *str);
tools/xenstored/domain.c +1 -8
index 6ef136e01f..040df98b8c 100644
@@ -1739,14 +1739,7 @@ void read_state_connection(const void *ctx, const void *state)
 	struct domain *domain, *tdomain;
 
 	if (sc->conn_type == XS_STATE_CONN_TYPE_SOCKET) {
-#ifdef NO_SOCKETS
-		barf("socket based connection without sockets");
-#else
-		conn = new_connection(&socket_funcs);
-		if (!conn)
-			barf("error restoring connection");
-		conn->fd = sc->spec.socket_fd;
-#endif
+		conn = add_socket_connection(sc->spec.socket_fd);
 	} else {
 		domain = introduce_domain(ctx, sc->spec.ring.domid,
 					  sc->spec.ring.evtchn, true);
tools/xenstored/minios.c +15 -0
index 3208169187..6d0c11423c 100644
@@ -18,12 +18,18 @@
 #include <sys/types.h>
 #include <sys/mman.h>
 #include "core.h"
+#include "utils.h"
 #include <xen/grant_table.h>
 
 void finish_daemonize(void)
 {
 }
 
+struct connection *add_socket_connection(int fd)
+{
+	barf("socket based connection without sockets");
+}
+
 evtchn_port_t get_xenbus_evtchn(void)
 {
 	return dom0_event;
@@ -55,3 +61,12 @@ void set_special_fds(void)
 void handle_special_fds(void)
 {
 }
+
+int get_socket_fd(void)
+{
+	return -1;
+}
+
+void set_socket_fd(int fd)
+{
+}
tools/xenstored/posix.c +164 -0

201 lines not on this page · raw message

Signature · 1 line
2.35.3
Reviewed-by on v4 24/32
#43 lore raw

Re: [PATCH v4 24/32] tools/xenstored: move all socket handling into posix.c

Hi Juergen,

Quoted 5 lines · Juergen Gross

All of the socket handling is needed only when running as daemon.

Move it into posix.c, allowing to remove the NO_SOCKETS macro.

Cheers,

Signature · 1 line
Julien Grall
#44 lore raw

PATCH v4 25/32 tools/xenstored: get own domid in stubdom case

In reply to Juergen Gross

Obtain own domid when running as stubdom.

---
V2:
- replacement of V1 patch (Andrew Cooper)
V3:
- rename called function to get_domid() (Julien Grall)
- change stub_domid type to domid_t (Julien Grall)

---
 tools/xenstored/core.c   | 1 +
 tools/xenstored/core.h   | 1 +
 tools/xenstored/minios.c | 4 ++++
 3 files changed, 6 insertions(+)
tools/xenstored/core.c +1 -0
index c045a6e5db..9eb3cdf446 100644
@@ -2557,6 +2557,7 @@ static struct option options[] = {
 int dom0_domid = 0;
 int dom0_event = 0;
 int priv_domid = 0;
+domid_t stub_domid = DOMID_INVALID;
 
 static unsigned int get_optval_uint(const char *arg)
 {
tools/xenstored/core.h +1 -0
index 6180ec8b5c..f6af086f01 100644
@@ -361,6 +361,7 @@ do {						\
 extern int dom0_domid;
 extern int dom0_event;
 extern int priv_domid;
+extern domid_t stub_domid;
 extern bool keep_orphans;
 
 extern struct pollfd *poll_fds;
tools/xenstored/minios.c +4 -0
index 6d0c11423c..22ac8defbd 100644
@@ -20,6 +20,7 @@
 #include "core.h"
 #include "utils.h"
 #include <xen/grant_table.h>
+#include <mini-os/lib.h>
 
 void finish_daemonize(void)
 {
@@ -48,6 +49,9 @@ void unmap_xenbus(void *interface)
 
 void early_init(bool live_update, bool dofork, const char *pidfile)
 {
+	stub_domid = get_domid();
+	if (stub_domid == DOMID_INVALID)
+		barf("could not get own domid");
 }
 
 void late_init(bool live_update)
Signature · 1 line
2.35.3
#45 lore raw

PATCH v4 26/32 tools/xenstored: rework ring page (un)map functions

In reply to Juergen Gross

When [un]mapping the ring page of a Xenstore client, different actions are required for "normal" guests and dom0. Today this distinction is made at call site.

Move this distinction into [un]map_interface() instead, avoiding code duplication and preparing special handling for [un]mapping the stub domain's ring page.

---
 tools/xenstored/domain.c | 31 +++++++++++++------------------
 1 file changed, 13 insertions(+), 18 deletions(-)
tools/xenstored/domain.c +13 -18
index 040df98b8c..af80a8221d 100644
@@ -497,14 +497,20 @@ static const struct interface_funcs domain_funcs = {
 
 static void *map_interface(domid_t domid)
 {
+	if (domid == xenbus_master_domid())
+		return xenbus_map();
+
 	return xengnttab_map_grant_ref(*xgt_handle, domid,
 				       GNTTAB_RESERVED_XENSTORE,
 				       PROT_READ|PROT_WRITE);
 }
 
-static void unmap_interface(void *interface)
+static void unmap_interface(domid_t domid, void *interface)
 {
-	xengnttab_unmap(*xgt_handle, interface, 1);
+	if (domid == xenbus_master_domid())
+		unmap_xenbus(interface);
+	else
+		xengnttab_unmap(*xgt_handle, interface, 1);
 }
 
 static int domain_tree_remove_sub(const void *ctx, struct connection *conn,
@@ -594,14 +600,8 @@ static int destroy_domain(void *_domain)
 			eprintf("> Unbinding port %i failed!\n", domain->port);
 	}
 
-	if (domain->interface) {
-		/* Domain 0 was mapped by dom0_init, so it must be unmapped
-		   using munmap() and not the grant unmap call. */
-		if (domain->domid == dom0_domid)
-			unmap_xenbus(domain->interface);
-		else
-			unmap_interface(domain->interface);
-	}
+	if (domain->interface)
+		unmap_interface(domain->domid, domain->interface);
 
 	fire_special_watches("@releaseDomain");
 
@@ -966,18 +966,13 @@ static struct domain *introduce_domain(const void *ctx,
 		return NULL;
 
 	if (!domain->introduced) {
-		interface = is_master_domain ? xenbus_map()
-					     : map_interface(domid);
+		interface = map_interface(domid);
 		if (!interface && !restore)
 			return NULL;
 		if (new_domain(domain, port, restore)) {
 			rc = errno;
-			if (interface) {
-				if (is_master_domain)
-					unmap_xenbus(interface);
-				else
-					unmap_interface(interface);
-			}
+			if (interface)
+				unmap_interface(domid, interface);
 			errno = rc;
 			return NULL;
 		}
Signature · 1 line
2.35.3
#46 lore raw

PATCH v4 27/32 tools/xenstored: split domain_init()

In reply to Juergen Gross

Today domain_init() is called either just before calling dom0_init() in case no live update is being performed, or it is called after reading the global state from read_state_global(), as the event channel fd is needed.

Split up domain_init() into a preparation part which can be called unconditionally, and in a part setting up the event channel handle.

Note that there is no chance that chk_domain_generation() can be called now before xc_handle has been setup, so there is no need for the related special case anymore.

---
V3:
- rename new function to domain_early_init() (Julien Grall)

---
 tools/xenstored/core.c   |  2 ++
 tools/xenstored/domain.c | 12 ++++++------
 tools/xenstored/domain.h |  1 +
 3 files changed, 9 insertions(+), 6 deletions(-)
tools/xenstored/core.c +2 -0
index 9eb3cdf446..3bf2ec7734 100644
@@ -2742,6 +2742,8 @@ int main(int argc, char *argv[])
 
 	talloc_enable_null_tracking();
 
+	domain_early_init();
+
 	/* Listen to hypervisor. */
 	if (!live_update) {
 		domain_init(-1);
tools/xenstored/domain.c +6 -6
index af80a8221d..621b415088 100644
@@ -1224,10 +1224,8 @@ static int domeq_fn(const void *key1, const void *key2)
 	return *(const unsigned int *)key1 == *(const unsigned int *)key2;
 }
 
-void domain_init(int evtfd)
+void domain_early_init(void)
 {
-	int rc;
-
 	/* Start with a random rather low domain count for the hashtable. */
 	domhash = create_hashtable(NULL, "domains", domhash_fn, domeq_fn, 0);
 	if (!domhash)
@@ -1258,6 +1256,11 @@ void domain_init(int evtfd)
 	xengnttab_set_max_grants(*xgt_handle, DOMID_FIRST_RESERVED);
 
 	talloc_set_destructor(xgt_handle, close_xgt_handle);
+}
+
+void domain_init(int evtfd)
+{
+	int rc;
 
 	if (evtfd < 0)
 		xce_handle = xenevtchn_open(NULL, XENEVTCHN_NO_CLOEXEC);
@@ -1291,9 +1294,6 @@ static bool chk_domain_generation(unsigned int domid, uint64_t gen)
 {
 	struct domain *d;
 
-	if (!xc_handle && domid == dom0_domid)
-		return true;
-
 	d = find_domain_struct(domid);
 
 	return d && d->generation <= gen;
tools/xenstored/domain.h +1 -0
index 7625dca8cd..224c4c23e2 100644
@@ -82,6 +82,7 @@ int do_get_domain_path(const void *ctx, struct connection *conn,
 int do_reset_watches(const void *ctx, struct connection *conn,
 		     struct buffered_data *in);
 
+void domain_early_init(void);
 void domain_init(int evtfd);
 void dom0_init(void);
 void domain_deinit(void);
Signature · 1 line
2.35.3
#47 lore raw

PATCH v4 28/32 tools/xenstored: map stubdom interface

In reply to Juergen Gross

When running as stubdom, map the stubdom's Xenstore ring page in order to support using the 9pfs frontend.

Use the same pattern as in dom0_init() when running as daemon in dom0 (introduce the own domain, then send an event to the client side to signal Xenstore is ready to communicate).

---
 tools/xenstored/core.c   |  2 ++
 tools/xenstored/domain.c | 27 ++++++++++++++++++++++++++-
 tools/xenstored/domain.h |  1 +
 3 files changed, 29 insertions(+), 1 deletion(-)
tools/xenstored/core.c +2 -0
index 3bf2ec7734..48fc787ac1 100644
@@ -2767,6 +2767,8 @@ int main(int argc, char *argv[])
 		lu_read_state();
 #endif
 
+	stubdom_init();
+
 	check_store();
 
 	/* Get ready to listen to the tools. */
tools/xenstored/domain.c +26 -1
index 621b415088..1a7d5e9756 100644
@@ -37,6 +37,10 @@
 #include <xenctrl.h>
 #include <xen/grant_table.h>
 
+#ifdef __MINIOS__
+#include <mini-os/xenbus.h>
+#endif
+
 static xc_interface **xc_handle;
 xengnttab_handle **xgt_handle;
 static evtchn_port_t virq_port;
@@ -500,6 +504,11 @@ static void *map_interface(domid_t domid)
 	if (domid == xenbus_master_domid())
 		return xenbus_map();
 
+#ifdef __MINIOS__
+	if (domid == stub_domid)
+		return xenstore_buf;
+#endif
+
 	return xengnttab_map_grant_ref(*xgt_handle, domid,
 				       GNTTAB_RESERVED_XENSTORE,
 				       PROT_READ|PROT_WRITE);
@@ -509,7 +518,7 @@ static void unmap_interface(domid_t domid, void *interface)
 {
 	if (domid == xenbus_master_domid())
 		unmap_xenbus(interface);
-	else
+	else if (domid != stub_domid)
 		xengnttab_unmap(*xgt_handle, interface, 1);
 }
 
@@ -1214,6 +1223,22 @@ void dom0_init(void)
 	xenevtchn_notify(xce_handle, dom0->port);
 }
 
+void stubdom_init(void)
+{
+#ifdef __MINIOS__
+	struct domain *stubdom;
+
+	if (stub_domid < 0)
+		return;
+
+	stubdom = introduce_domain(NULL, stub_domid, xenbus_evtchn, false);
+	if (!stubdom)
+		barf_perror("Failed to initialize stubdom");
+
+	xenevtchn_notify(xce_handle, stubdom->port);
+#endif
+}
+
 static unsigned int domhash_fn(const void *k)
 {
 	return *(const unsigned int *)k;
tools/xenstored/domain.h +1 -0
index 224c4c23e2..844ac11510 100644
@@ -85,6 +85,7 @@ int do_reset_watches(const void *ctx, struct connection *conn,
 void domain_early_init(void);
 void domain_init(int evtfd);
 void dom0_init(void);
+void stubdom_init(void);
 void domain_deinit(void);
 void ignore_connection(struct connection *conn, unsigned int err);
 
Signature · 1 line
2.35.3
#48 lore raw

PATCH v4 29/32 tools/xenstored: mount 9pfs device in stubdom

In reply to Juergen Gross

Mount the 9pfs device in stubdom enabling it to use files.

This has to happen in a worker thread in order to allow the main thread handling the required Xenstore accesses in parallel.

---
V3:
- add logging in case of errors (Julien Grall)

---
 tools/xenstored/core.h   |  6 +++++
 tools/xenstored/domain.c |  2 ++
 tools/xenstored/minios.c | 54 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 62 insertions(+)
tools/xenstored/core.h +6 -0
index f6af086f01..fe0ee90581 100644
@@ -36,6 +36,8 @@
 #include "list.h"
 #include "hashtable.h"
 
+#define XENSTORE_LIB_DIR	XEN_LIB_DIR "/xenstore"
+
 #ifndef O_CLOEXEC
 #define O_CLOEXEC 0
 /* O_CLOEXEC support is needed for Live Update in the daemon case. */
@@ -399,6 +401,10 @@ void handle_special_fds(void);
 int get_socket_fd(void);
 void set_socket_fd(int fd);
 
+#ifdef __MINIOS__
+void mount_9pfs(void);
+#endif
+
 /* Close stdin/stdout/stderr to complete daemonize */
 void finish_daemonize(void);
 
tools/xenstored/domain.c +2 -0
index 1a7d5e9756..64c8fd0cc3 100644
@@ -1236,6 +1236,8 @@ void stubdom_init(void)
 		barf_perror("Failed to initialize stubdom");
 
 	xenevtchn_notify(xce_handle, stubdom->port);
+
+	mount_9pfs();
 #endif
 }
 
tools/xenstored/minios.c +54 -0

67 lines not on this page · raw message

Signature · 1 line
2.35.3
#49 lore raw

PATCH v4 30/32 tools/xenstored: add helpers for filename handling

In reply to Juergen Gross

Add some helpers for handling filenames which might need different implementations between stubdom and daemon environments:

- expansion of relative filenames (those are not really defined today, just expand them to be relative to /var/lib/xen/xenstore)
- expansion of xenstore_daemon_rundir() (used e.g. for saving the state file in case of live update - needs to be unchanged in the daemon case, but should result in /var/lib/xen/xenstore for stubdom)

---
V3:
- make absolute_filename() return a pointer to const (Julien Grall)

---
 tools/xenstored/core.c      | 15 +++++++++++++--
 tools/xenstored/core.h      |  5 ++++-
 tools/xenstored/lu_daemon.c |  4 ++--
 tools/xenstored/minios.c    |  5 +++++
 tools/xenstored/posix.c     |  8 +++++++-
 5 files changed, 31 insertions(+), 6 deletions(-)
tools/xenstored/core.c +13 -2
index 48fc787ac1..bada1ad9a2 100644
@@ -63,7 +63,7 @@ char **orig_argv;
 LIST_HEAD(connections);
 int tracefd = -1;
 bool keep_orphans = false;
-char *tracefile = NULL;
+const char *tracefile = NULL;
 static struct hashtable *nodes;
 unsigned int trace_flags = TRACE_OBJ | TRACE_IO;
 
@@ -137,6 +137,17 @@ void trace_destroy(const void *data, const char *type)
 		trace("obj: DESTROY %s %p\n", type, data);
 }
 
+/*
+ * Return an absolute filename.
+ * In case of a relative filename given as input, prepend XENSTORE_LIB_DIR.
+ */
+const char *absolute_filename(const void *ctx, const char *filename)
+{
+	if (filename[0] != '/')
+		return talloc_asprintf(ctx, XENSTORE_LIB_DIR "/%s", filename);
+	return talloc_strdup(ctx, filename);
+}
+
 void close_log(void)
 {
 	if (tracefd >= 0)
@@ -2759,7 +2770,7 @@ int main(int argc, char *argv[])
 #endif
 
 	if (tracefile)
-		tracefile = talloc_strdup(NULL, tracefile);
+		tracefile = absolute_filename(NULL, tracefile);
 
 #ifndef NO_LIVE_UPDATE
 	/* Read state in case of live update. */
tools/xenstored/core.h +4 -1
index fe0ee90581..e58779e88c 100644
@@ -341,7 +341,7 @@ void close_log(void);
 extern int orig_argc;
 extern char **orig_argv;
 
-extern char *tracefile;
+extern const char *tracefile;
 extern int tracefd;
 
 /* Trace flag values must be kept in sync with trace_switches[] contents. */
@@ -405,6 +405,9 @@ void set_socket_fd(int fd);
 void mount_9pfs(void);
 #endif
 
+const char *xenstore_rundir(void);
+const char *absolute_filename(const void *ctx, const char *filename);
+
 /* Close stdin/stdout/stderr to complete daemonize */
 void finish_daemonize(void);
 
tools/xenstored/lu_daemon.c +2 -2
index 71bcabadd3..6351111ab0 100644
@@ -24,7 +24,7 @@ void lu_get_dump_state(struct lu_dump_state *state)
 	state->size = 0;
 
 	state->filename = talloc_asprintf(NULL, "%s/state_dump",
-					  xenstore_daemon_rundir());
+					  xenstore_rundir());
 	if (!state->filename)
 		barf("Allocation failure");
 
@@ -65,7 +65,7 @@ FILE *lu_dump_open(const void *ctx)
 	int fd;
 
 	filename = talloc_asprintf(ctx, "%s/state_dump",
-				   xenstore_daemon_rundir());
+				   xenstore_rundir());
 	if (!filename)
 		return NULL;
 
tools/xenstored/minios.c +5 -0
index 562a9b4972..e70386f8c7 100644
@@ -128,3 +128,8 @@ void mount_9pfs(void)
 {
 	create_thread("mount-9pfs", mount_thread, NULL);
 }
+
+const char *xenstore_rundir(void)
+{
+	return XENSTORE_LIB_DIR;
+}
tools/xenstored/posix.c +7 -1
index 496329dfd1..d88c82d972 100644
@@ -326,9 +326,10 @@ void early_init(bool live_update, bool dofork, const char *pidfile)
 {
 	reopen_log();
 
-	/* Make sure xenstored directory exists. */
+	/* Make sure xenstored directories exist. */
 	/* Errors ignored here, will be reported when we open files */
 	mkdir(xenstore_daemon_rundir(), 0755);
+	mkdir(XENSTORE_LIB_DIR, 0755);
 
 	if (dofork) {
 		openlog("xenstored", 0, LOG_DAEMON);
@@ -406,3 +407,8 @@ void set_socket_fd(int fd)
 {
 	sock = fd;
 }
+
+const char *xenstore_rundir(void)
+{
+	return xenstore_daemon_rundir();
+}
Signature · 1 line
2.35.3
#50 lore raw

PATCH v4 31/32 tools/xenstored: support complete log capabilities in stubdom

In reply to Juergen Gross

With 9pfs being fully available in Xenstore-stubdom now, there is no reason to not fully support all logging capabilities in stubdom.

Open the logfile on stubdom only after the 9pfs file system has been mounted.

---
V3:
- remove now stale comment in sysconfig.xencommons.in (Julien Grall)

---
 .../Linux/init.d/sysconfig.xencommons.in      |  1 -
 tools/hotplug/Linux/launch-xenstore.in        |  1 +
 tools/xenstored/control.c                     | 30 +++++++++----------
 tools/xenstored/minios.c                      |  3 ++
 4 files changed, 19 insertions(+), 16 deletions(-)
tools/hotplug/Linux/init.d/sysconfig.xencommons.in +0 -1
index 433e4849af..1bdd830d8a 100644
@@ -58,7 +58,6 @@ XENSTORED_ARGS=
 ## Default: Not defined, tracing off
 #
 # Log xenstored messages
-# Only evaluated if XENSTORETYPE is "daemon".
 #XENSTORED_TRACE=[yes|on|1]
 
 ## Type: integer
tools/hotplug/Linux/launch-xenstore.in +1 -0
index e854ca1eb8..da4eeca7c5 100644
@@ -98,6 +98,7 @@ test -f @CONFIG_DIR@/@CONFIG_LEAF_DIR@/xencommons && . @CONFIG_DIR@/@CONFIG_LEAF
 	[ -z "$XENSTORE_DOMAIN_SIZE" ] && XENSTORE_DOMAIN_SIZE=8
 	XENSTORE_DOMAIN_ARGS="$XENSTORE_DOMAIN_ARGS --memory $XENSTORE_DOMAIN_SIZE"
 	[ -z "$XENSTORE_MAX_DOMAIN_SIZE" ] || XENSTORE_DOMAIN_ARGS="$XENSTORE_DOMAIN_ARGS --maxmem $XENSTORE_MAX_DOMAIN_SIZE"
+	[ -z "$XENSTORED_TRACE" ] || XENSTORE_DOMAIN_ARGS="$XENSTORE_DOMAIN_ARGS -T xenstored-trace.log"
 
 	echo -n Starting $XENSTORE_DOMAIN_KERNEL...
 	${LIBEXEC_BIN}/init-xenstore-domain $XENSTORE_DOMAIN_ARGS || exit 1
tools/xenstored/control.c +15 -15
index b2f64d674f..dae23a5ac0 100644
@@ -201,19 +201,6 @@ static int do_control_quota_s(const void *ctx, struct connection *conn,
 	return EINVAL;
 }
 
-#ifdef __MINIOS__
-static int do_control_memreport(const void *ctx, struct connection *conn,
-				const char **vec, int num)
-{
-	if (num)
-		return EINVAL;
-
-	talloc_report_full(NULL, stdout);
-
-	send_ack(conn, XS_CONTROL);
-	return 0;
-}
-#else
 static int do_control_logfile(const void *ctx, struct connection *conn,
 			      const char **vec, int num)
 {
@@ -222,13 +209,26 @@ static int do_control_logfile(const void *ctx, struct connection *conn,
 
 	close_log();
 	talloc_free(tracefile);
-	tracefile = talloc_strdup(NULL, vec[0]);
+	tracefile = absolute_filename(NULL, vec[0]);
 	reopen_log();
 
 	send_ack(conn, XS_CONTROL);
 	return 0;
 }
 
+#ifdef __MINIOS__
+static int do_control_memreport(const void *ctx, struct connection *conn,
+				const char **vec, int num)
+{
+	if (num)
+		return EINVAL;
+
+	talloc_report_full(NULL, stdout);
+
+	send_ack(conn, XS_CONTROL);
+	return 0;
+}
+#else
 static int do_control_memreport(const void *ctx, struct connection *conn,
 				const char **vec, int num)
 {
@@ -309,10 +309,10 @@ static struct cmd_s cmds[] = {
 		"[-c <cmdline>] [-F] [-t <timeout>] <file>\n"
 		"    Default timeout is 60 seconds.", 5 },
 #endif
+	{ "logfile", do_control_logfile, "<file>" },
 #ifdef __MINIOS__
 	{ "memreport", do_control_memreport, "" },
 #else
-	{ "logfile", do_control_logfile, "<file>" },
 	{ "memreport", do_control_memreport, "[<file>]" },
 #endif
 	{ "print", do_control_print, "<string>" },
tools/xenstored/minios.c +3 -0
index e70386f8c7..a229954cf4 100644
@@ -122,6 +122,9 @@ static void mount_thread(void *p)
 	}
 
 	p9_device = init_9pfront(0, XENSTORE_LIB_DIR);
+
+	/* Start logging if selected. */
+	reopen_log();
 }
 
 void mount_9pfs(void)
Signature · 1 line
2.35.3
#51 lore raw

PATCH v4 32/32 tools/xenstored: have a single do_control_memreport()

In reply to Juergen Gross

With 9pfs now available in Xenstore-stubdom, there is no reason to have distinct do_control_memreport() variants for the daemon and the stubdom implementations.

---
 tools/xenstored/control.c | 27 +++++++--------------------
 1 file changed, 7 insertions(+), 20 deletions(-)
tools/xenstored/control.c +7 -20
index dae23a5ac0..9561289179 100644
@@ -216,23 +216,11 @@ static int do_control_logfile(const void *ctx, struct connection *conn,
 	return 0;
 }
 
-#ifdef __MINIOS__
-static int do_control_memreport(const void *ctx, struct connection *conn,
-				const char **vec, int num)
-{
-	if (num)
-		return EINVAL;
-
-	talloc_report_full(NULL, stdout);
-
-	send_ack(conn, XS_CONTROL);
-	return 0;
-}
-#else
 static int do_control_memreport(const void *ctx, struct connection *conn,
 				const char **vec, int num)
 {
 	FILE *fp;
+	const char *filename;
 	int fd;
 
 	if (num > 1)
@@ -255,8 +243,12 @@ static int do_control_memreport(const void *ctx, struct connection *conn,
 			if (!fp)
 				close(fd);
 		}
-	} else
-		fp = fopen(vec[0], "a");
+	} else {
+		filename = absolute_filename(ctx, vec[0]);
+		if (!filename)
+			return ENOMEM;
+		fp = fopen(filename, "a");
+	}
 
 	if (!fp)
 		return EBADF;
@@ -267,7 +259,6 @@ static int do_control_memreport(const void *ctx, struct connection *conn,
 	send_ack(conn, XS_CONTROL);
 	return 0;
 }
-#endif
 
 static int do_control_print(const void *ctx, struct connection *conn,
 			    const char **vec, int num)
@@ -310,11 +301,7 @@ static struct cmd_s cmds[] = {
 		"    Default timeout is 60 seconds.", 5 },
 #endif
 	{ "logfile", do_control_logfile, "<file>" },
-#ifdef __MINIOS__
-	{ "memreport", do_control_memreport, "" },
-#else
 	{ "memreport", do_control_memreport, "[<file>]" },
-#endif
 	{ "print", do_control_print, "<string>" },
 	{ "quota", do_control_quota,
 		"[set <name> <val>|<domid>|max [-r]]" },
Signature · 1 line
2.35.3