Skip to contentSkip to conversation

QEMU Object Model

RFC PATCH In review Anthony Liguori 5 participants 52 messages Jul 25, 2011 – Jul 29, 2011 Kbuild

lore
Share & tools
lore
#0 lore raw

cover QEMU Object Model

Hi,

This series is the rough beginnings of the QEMU Object Model. This is basically qdev generalized on steroids.

This series includes the core infrastructure, a strawman Device type, and the beginnings of the conversion of CharDriverState. This is in a rougher state than I would like it to be but I wanted to get the concepts on the list as soon as possible.

My plan is to drop the Device parts from future versions of the series and just focus on backends to start with.

Please note that this series has an awful lot of ramifications. Most of our current command line options would become deprecated, the build system will change significantly, and a lot of our QMP functions will become deprecated.

It seems like a lot of change, but hopefully this series illustrates how we can do it very incrementally with value being added at each stage of the conversion.

#1 lore raw

PATCH 1/21 qom: add make infrastructure

QOM provides a unified model for separating modules into independently buildable components. To fully take advantage of this, we need a bit more make infrastructure that lets us describe these modules and their dependencies. Ultimately this will enable us to support tristate modules that can be demand loaded as shared libraries.

For now, only support boolean modules and don't do any dependency resolution. I expect that we'll figure out how to borrow the kernel's Kconfig processing scripts to make this all work.

---
 Makefile.objs        |    3 +++
 Makefile.qom         |    9 +++++++++
 Qconfig              |    1 +
 scripts/genconfig.sh |   30 ++++++++++++++++++++++++++++++
 4 files changed, 43 insertions(+), 0 deletions(-)
 create mode 100644 Makefile.qom
 create mode 100644 Qconfig
 create mode 100755 scripts/genconfig.sh
Makefile.objs +3 -0
index 6991a9f..9cc87fd 100644
@@ -158,6 +158,9 @@ common-obj-$(CONFIG_SLIRP) += $(addprefix slirp/, $(slirp-obj-y))
 common-obj-$(CONFIG_XEN_BACKEND) += xen_backend.o xen_devconfig.o
 common-obj-$(CONFIG_XEN_BACKEND) += xen_console.o xenfb.o xen_disk.o xen_nic.o
 
+# QEMU Object Model
+include $(SRC_PATH)/Makefile.qom
+
 ######################################################################
 # libuser
 
Makefile.qom new file +9 -0
new file mode 100644
index 0000000..8b14952
@@ -0,0 +1,9 @@
+QEMU_CFLAGS += -I$(SRC_PATH)/include
+
+QCONFIGS = $(shell find $(SRC_PATH) -name "Qconfig" -print)
+
+config-qom.mak: $(SRC_PATH)/Qconfig $(QCONFIGS)
+	$(SRC_PATH)/scripts/genconfig.sh $< > $@
+
+-include config-qom.mak
+
Qconfig new file +1 -0
new file mode 100644
index 0000000..62b15d7
@@ -0,0 +1 @@
+# Do nothing for now
scripts/genconfig.sh new file +30 -0
new file mode 100755
index 0000000..14fef23
@@ -0,0 +1,30 @@
+#!/bin/sh
+#
+# Simple Qconfig parser
+#
+# Copyright IBM, Corp. 2011
+#
+# Authors:
+#  Anthony Liguori   <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL, version 2.  See
+# the COPYING file in the top-level directory.
+#
+
+# This is just intended as a placeholder.  Please do not enhance this script.
+# Instead, please try to port the Linux kernel's Kconfig parser.
+
+process() {
+    local basedir=`dirname $1`
+    cat "$1" | while read LINE; do
+	local first_word=`echo $LINE | cut -f1 -d' '`
+	if test "$first_word" = "config"; then
+	    echo $LINE | sed -e 's:^config \(.*\):CONFIG_\1=y:g'
+	elif test "$first_word" = "source"; then
+	    local rest=`echo $LINE | cut -f2- -d' '`
+	    process "$basedir/$rest"
+	fi
+    done
+}
+
+process "$1"
Signature · 1 line
1.7.4.1
#2 lore raw

PATCH 2/21 qom: convert QAPI to use Qconfig build system

In reply to Anthony Liguori

Plug depends on QAPI and in order to express that dependency, QAPI needs to use the Qconfig build system. Right now, QAPI is only built for guest agent, but this changes the generic build to now include QAPI.

---
 Makefile      |   10 ++++++----
 Makefile.objs |    4 ----
 Makefile.qom  |    2 ++
 Qconfig       |    2 +-
 qapi/Makefile |    3 +++
 qapi/Qconfig  |   19 +++++++++++++++++++
 6 files changed, 31 insertions(+), 9 deletions(-)
 create mode 100644 qapi/Makefile
 create mode 100644 qapi/Qconfig
Makefile +6 -4
index f3a03ad..81d864f 100644
@@ -185,16 +185,18 @@ $(qapi-dir)/qga-qapi-visit.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scr
 $(qapi-dir)/qga-qmp-marshal.c: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py
 	$(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "qga-" < $<, "  GEN   $@")
 
-test-visitor.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h) $(qapi-obj-y)
+qga-obj-y := $(addprefix qapi/,$(qapi-obj-y))
+
+test-visitor.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h) $(qga-obj-y)
 test-visitor: test-visitor.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o
 
 test-qmp-commands.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h test-qmp-marshal.c test-qmp-commands.h) $(qapi-obj-y)
-test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o
+test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qga-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o
 
 QGALIB=qga/guest-agent-command-state.o qga/guest-agent-commands.o
 
-qemu-ga.o: $(addprefix $(qapi-dir)/, qga-qapi-types.c qga-qapi-types.h qga-qapi-visit.c qga-qmp-marshal.c) $(qapi-obj-y)
-qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o $(qapi-dir)/qga-qapi-visit.o $(qapi-dir)/qga-qapi-types.o $(qapi-dir)/qga-qmp-marshal.o
+qemu-ga.o: $(addprefix $(qapi-dir)/, qga-qapi-types.c qga-qapi-types.h qga-qapi-visit.c qga-qmp-marshal.c) $(qga-obj-y)
+qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qga-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o $(qapi-dir)/qga-qapi-visit.o $(qapi-dir)/qga-qapi-types.o $(qapi-dir)/qga-qmp-marshal.o
 
 QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
 
Makefile.objs +0 -4
index 9cc87fd..ef6030a 100644
@@ -379,10 +379,6 @@ libcacard-y = cac.o event.o vcard.o vreader.o vcard_emul_nss.o vcard_emul_type.o
 ######################################################################
 # qapi
 
-qapi-nested-y = qapi-visit-core.o qmp-input-visitor.o qmp-output-visitor.o qapi-dealloc-visitor.o
-qapi-nested-y += qmp-registry.o qmp-dispatch.o
-qapi-obj-y = $(addprefix qapi/, $(qapi-nested-y))
-
 vl.o: QEMU_CFLAGS+=$(GPROF_CFLAGS)
 
 vl.o: QEMU_CFLAGS+=$(SDL_CFLAGS)
Makefile.qom +2 -0
index 8b14952..1b06970 100644
@@ -7,3 +7,5 @@ config-qom.mak: $(SRC_PATH)/Qconfig $(QCONFIGS)
 
 -include config-qom.mak
 
+include $(SRC_PATH)/qapi/Makefile
+common-obj-y += $(addprefix qapi/,$(qapi-obj-y))
Qconfig +1 -1
index 62b15d7..cdf8f6c 100644
@@ -1 +1 @@
-# Do nothing for now
+source qapi/Qconfig
qapi/Makefile new file +3 -0
new file mode 100644
index 0000000..11efdfe
@@ -0,0 +1,3 @@
+qapi-obj-$(CONFIG_QAPI) += qapi-dealloc-visitor.o qapi-visit-core.o
+qapi-obj-$(CONFIG_QAPI_QMP) += qmp-input-visitor.o qmp-output-visitor.o
+qapi-obj-$(CONFIG_QAPI_QMP_SERVER) += qmp-dispatch.o qmp-registry.o
qapi/Qconfig new file +19 -0
new file mode 100644
index 0000000..aaa9f01
@@ -0,0 +1,19 @@
+config QAPI
+       bool "QEMU API Support"
+       default y
+       help
+         This provides a generic marshalling framework for converting C types
+         to other data structures.  If unsure, say y here.
+
+config QAPI_QMP
+       bool "QAPI support for QObjects"
+       default y
+       help
+         This allows QAPI to convert to and from QObjects.  QObjects are mainly
+         used to marshal to and from JSON.
+
+config QAPI_QMP_SERVER
+       bool "QAPI based QMP server"
+       default y
+       help
+         This provides a QMP server framework using QAPI.
Signature · 1 line
1.7.4.1
#3 lore raw

PATCH 3/21 qom: Add core type system

In reply to Anthony Liguori

This patch implements the basic type system used by QEMU Object Model. This infrastructure supports the registration of classes and instantiation of objects through a generic factory interface. Classes support polymophism and single inheritance.

Interfaces can also be used to approximate multiple inheritance.

---
 Makefile.qom        |    4 +
 Qconfig             |    1 +
 configure           |    2 +-
 include/qemu/type.h |  513 ++++++++++++++++++++++++++++++++++++++++++++++++++
 qom/Makefile        |    1 +
 qom/Qconfig         |    6 +
 qom/type.c          |  523 +++++++++++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 1049 insertions(+), 1 deletions(-)
 create mode 100644 include/qemu/type.h
 create mode 100644 qom/Makefile
 create mode 100644 qom/Qconfig
 create mode 100644 qom/type.c
Makefile.qom +4 -0
index 1b06970..34f1f91 100644
@@ -9,3 +9,7 @@ config-qom.mak: $(SRC_PATH)/Qconfig $(QCONFIGS)
 
 include $(SRC_PATH)/qapi/Makefile
 common-obj-y += $(addprefix qapi/,$(qapi-obj-y))
+
+include $(SRC_PATH)/qom/Makefile
+common-obj-y += $(addprefix qom/,$(qom-obj-y))
+
Qconfig +1 -0
index cdf8f6c..889dfa6 100644
@@ -1 +1,2 @@
 source qapi/Qconfig
+source qom/Qconfig
configure +1 -1
index 600da9b..93e5e97 100755
@@ -3516,7 +3516,7 @@ DIRS="$DIRS pc-bios/spapr-rtas"
 DIRS="$DIRS roms/seabios roms/vgabios"
 DIRS="$DIRS fsdev ui"
 DIRS="$DIRS qapi"
-DIRS="$DIRS qga"
+DIRS="$DIRS qga qom"
 FILES="Makefile tests/Makefile"
 FILES="$FILES tests/cris/Makefile tests/cris/.gdbinit"
 FILES="$FILES pc-bios/optionrom/Makefile pc-bios/keymaps"
include/qemu/type.h new file +513 -0

513 lines not on this page · raw message

qom/Makefile new file +1 -0
new file mode 100644
index 0000000..838054f
@@ -0,0 +1 @@
+qom-obj-$(CONFIG_QOM) += type.o
qom/Qconfig new file +6 -0
new file mode 100644
index 0000000..16660b4
@@ -0,0 +1,6 @@
+config QOM
+       bool "QEMU Object Model Support"
+       default y
+       depends on QAPI
+       help
+         This is the core object model used by QEMU.  If in doubt, say y here.
qom/type.c new file +523 -0

523 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#4 lore raw

PATCH 4/21 qom: add Plug class

In reply to Anthony Liguori

The Plug class is the base class for all objects. Plugs implement properties using the existing Visitor framework. This allows for very complex properties to be implemented.

Plugs also implement life cycle management by containing a realized state. An object isn't fully constructed until its realized. By setting realized to false, an object can also be reset.

Plug properties can be set to be read-only or read-write. A read-write property can be locked. While a read-write property is locked, it cannot be written to.

The expectation is that some properties will be locked at realize time.

---
 include/qemu/plug-proptypes.h |   14 +++
 include/qemu/plug.h           |   73 +++++++++++++
 qerror.c                      |    4 +
 qerror.h                      |    3 +
 qom/Makefile                  |    2 +-
 qom/plug-proptypes.c          |   52 ++++++++++
 qom/plug.c                    |  225 +++++++++++++++++++++++++++++++++++++++++
 qom/string-visitor.c          |   41 ++++++++
 qom/string-visitor.h          |   21 ++++
 9 files changed, 434 insertions(+), 1 deletions(-)
 create mode 100644 include/qemu/plug-proptypes.h
 create mode 100644 include/qemu/plug.h
 create mode 100644 qom/plug-proptypes.c
 create mode 100644 qom/plug.c
 create mode 100644 qom/string-visitor.c
 create mode 100644 qom/string-visitor.h
include/qemu/plug-proptypes.h new file +14 -0
new file mode 100644
index 0000000..2c7be0e
@@ -0,0 +1,14 @@
+#ifndef PLUG_PROPTYPES_H
+#define PLUG_PROPTYPES_H
+
+#include "plug.h"
+
+typedef bool (PlugPropertyGetterBool)(Plug *plug);
+typedef void (PlugPropertySetterBool)(Plug *plug, bool value);
+
+void plug_add_property_bool(Plug *plug, const char *name,
+                            PlugPropertyGetterBool *getter,
+                            PlugPropertySetterBool *setter,
+                            int flags);
+
+#endif
include/qemu/plug.h new file +73 -0

73 lines not on this page · raw message

qerror.c +4 -0
index 69c1bc9..dbe119c 100644
@@ -170,6 +170,10 @@ static const QErrorStringTable qerror_table[] = {
         .desc      = "Property '%(device).%(property)' not found",
     },
     {
+        .error_fmt = QERR_PROPERTY_READ_ONLY,
+        .desc      = "Property '%(device).%(property)' is read only",
+    },
+    {
         .error_fmt = QERR_PROPERTY_VALUE_BAD,
         .desc      = "Property '%(device).%(property)' doesn't take value '%(value)'",
     },
qerror.h +3 -0
index 8058456..eaabe6c 100644
@@ -145,6 +145,9 @@ QError *qobject_to_qerror(const QObject *obj);
 #define QERR_PROPERTY_NOT_FOUND \
     "{ 'class': 'PropertyNotFound', 'data': { 'device': %s, 'property': %s } }"
 
+#define QERR_PROPERTY_READ_ONLY \
+    "{ 'class': 'PropertyReadOnly', 'data': { 'device': %s, 'property': %s } }"
+
 #define QERR_PROPERTY_VALUE_BAD \
     "{ 'class': 'PropertyValueBad', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
 
qom/Makefile +1 -1
index 838054f..8a438d5 100644
@@ -1 +1 @@
-qom-obj-$(CONFIG_QOM) += type.o
+qom-obj-$(CONFIG_QOM) += type.o string-visitor.o plug.o plug-proptypes.o
qom/plug-proptypes.c new file +52 -0

52 lines not on this page · raw message

qom/plug.c new file +225 -0

225 lines not on this page · raw message

qom/string-visitor.c new file +41 -0

41 lines not on this page · raw message

qom/string-visitor.h new file +21 -0
new file mode 100644
index 0000000..ddee3e5
@@ -0,0 +1,21 @@
+#ifndef STRING_VISITOR_H
+#define STRING_VISITOR_H
+
+#include "qapi/qapi-visit-core.h"
+
+typedef struct StringInputVisitor
+{
+    Visitor parent;
+    const char *value;
+} StringInputVisitor;
+
+typedef struct StringOutputVisitor
+{
+    Visitor parent;
+    char value[256];
+} StringOutputVisitor;
+
+void string_input_visitor_init(StringInputVisitor *sv, const char *value);
+void string_output_visitor_init(StringOutputVisitor *sv);
+
+#endif
Signature · 1 line
1.7.4.1
#5 lore raw

PATCH 5/21 plug: add Plug property type

In reply to Anthony Liguori

Plug properties types allow composition within the object model. A plug is an object that is directly created from the current object, usually using the same memory as the current object.

Realize state is propagated to any plugs assocatied with the object. Lifecycle is also propagated such that when a plug is added, its automatically initialized and the plug is finalized when the parent object is finalized.

---
 include/qemu/plug.h |    4 ++
 qom/plug.c          |  104 +++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 108 insertions(+), 0 deletions(-)
include/qemu/plug.h +4 -0
index f6948a0..fdefa04 100644
@@ -68,6 +68,10 @@ bool plug_get_realized(Plug *plug);
 void plug_realize_all(Plug *plug);
 void plug_unrealize_all(Plug *plug);
 
+void plug_add_property_plug(Plug *plug, Plug *value, const char *typename, const char *name, ...);
+
+Plug *plug_get_property_plug(Plug *plug, Error **errp, const char *name, ...);
+
 #include "qemu/plug-proptypes.h"
 
 #endif
qom/plug.c +104 -0

122 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#6 lore raw

PATCH 6/21 plug: add socket property type

In reply to Anthony Liguori

Sockets form back links in the object graph. From the object's perspective, a socket just looks like a pointer to an object. The socket property type provides a generic mechanism to set those pointers to other objects while providing strong type checking.

It's also useful to lock sockets, particularly after realize. This allows for an object to enforce that a socket is programmed prior to realize and then not modified afterwards.

---
 include/qemu/plug.h |    2 +
 qom/plug.c          |   64 +++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 66 insertions(+), 0 deletions(-)
include/qemu/plug.h +2 -0
index fdefa04..a7ca985 100644
@@ -72,6 +72,8 @@ void plug_add_property_plug(Plug *plug, Plug *value, const char *typename, const
 
 Plug *plug_get_property_plug(Plug *plug, Error **errp, const char *name, ...);
 
+void plug_add_property_socket(Plug *plug, const char *name, Plug **value, const char *typename);
+
 #include "qemu/plug-proptypes.h"
 
 #endif
qom/plug.c +64 -0

70 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#7 lore raw

PATCH 7/21 plug: add generated property types

In reply to Anthony Liguori

Right now this uses the preprocessor and is vomit inducing. I think a python generator is in the near future.

---
 include/qemu/plug-proptypes.h |   29 +++++++++-
 include/qemu/plug.h           |    4 +-
 qom/plug-proptypes.c          |  119 ++++++++++++++++++++++++++++++++++++++++-
 qom/plug.c                    |   10 ++--
 4 files changed, 151 insertions(+), 11 deletions(-)
include/qemu/plug-proptypes.h +27 -2
index 2c7be0e..cf3e06e 100644
@@ -3,8 +3,33 @@
 
 #include "plug.h"
 
-typedef bool (PlugPropertyGetterBool)(Plug *plug);
-typedef void (PlugPropertySetterBool)(Plug *plug, bool value);
+#define CONCAT_I(a, b) a ## b
+#define CONCAT(a, b) CONCAT_I(a, b)
+
+#define GEN_PROP(ctype, typename, ctypename)                   \
+typedef ctype (CONCAT(PlugPropertyGetter, typename))(Plug *plug, Error **errp);  \
+typedef void (CONCAT(PlugPropertySetter, typename))(Plug *plug, ctype value, Error **errp); \
+ \
+void CONCAT(plug_add_property_, ctypename)(Plug *plug, const char *name, \
+                                           CONCAT(PlugPropertyGetter, typename) *getter, \
+                                           CONCAT(PlugPropertySetter, typename) *setter, \
+                                           int flags)
+
+GEN_PROP(int8_t, Int8, int8);
+GEN_PROP(int16_t, Int16, int16);
+GEN_PROP(int32_t, Int32, int32);
+GEN_PROP(int64_t, Int64, int64);
+GEN_PROP(uint8_t, UInt8, uint8);
+GEN_PROP(uint16_t, UInt16, uint16);
+GEN_PROP(uint32_t, UInt32, uint32);
+GEN_PROP(uint64_t, UInt64, uint64);
+GEN_PROP(int64_t, Int, int);
+GEN_PROP(const char *, Str, str);
+
+#undef GEN_PROP
+
+typedef bool (PlugPropertyGetterBool)(Plug *plug, Error **errp);
+typedef void (PlugPropertySetterBool)(Plug *plug, bool value, Error **errp);
 
 void plug_add_property_bool(Plug *plug, const char *name,
                             PlugPropertyGetterBool *getter,
include/qemu/plug.h +2 -2
index a7ca985..03b63a2 100644
@@ -62,8 +62,8 @@ void plug_unlock_property(Plug *plug, const char *name);
 void plug_lock_all_properties(Plug *plug);
 void plug_unlock_all_properties(Plug *plug);
 
-void plug_set_realized(Plug *plug, bool realized);
-bool plug_get_realized(Plug *plug);
+void plug_set_realized(Plug *plug, bool realized, Error **errp);
+bool plug_get_realized(Plug *plug, Error **errp);
 
 void plug_realize_all(Plug *plug);
 void plug_unrealize_all(Plug *plug);
qom/plug-proptypes.c +117 -2

140 lines not on this page · raw message

qom/plug.c +5 -5
index a9d8154..7f21c6b 100644
@@ -136,7 +136,7 @@ void plug_foreach_property(Plug *plug, PropertyEnumerator *enumfn, void *opaque)
     }
 }
 
-void plug_set_realized(Plug *plug, bool realized)
+void plug_set_realized(Plug *plug, bool realized, Error **errp)
 {
     PlugClass *class = PLUG_GET_CLASS(plug);
     bool old_value = plug->realized;
@@ -154,7 +154,7 @@ void plug_set_realized(Plug *plug, bool realized)
     }
 }
 
-bool plug_get_realized(Plug *plug)
+bool plug_get_realized(Plug *plug, Error **errp)
 {
     return plug->realized;
 }
@@ -180,7 +180,7 @@ static void plug_propagate_realized(Plug *plug, const char *name,
         child_name = plug_get_property_str(plug, name, NULL);
         child_plug = PLUG(type_find_by_id(child_name));
 
-        plug_set_realized(child_plug, plug_get_realized(plug));
+        plug_set_realized(child_plug, plug_get_realized(plug, NULL), NULL);
 
         qemu_free(child_name);
     }
@@ -329,7 +329,7 @@ void plug_realize_all(Plug *plug)
 {
     /* This doesn't loop infinitely because the callbacks are only called when
      * the state changes. */
-    plug_set_realized(plug, true);
+    plug_set_realized(plug, true, NULL);
     plug_lock_all_properties(plug);
     plug_foreach_property(plug, plug_propagate_realized, NULL);
 }
@@ -338,7 +338,7 @@ void plug_unrealize_all(Plug *plug)
 {
     /* This doesn't loop infinitely because the callbacks are only called when
      * the state changes. */
-    plug_set_realized(plug, false);
+    plug_set_realized(plug, false, NULL);
     plug_unlock_all_properties(plug);
     plug_foreach_property(plug, plug_propagate_realized, NULL);
 }
Signature · 1 line
1.7.4.1
#8 lore raw

PATCH 8/21 qom: add plug_create QMP command

In reply to Anthony Liguori
---
 monitor.c       |   49 +++++++++++++++++++++++++++++++++++++++++++++++++
 qmp-commands.hx |   27 +++++++++++++++++++++++++++
 2 files changed, 76 insertions(+), 0 deletions(-)
monitor.c +49 -0
index 718935b..8406b5b 100644
@@ -62,6 +62,12 @@
 #endif
 #include "ui/qemu-spice.h"
 
+#include "qemu/plug.h"
+#include "qapi/qmp-input-visitor.h"
+#include "qapi/qmp-output-visitor.h"
+
+#include <glib.h>
+
 //#define DEBUG
 //#define DEBUG_COMPLETION
 
@@ -1020,6 +1026,49 @@ static int do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
     return 0;
 }
 
+static GSList *global_plug_list;
+
+static int do_plug_create(Monitor *mon, const QDict *qdict, QObject **ret_data)
+{
+    const char *id = qdict_get_str(qdict, "id");
+    const char *type = qdict_get_str(qdict, "type");
+    QmpInputVisitor *qiv;
+    Visitor *v;
+    const QDictEntry *e;
+    TypeInstance *inst;
+    Plug *plug;
+
+    inst = type_new(type, id);
+    if (inst == NULL) {
+        return -1;
+    }
+
+    plug = PLUG(inst);
+
+    global_plug_list = g_slist_prepend(global_plug_list, plug);
+
+    qiv = qmp_input_visitor_new((QObject *)QOBJECT(qdict));
+    v = qmp_input_get_visitor(qiv);
+
+    for (e = qdict_first(qdict); e; e = qdict_next(qdict, e)) {
+        Error *local_err = NULL;
+
+        if (strcmp(e->key, "id") == 0 || strcmp(e->key, "type") == 0) {
+            continue;
+        }
+
+        plug_set_property(plug, e->key, v, &local_err);
+        if (local_err) {
+            error_free(local_err);
+            return -1;
+        }
+    }
+
+    qmp_input_visitor_cleanup(qiv);
+
+    return 0;
+}
+
 #ifdef CONFIG_VNC
 static int change_vnc_password(const char *password)
 {
qmp-commands.hx +27 -0
index 54e313c..c86d396 100644
@@ -85,6 +85,33 @@ Example:
 EQMP
 
     {
+        .name       = "plug_create",
+        .args_type  = "device:O",
+        .params     = "type=value,id=value[,prop=value][,...]",
+        .help       = "create a plug",
+        .user_print = monitor_user_noop,
+        .mhandler.cmd_new = do_plug_create,
+    },
+
+SQMP
+plug_create
+-----------
+
+Create a plug.
+
+Arguments:
+
+- type: typename of object (json-string)
+- id: name of object (json-string)
+- object properties
+
+Notes:
+
+ (1) id MUST not contain the sequence "::"
+
+EQMP
+
+    {
         .name       = "eject",
         .args_type  = "force:-f,device:B",
         .params     = "[-f] device",
Signature · 1 line
1.7.4.1
#9 lore raw

PATCH 9/21 qom: add plug_list QMP command

In reply to Anthony Liguori
---
 monitor.c       |   25 +++++++++++++++++++++++++
 qmp-commands.hx |    9 +++++++++
 2 files changed, 34 insertions(+), 0 deletions(-)
monitor.c +25 -0
index 8406b5b..f17eb3a 100644
@@ -1069,6 +1069,31 @@ static int do_plug_create(Monitor *mon, const QDict *qdict, QObject **ret_data)
     return 0;
 }
 
+static int do_plug_list(Monitor *mon, const QDict *qdict, QObject **ret_data)
+{
+    QList *qlist = qlist_new();
+    const char *type = qdict_get_try_str(qdict, "type");
+    GSList *i;
+
+    for (i = global_plug_list; i; i = i->next) {
+        TypeInstance *obj = i->data;
+        QDict *item = qdict_new();
+
+        if (type && !type_is_type(obj, type)) {
+            continue;
+        }
+
+        qdict_put(item, "id", qstring_from_str(type_get_id(obj)));
+        qdict_put(item, "type", qstring_from_str(type_get_type(obj)));
+
+        qlist_append(qlist, item);
+    }
+
+    *ret_data = QOBJECT(qlist);
+
+    return 0;
+}
+
 #ifdef CONFIG_VNC
 static int change_vnc_password(const char *password)
 {
qmp-commands.hx +9 -0
index c86d396..16f3f4d 100644
@@ -112,6 +112,15 @@ Notes:
 EQMP
 
     {
+        .name       = "plug_list",
+        .args_type  = "type:s?",
+        .params     = "",
+        .help       = "list plugs",
+        .user_print = monitor_user_noop,
+        .mhandler.cmd_new = do_plug_list,
+    },
+
+    {
         .name       = "eject",
         .args_type  = "force:-f,device:B",
         .params     = "[-f] device",
Signature · 1 line
1.7.4.1
#10 lore raw

PATCH 10/21 qom: add plug_get QMP command

In reply to Anthony Liguori
---
 monitor.c       |   35 +++++++++++++++++++++++++++++++++++
 qmp-commands.hx |    9 +++++++++
 2 files changed, 44 insertions(+), 0 deletions(-)
monitor.c +35 -0
index f17eb3a..1937e9f 100644
@@ -1094,6 +1094,41 @@ static int do_plug_list(Monitor *mon, const QDict *qdict, QObject **ret_data)
     return 0;
 }
 
+static int do_plug_get(Monitor *mon, const QDict *qdict, QObject **ret_data)
+{
+    const char *id = qdict_get_str(qdict, "id");
+    const char *name = qdict_get_str(qdict, "name");
+    Error *local_err = NULL;
+    QmpOutputVisitor *qov;
+    TypeInstance *inst;
+    Plug *plug;
+    Visitor *v;
+
+    qov = qmp_output_visitor_new();
+    v = qmp_output_get_visitor(qov);
+
+    inst = type_find_by_id(id);
+    if (inst == NULL) {
+        return -1;
+    }
+
+    plug = PLUG(inst);
+
+    plug_get_property(plug, name, v, &local_err);
+    if (local_err) {
+        error_free(local_err);
+        qmp_output_visitor_cleanup(qov);
+
+        return -1;
+    }
+
+    *ret_data = qmp_output_get_qobject(qov);
+
+    qmp_output_visitor_cleanup(qov);
+
+    return 0;
+}
+
 #ifdef CONFIG_VNC
 static int change_vnc_password(const char *password)
 {
qmp-commands.hx +9 -0
index 16f3f4d..822d422 100644
@@ -121,6 +121,15 @@ EQMP
     },
 
     {
+        .name       = "plug_get",
+        .args_type  = "options:O",
+        .params     = "",
+        .help       = "get plug property",
+        .user_print = monitor_user_noop,
+        .mhandler.cmd_new = do_plug_get,
+    },
+
+    {
         .name       = "eject",
         .args_type  = "force:-f,device:B",
         .params     = "[-f] device",
Signature · 1 line
1.7.4.1
#11 lore raw

PATCH 11/21 qom: add plug_set QMP command

In reply to Anthony Liguori
---
 monitor.c       |   33 +++++++++++++++++++++++++++++++++
 qmp-commands.hx |    9 +++++++++
 2 files changed, 42 insertions(+), 0 deletions(-)
monitor.c +33 -0
index 1937e9f..47011dd 100644
@@ -1129,6 +1129,39 @@ static int do_plug_get(Monitor *mon, const QDict *qdict, QObject **ret_data)
     return 0;
 }
 
+static int do_plug_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
+{
+    const char *id = qdict_get_str(qdict, "id");
+    const char *name = qdict_get_str(qdict, "name");
+    QObject *value = qdict_get(qdict, "value");
+    Error *local_err = NULL;
+    QmpInputVisitor *qiv;
+    TypeInstance *inst;
+    Plug *plug;
+    Visitor *v;
+
+    qiv = qmp_input_visitor_new(value);
+    v = qmp_input_get_visitor(qiv);
+
+    inst = type_find_by_id(id);
+    if (inst == NULL) {
+        return -1;
+    }
+
+    plug = PLUG(inst);
+
+    plug_set_property(plug, name, v, &local_err);
+    if (local_err) {
+        error_free(local_err);
+        qmp_input_visitor_cleanup(qiv);
+        return -1;
+    }
+
+    qmp_input_visitor_cleanup(qiv);
+
+    return 0;
+}
+
 #ifdef CONFIG_VNC
 static int change_vnc_password(const char *password)
 {
qmp-commands.hx +9 -0
index 822d422..1d7e87b 100644
@@ -130,6 +130,15 @@ EQMP
     },
 
     {
+        .name       = "plug_set",
+        .args_type  = "options:O",
+        .params     = "",
+        .help       = "set plug property",
+        .user_print = monitor_user_noop,
+        .mhandler.cmd_new = do_plug_set,
+    },
+
+    {
         .name       = "eject",
         .args_type  = "force:-f,device:B",
         .params     = "[-f] device",
Signature · 1 line
1.7.4.1
#12 lore raw

PATCH 12/21 qom: add plug_list_props QMP command

In reply to Anthony Liguori
---
 monitor.c       |   35 +++++++++++++++++++++++++++++++++++
 qmp-commands.hx |    9 +++++++++
 2 files changed, 44 insertions(+), 0 deletions(-)
monitor.c +35 -0
index 47011dd..e53808a 100644
@@ -1162,6 +1162,41 @@ static int do_plug_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
     return 0;
 }
 
+static void plug_list_props_tramp(Plug *plug, const char *name, const char *typename, int flags, void *opaque)
+{
+    QList *qlist = opaque;
+    QDict *item = qdict_new();
+
+    qdict_put(item, "name", qstring_from_str(name));
+    qdict_put(item, "type", qstring_from_str(typename));
+    qdict_put(item, "readable", qbool_from_int(!!(flags & PROP_F_READ)));
+    qdict_put(item, "writeable", qbool_from_int(!!(flags & PROP_F_WRITE)));
+    qdict_put(item, "locked", qbool_from_int(!!(flags & PROP_F_LOCKED)));
+
+    qlist_append(qlist, item);
+}
+
+static int do_plug_list_props(Monitor *mon, const QDict *qdict, QObject **ret_data)
+{
+    const char *id = qdict_get_str(qdict, "id");
+    QList *qlist = qlist_new();
+    TypeInstance *inst;
+    Plug *plug;
+
+    inst = type_find_by_id(id);
+    if (inst == NULL) {
+        return -1;
+    }
+
+    plug = PLUG(inst);
+
+    plug_foreach_property(plug, plug_list_props_tramp, qlist);
+
+    *ret_data = QOBJECT(qlist);
+
+    return 0;
+}
+
 #ifdef CONFIG_VNC
 static int change_vnc_password(const char *password)
 {
qmp-commands.hx +9 -0
index 1d7e87b..6f1091b 100644
@@ -139,6 +139,15 @@ EQMP
     },
 
     {
+        .name       = "plug_list_props",
+        .args_type  = "id:s",
+        .params     = "",
+        .help       = "list plug properties",
+        .user_print = monitor_user_noop,
+        .mhandler.cmd_new = do_plug_list_props,
+    },
+
+    {
         .name       = "eject",
         .args_type  = "force:-f,device:B",
         .params     = "[-f] device",
Signature · 1 line
1.7.4.1
#13 lore raw

PATCH 13/21 qom: add plug_destroy command

In reply to Anthony Liguori
---
 monitor.c       |   20 ++++++++++++++++++++
 qmp-commands.hx |    9 +++++++++
 2 files changed, 29 insertions(+), 0 deletions(-)
monitor.c +20 -0
index e53808a..549251a 100644
@@ -1069,6 +1069,26 @@ static int do_plug_create(Monitor *mon, const QDict *qdict, QObject **ret_data)
     return 0;
 }
 
+static int do_plug_destroy(Monitor *mon, const QDict *qdict, QObject **ret_data)
+{
+    const char *id = qdict_get_str(qdict, "id");
+    TypeInstance *inst;
+    Plug *plug;
+
+    inst = type_find_by_id(id);
+    if (inst == NULL) {
+        return -1;
+    }
+
+    plug = PLUG(inst);
+
+    global_plug_list = g_slist_remove(global_plug_list, plug);
+
+    type_delete(inst);
+
+    return 0;
+}
+
 static int do_plug_list(Monitor *mon, const QDict *qdict, QObject **ret_data)
 {
     QList *qlist = qlist_new();
qmp-commands.hx +9 -0
index 6f1091b..8203371 100644
@@ -112,6 +112,15 @@ Notes:
 EQMP
 
     {
+        .name       = "plug_destroy",
+        .args_type  = "type:s",
+        .params     = "type=value",
+        .help       = "destroy a plug",
+        .user_print = monitor_user_noop,
+        .mhandler.cmd_new = do_plug_destroy,
+    },
+
+    {
         .name       = "plug_list",
         .args_type  = "type:s?",
         .params     = "",
Signature · 1 line
1.7.4.1
#14 lore raw

PATCH 14/21 qom: add example qsh command

In reply to Anthony Liguori

This lets you explore the QEMU Object Model with a filesystem like interface.

---
 scripts/qsh |  178 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 178 insertions(+), 0 deletions(-)
 create mode 100755 scripts/qsh
scripts/qsh new file +178 -0
new file mode 100755
index 0000000..b4b5e94
@@ -0,0 +1,178 @@
+#!/usr/bin/python
+
+import json, socket
+import sys
+
+class QmpException(Exception):
+    def __init__(self, cls, desc):
+        Exception.__init__(self, desc)
+
+class QmpClient(object):
+    def __init__(self, host, port):
+        s = socket.socket(socket.AF_INET)
+        s.connect((host, port))
+
+        self.s = s
+        self.buffer = ''
+        self.readline()
+
+    def readline(self):
+        while not self.buffer.find('\n') != -1:
+            self.buffer += self.s.recv(1024)
+
+        line, self.buffer = self.buffer.split('\n', 1)
+        return line
+
+    def _command(self, _command_name, **args):
+        req = { "execute": _command_name, "arguments": args }
+        self.s.sendall(json.dumps(req))
+        
+        rsp = json.loads(self.readline())
+        if rsp.has_key('error'):
+            raise QmpException(rsp['error']['class'], rsp['error']['desc'])
+        return rsp['return']
+
+    def qmp_capabilities(self):
+        return self._command('qmp_capabilities')
+
+    def plug_create(self, typename, name, **args):
+        self._command('plug_create', id=name, type=typename, **args)
+
+    def plug_list(self, typename=None):
+        if typename == None:
+            return self._command('plug_list')
+        else:
+            return self._command('plug_list', type=typename)
+
+    def plug_get(self, name, propname):
+        return self._command('plug_get', id=name, name=propname)
+
+    def plug_set(self, name, propname, value):
+        self._command('plug_set', id=name, name=propname, value=value)
+
+    def plug_list_props(self, name):
+        return self._command('plug_list_props', id=name)
+
+    def quit(self):
+        self._command('quit')
+
+from ConfigParser import SafeConfigParser
+import re
+
+class GitConfigParser(SafeConfigParser):
+    SECTCRE = re.compile(r'\[(?P<header>[^\"]+"[^"]*")\]')
+
+
+def resolve_property(qmp, value):
+    value = value[1:]
+
+    components = value.split('/')
+
+    name = components[0]
+    components = components[1:]
+
+    prop = components[-1]
+    for component in components[:-1]:
+        if component.startswith('@'):
+            component = component[1:]
+        name = qmp.plug_get(name, component)
+
+    if prop.startswith('@'):
+        prop = prop[1:]
+
+    return name, prop
+
+def parse_property(srv, value):
+    if value == 'True':
+        value = True
+    elif value == 'False':
+        value = False
+    elif value[0] in '0123456789-':
+        value = int(value)
+    elif value[0] == '/':
+        name, prop = resolve_property(srv, value)
+        value = qmp.plug_get(name, prop)
+    elif value[0] == '"':
+        value = value[1:-1]
+    return value
+
+qmp = QmpClient('localhost', 8080)
+qmp.qmp_capabilities()
+
+command = sys.argv[1]
+
+if command == 'import':    
+    cp = GitConfigParser()
+    cp.read([sys.argv[2]])
+
+    for section in cp.sections():
+        kind, name = section.split(' ', 1)
+        name = name[1:-1]
+        qmp.plug_create(kind, name)
+
+    for section in cp.sections():
+        kind, name = section.split(' ', 1)
+        name = name[1:-1]
+
+        for key, value in cp.items(section):
+            value = parse_property(qmp, value)
+            qmp.plug_set(name, key, value)
+elif command == 'create':
+    if len(sys.argv) != 4:
+        sys.exit(1)
+    qmp.plug_create(sys.argv[2], sys.argv[3])
+elif command == 'exit':
+    qmp.quit()
+elif command == 'set':
+    if len(sys.argv) != 4:
+        sys.exit(1)
+
+    name, prop = resolve_property(qmp, sys.argv[2])
+
+    value = parse_property(qmp, sys.argv[3])
+    qmp.plug_set(name, prop, value)
+elif command == 'get':
+    if len(sys.argv) != 3:
+        sys.exit(1)
+
+    name, prop = resolve_property(qmp, sys.argv[2])
+    print qmp.plug_get(name, prop)
+elif command == 'plug_list':
+    if len(sys.argv) != 3:
+        sys.exit(1)
+
+    items = qmp.plug_list(sys.argv[2])
+    for i in items:
+        print i
+elif command == 'ls':
+    if len(sys.argv) != 3:
+        sys.exit(1)
+
+    path = sys.argv[2]
+
+    while path.endswith('/'):
+        path = path[:-1]
+
+    if path == '':
+        path = '/'
+
+    if path == '/':
+        items = qmp.plug_list()
+        for item in items:
+            print '%s/' % item['id']
+    else:
+        if path[1:].find('/') == -1:
+            items = qmp.plug_list_props(path[1:])
+        else:
+            name, prop = resolve_property(qmp, path)
+            name = qmp.plug_get(name, prop)
+            items = qmp.plug_list_props(name)
+
+        for item in items:
+            if item['type'].startswith('plug<'):
+                print '%s/' % item['name']
+            elif item['type'].startswith('socket<'):
+                print '@%s/' % item['name']
+            else:
+                print '%s' % item['name']
+
Signature · 1 line
1.7.4.1
#15 lore raw

PATCH 15/21 qom: add Device class

In reply to Anthony Liguori

Device is meant to replace DeviceState as the root class for the device model. This is included here merely as a RFC. Device adds a couple of useful features.

1) Default hard reset. Device will literally call finalize on the object and then reinitialize it in place. This means that most devices don't have to worry about implementing reset logic.

Reset preserves the current state of properties which makes it equivalent to taking the properties of the current device and then initializing a new object using those properties.

2) Full object serialization as a property. The 'state' property is special in that it will invoke a visit method that's intended to be overridden by a subclass. The visit method will visit the full object.

This exists to enable live migration. Notice that there is no mention of compatibility, versioning, subsections, etc. The idea behind supporting robust migration is that the device model is only responsible for generating the state of the current device model, the structure of the device model, and the current set of properties.

The expectation is that another layer will perform transformations of the resulting tree to preserve migration compatibility. Tree transformation is a powerful mechanism and even with a totally different device model, this should enable us to support migration compatibility even to the current VMState based migration code.

---
 Makefile.qom          |    3 +
 Qconfig               |    1 +
 configure             |    2 +-
 devices/Makefile      |    1 +
 devices/Qconfig       |    6 ++
 devices/device.c      |  125 +++++++++++++++++++++++++++++++++++++++++++++++++
 include/qemu/device.h |   28 +++++++++++
 7 files changed, 165 insertions(+), 1 deletions(-)
 create mode 100644 devices/Makefile
 create mode 100644 devices/Qconfig
 create mode 100644 devices/device.c
 create mode 100644 include/qemu/device.h
Makefile.qom +3 -0
index 34f1f91..c694cbb 100644
@@ -13,3 +13,6 @@ common-obj-y += $(addprefix qapi/,$(qapi-obj-y))
 include $(SRC_PATH)/qom/Makefile
 common-obj-y += $(addprefix qom/,$(qom-obj-y))
 
+include $(SRC_PATH)/devices/Makefile
+common-obj-y += $(addprefix devices/,$(devices-obj-y))
+
Qconfig +1 -0
index 889dfa6..03f2a87 100644
@@ -1,2 +1,3 @@
 source qapi/Qconfig
 source qom/Qconfig
+source devices/Qconfig
configure +1 -1
index 93e5e97..6ec1020 100755
@@ -3516,7 +3516,7 @@ DIRS="$DIRS pc-bios/spapr-rtas"
 DIRS="$DIRS roms/seabios roms/vgabios"
 DIRS="$DIRS fsdev ui"
 DIRS="$DIRS qapi"
-DIRS="$DIRS qga qom"
+DIRS="$DIRS qga qom devices"
 FILES="Makefile tests/Makefile"
 FILES="$FILES tests/cris/Makefile tests/cris/.gdbinit"
 FILES="$FILES pc-bios/optionrom/Makefile pc-bios/keymaps"
devices/Makefile new file +1 -0
new file mode 100644
index 0000000..fbb0b82
@@ -0,0 +1 @@
+devices-obj-$(CONFIG_DEVICE) := device.o
devices/Qconfig new file +6 -0
new file mode 100644
index 0000000..6a06417
@@ -0,0 +1,6 @@
+config DEVICE
+       bool "QOM based device model"
+       default y
+       depends on QOM && QAPI_QMP
+       help
+         Device model
devices/device.c new file +125 -0

125 lines not on this page · raw message

include/qemu/device.h new file +28 -0
new file mode 100644
index 0000000..8e15232
@@ -0,0 +1,28 @@
+#ifndef DEVICE_H
+#define DEVICE_H
+
+#include "qemu/plug.h"
+
+typedef struct Device
+{
+    Plug parent;
+} Device;
+
+typedef void (DeviceVisitor)(Device *device, Visitor *v, const char *name, Error **errp);
+
+typedef struct DeviceClass
+{
+    PlugClass parent_class;
+
+    /* public */
+    DeviceVisitor *visit;
+} DeviceClass;
+
+#define TYPE_DEVICE "device"
+#define DEVICE(obj) TYPE_CHECK(Device, obj, TYPE_DEVICE)
+#define DEVICE_CLASS(class) TYPE_CLASS_CHECK(DeviceClass, class, TYPE_DEVICE)
+#define DEVICE_GET_CLASS(obj) TYPE_GET_CLASS(DeviceClass, obj, TYPE_DEVICE)
+
+void device_visit(Device *device, Visitor *v, const char *name, Error **errp);
+
+#endif
Signature · 1 line
1.7.4.1
#16 lore raw

Re: [Qemu-devel] [PATCH 15/21] qom: add Device class

Quoted 6 lines · Anthony Liguori

Device is meant to replace DeviceState as the root class for the device model. This is included here merely as a RFC.  Device adds a couple of useful features.

1) Default hard reset.  Device will literally call finalize on the object and then reinitialize it in place.  This means that most devices don't have to worry about implementing reset logic.

I like having a reset implemented as "just reinstantiate everything", but this only really covers one of the different reset flavours ("simulation reset", ie "give me a system in the same state as if I'd just started qemu from scratch"). I think devices are still going to need to implement "simulated reset", which is what they do when the core causes a simulated reset signal to go active (and which ought really to be implemented by having an incoming gpio signal 'reset'). The two are not always identical, and you don't necessarily want to reset the whole of the model at once... (And then some devices have another level of 'soft reset' which you get by writing to one of its registers.)

...all of which isn't particularly relevant to the object/device model, but I just wanted to say "reset isn't quite that simple" :-)

-- PMM

#17 lore raw

Re: [Qemu-devel] [PATCH 15/21] qom: add Device class

Quoted 8 lines · Peter Maydell
Quoted 6 lines · Anthony Liguori

Device is meant to replace DeviceState as the root class for the device model. This is included here merely as a RFC. Device adds a couple of useful features.

1) Default hard reset. Device will literally call finalize on the object and then reinitialize it in place. This means that most devices don't have to worry about implementing reset logic.

Quoted 7 lines

I like having a reset implemented as "just reinstantiate everything", but this only really covers one of the different reset flavours ("simulation reset", ie "give me a system in the same state as if I'd just started qemu from scratch"). I think devices are still going to need to implement "simulated reset", which is what they do when the core causes a simulated reset signal to go active (and which ought really to be implemented by having an incoming gpio signal 'reset').

reset is implemented as an edge of the realized property which is basically a pin.

I view realized as the Vcc pin. In fact, I named it as such originally but thought that was too obscure :-)

realize() is when Vcc goes high, unrealize/reset is when Vcc goes low. In terms of the very base Device class, there really is only one Vcc pin. For other types of devices, there might be multiple types of pins that have reset semantics.

Quoted 7 lines

The two are not always identical,
and you don't necessarily want to reset the whole of the model at once... (And then some devices have another level of 'soft reset' which you get by writing to one of its registers.)

...all of which isn't particularly relevant to the object/device model, but I just wanted to say "reset isn't quite that simple" :-)

Am very well aware, and tried to accommodate this. It's not modelled as a Pin because a Pin is a Device and it turns out that the notion of realized is also useful for non-Device objects.

Regards,

Anthony Liguori

Quoted 2 lines

-- PMM

#18 lore raw

PATCH 16/21 qom-devices: add a Pin class

In reply to Anthony Liguori
---
 devices/Makefile   |    2 +-
 devices/pin.c      |   69 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 include/qemu/pin.h |   28 +++++++++++++++++++++
 3 files changed, 98 insertions(+), 1 deletions(-)
 create mode 100644 devices/pin.c
 create mode 100644 include/qemu/pin.h
devices/Makefile +1 -1
index fbb0b82..fa52689 100644
@@ -1 +1 @@
-devices-obj-$(CONFIG_DEVICE) := device.o
+devices-obj-$(CONFIG_DEVICE) := device.o pin.o
devices/pin.c new file +69 -0

69 lines not on this page · raw message

include/qemu/pin.h new file +28 -0
new file mode 100644
index 0000000..e8f2582
@@ -0,0 +1,28 @@
+#ifndef PIN_H
+#define PIN_H
+
+#include "qemu/device.h"
+#include "notify.h"
+
+typedef struct Pin
+{
+    Device parent;
+
+    /* private */
+    bool level;
+
+    /* FIXME */
+    NotifierList level_changed;
+} Pin;
+
+#define TYPE_PIN "pin"
+#define PIN(obj) TYPE_CHECK(Pin, obj, TYPE_PIN)
+
+void pin_initialize(Pin *pin, const char *id);
+void pin_finalize(Pin *pin);
+void pin_visit(Pin *pin, Visitor *v, const char *name, Error **errp);
+
+void pin_set_level(Pin *pin, bool value, Error **errp);
+bool pin_get_level(Pin *pin, Error **errp);
+
+#endif
Signature · 1 line
1.7.4.1
#19 lore raw

PATCH 17/21 qom: add CharDriver class

In reply to Anthony Liguori

The CharDriver type replaces the CharDriverState in QEMU today. Here's how everything matches up:

1) qemu_chr_open() no longer exists. This function used to act as a factory and used parsing of the filename to determine which type to create. A newer version using QemuOpts was introduced, qemu_chr_open_opts() which eliminates the filename in favor of typed key value pairs.

Now, plug_create() can be used to create CharDrivers using an explicit type that subclasses CharDriver.

2) query-chardev is deprecated. This is replaced by plug_list(type=char-driver) and plug_list_props().

3) We can now dynamically add and remove new CharDrivers

---
 Makefile.qom          |    3 +
 Qconfig               |    1 +
 chrdrv/Makefile       |    1 +
 chrdrv/Qconfig        |    5 +
 chrdrv/chrdrv.c       |  229 ++++++++++++++++++++++++++++++++++++++++
 configure             |    2 +-
 include/qemu/chrdrv.h |  281 +++++++++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 521 insertions(+), 1 deletions(-)
 create mode 100644 chrdrv/Makefile
 create mode 100644 chrdrv/Qconfig
 create mode 100644 chrdrv/chrdrv.c
 create mode 100644 include/qemu/chrdrv.h
Makefile.qom +3 -0
index c694cbb..02a5ca5 100644
@@ -16,3 +16,6 @@ common-obj-y += $(addprefix qom/,$(qom-obj-y))
 include $(SRC_PATH)/devices/Makefile
 common-obj-y += $(addprefix devices/,$(devices-obj-y))
 
+include $(SRC_PATH)/chrdrv/Makefile
+common-obj-y += $(addprefix chrdrv/,$(chrdrv-obj-y))
+
Qconfig +1 -0
index 03f2a87..57c1c7d 100644
@@ -1,3 +1,4 @@
 source qapi/Qconfig
 source qom/Qconfig
 source devices/Qconfig
+source chrdrv/Qconfig
chrdrv/Makefile new file +1 -0
new file mode 100644
index 0000000..43a51e7
@@ -0,0 +1 @@
+chrdrv-obj-$(CONFIG_CHRDRV) := chrdrv.o
chrdrv/Qconfig new file +5 -0
new file mode 100644
index 0000000..845c205
@@ -0,0 +1,5 @@
+config CHRDRV
+       bool "QEMU Character Drivers"
+       default y
+       help
+         Character layer
chrdrv/chrdrv.c new file +229 -0

229 lines not on this page · raw message

configure +1 -1
index 6ec1020..63c62b0 100755
@@ -3516,7 +3516,7 @@ DIRS="$DIRS pc-bios/spapr-rtas"
 DIRS="$DIRS roms/seabios roms/vgabios"
 DIRS="$DIRS fsdev ui"
 DIRS="$DIRS qapi"
-DIRS="$DIRS qga qom devices"
+DIRS="$DIRS qga qom devices chrdrv"
 FILES="Makefile tests/Makefile"
 FILES="$FILES tests/cris/Makefile tests/cris/.gdbinit"
 FILES="$FILES pc-bios/optionrom/Makefile pc-bios/keymaps"
include/qemu/chrdrv.h new file +281 -0

281 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#20 lore raw

PATCH 18/21 qom-chrdrv: add memory character driver

In reply to Anthony Liguori

This is used primarly by QMP.

---
 chrdrv/Makefile       |    1 +
 chrdrv/Qconfig        |    7 +++++
 chrdrv/memchr.c       |   70 +++++++++++++++++++++++++++++++++++++++++++++++++
 include/qemu/memchr.h |   46 ++++++++++++++++++++++++++++++++
 4 files changed, 124 insertions(+), 0 deletions(-)
 create mode 100644 chrdrv/memchr.c
 create mode 100644 include/qemu/memchr.h
chrdrv/Makefile +1 -0
index 43a51e7..6cfdd27 100644
@@ -1 +1,2 @@
 chrdrv-obj-$(CONFIG_CHRDRV) := chrdrv.o
+chrdrv-obj-$(CONFIG_CHRDRV_MEM) += memchr.o
chrdrv/Qconfig +7 -0
index 845c205..f3f939e 100644
@@ -3,3 +3,10 @@ config CHRDRV
        default y
        help
          Character layer
+
+config CHRDRV_MEM
+       bool "Memory character device"
+       default y
+       depends on CHRDRV
+       help
+         Character device that stores all written data to a memory buffer.
chrdrv/memchr.c new file +70 -0

70 lines not on this page · raw message

include/qemu/memchr.h new file +46 -0

46 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#21 lore raw

PATCH 19/21 qom-chrdrv: add Socket base class

In reply to Anthony Liguori

This introduces two classed, SocketCharDriver and SocketServer. SocketCharDriver implements the generic logic for all socket based transports. SocketServer implements the necessary functionality for server-based socket transports.

Unlike the previous socket CharDriverState, there is no magic overloading based on passed options. You have to explicitly create types of socket CharDrivers for TCP or Unix domain sockets.

---
 chrdrv/Makefile          |    1 +
 chrdrv/Qconfig           |    7 ++
 chrdrv/socketchr.c       |  250 ++++++++++++++++++++++++++++++++++++++++++++++
 include/qemu/socketchr.h |  109 ++++++++++++++++++++
 4 files changed, 367 insertions(+), 0 deletions(-)
 create mode 100644 chrdrv/socketchr.c
 create mode 100644 include/qemu/socketchr.h
chrdrv/Makefile +1 -0
index 6cfdd27..84bff48 100644
@@ -1,2 +1,3 @@
 chrdrv-obj-$(CONFIG_CHRDRV) := chrdrv.o
 chrdrv-obj-$(CONFIG_CHRDRV_MEM) += memchr.o
+chrdrv-obj-$(CONFIG_CHRDRV_SOCKET) += socketchr.o
chrdrv/Qconfig +7 -0
index f3f939e..417c063 100644
@@ -10,3 +10,10 @@ config CHRDRV_MEM
        depends on CHRDRV
        help
          Character device that stores all written data to a memory buffer.
+
+config CHRDRV_SOCKET
+       bool "Socket character driver"
+       default y
+       depends on CHRDRV
+       help
+         Character driver that implements a socket based transport.
chrdrv/socketchr.c new file +250 -0

250 lines not on this page · raw message

include/qemu/socketchr.h new file +109 -0

109 lines not on this page · raw message

Signature · 1 line
1.7.4.1
#22 lore raw

PATCH 20/21 qom-chrdrv: add TCPServer class

In reply to Anthony Liguori

This is roughly equivalent to -chardev socket,path=PATH,port=PORT,server=on

---
 chrdrv/Makefile       |    1 +
 chrdrv/Qconfig        |    7 ++
 chrdrv/tcpsrv.c       |  203 +++++++++++++++++++++++++++++++++++++++++++++++++
 include/qemu/tcpsrv.h |   40 ++++++++++
 4 files changed, 251 insertions(+), 0 deletions(-)
 create mode 100644 chrdrv/tcpsrv.c
 create mode 100644 include/qemu/tcpsrv.h
chrdrv/Makefile +1 -0
index 84bff48..50a3d50 100644
@@ -1,3 +1,4 @@
 chrdrv-obj-$(CONFIG_CHRDRV) := chrdrv.o
 chrdrv-obj-$(CONFIG_CHRDRV_MEM) += memchr.o
 chrdrv-obj-$(CONFIG_CHRDRV_SOCKET) += socketchr.o
+chrdrv-obj-$(CONFIG_CHRDRV_TCP_SERVER) += tcpsrv.o
chrdrv/Qconfig +7 -0
index 417c063..ea22b50 100644
@@ -17,3 +17,10 @@ config CHRDRV_SOCKET
        depends on CHRDRV
        help
          Character driver that implements a socket based transport.
+
+config CHRDRV_TCP_SERVER
+       bool "TCP server character driver"
+       default y
+       depends on CHRDRV_SOCKET
+       help
+         Character driver that implements a TCP server transport.
chrdrv/tcpsrv.c new file +203 -0

203 lines not on this page · raw message

include/qemu/tcpsrv.h new file +40 -0
new file mode 100644
index 0000000..c398483
@@ -0,0 +1,40 @@
+#ifndef CHAR_DRIVER_TCP_H
+#define CHAR_DRIVER_TCP_H
+
+#include "qemu/socketchr.h"
+#include "qemu_socket.h"
+
+typedef struct TcpServer
+{
+    SocketServer parent;
+
+    struct sockaddr_in peer;
+
+    char *host;
+    char *port;
+
+    bool ipv4;
+    bool ipv6;
+} TcpServer;
+
+#define TYPE_TCP_SERVER "tcp-server"
+#define TCP_SERVER(obj) TYPE_CHECK(TcpServer, obj, TYPE_TCP_SERVER)
+
+void tcp_server_initialize(TcpServer *obj, const char *id);
+void tcp_server_finalize(TcpServer *obj);
+
+const char *tcp_server_get_host(TcpServer *obj, Error **errp);
+void tcp_server_set_host(TcpServer *obj, const char *value, Error **errp);
+
+const char *tcp_server_get_port(TcpServer *obj, Error **errp);
+void tcp_server_set_port(TcpServer *obj, const char *value, Error **errp);
+
+bool tcp_server_get_ipv4(TcpServer *obj, Error **errp);
+void tcp_server_set_ipv4(TcpServer *obj, bool value, Error **errp);
+
+bool tcp_server_get_ipv6(TcpServer *obj, Error **errp);
+void tcp_server_set_ipv6(TcpServer *obj, bool value, Error **errp);
+
+const char *tcp_server_get_peername(TcpServer *obj, Error **errp);
+
+#endif
Signature · 1 line
1.7.4.1
#23 lore raw

PATCH 21/21 qom-chrdrv: add UnixServer

In reply to Anthony Liguori

This is roughly equivalent to -chardev socket,path=PATH,server=on

---
 chrdrv/Makefile        |    1 +
 chrdrv/Qconfig         |    7 +++
 chrdrv/unixsrv.c       |  104 ++++++++++++++++++++++++++++++++++++++++++++++++
 include/qemu/unixsrv.h |   24 +++++++++++
 4 files changed, 136 insertions(+), 0 deletions(-)
 create mode 100644 chrdrv/unixsrv.c
 create mode 100644 include/qemu/unixsrv.h
chrdrv/Makefile +1 -0
index 50a3d50..43e516f 100644
@@ -2,3 +2,4 @@ chrdrv-obj-$(CONFIG_CHRDRV) := chrdrv.o
 chrdrv-obj-$(CONFIG_CHRDRV_MEM) += memchr.o
 chrdrv-obj-$(CONFIG_CHRDRV_SOCKET) += socketchr.o
 chrdrv-obj-$(CONFIG_CHRDRV_TCP_SERVER) += tcpsrv.o
+chrdrv-obj-$(CONFIG_CHRDRV_UNIX_SERVER) += unixsrv.o
chrdrv/Qconfig +7 -0
index ea22b50..ae2c20e 100644
@@ -24,3 +24,10 @@ config CHRDRV_TCP_SERVER
        depends on CHRDRV_SOCKET
        help
          Character driver that implements a TCP server transport.
+
+config CHRDRV_UNIX_SERVER
+       bool "UNIX server character driver"
+       default y
+       depends on CHRDRV_SOCKET && UNIX
+       help
+         Character driver that implements a domain socket server transport.
chrdrv/unixsrv.c new file +104 -0

104 lines not on this page · raw message

include/qemu/unixsrv.h new file +24 -0
new file mode 100644
index 0000000..71182bc
@@ -0,0 +1,24 @@
+#ifndef CHAR_DRIVER_UNIX_H
+#define CHAR_DRIVER_UNIX_H
+
+#include "qemu/socketchr.h"
+#include "qemu_socket.h"
+
+typedef struct UnixServer
+{
+    SocketServer parent;
+
+    /* private */
+    char *path;
+} UnixServer;
+
+#define TYPE_UNIX_SERVER "unix-server"
+#define UNIX_SERVER(obj) TYPE_CHECK(UnixServer, obj, TYPE_UNIX_SERVER)
+
+void unix_server_initialize(UnixServer *obj, const char *id);
+void unix_server_finalize(UnixServer *obj);
+
+const char *unix_server_get_path(UnixServer *obj, Error **errp);
+void unix_server_set_path(UnixServer *obj, const char *value, Error **errp);
+
+#endif
Signature · 1 line
1.7.4.1
#24 lore raw
In reply to Anthony Liguori

Am 25.07.2011 03:44, schrieb Anthony Liguori:

Quoted 13 lines

Hi,

This series is the rough beginnings of the QEMU Object Model. This is basically qdev generalized on steroids.

This series includes the core infrastructure, a strawman Device type, and the beginnings of the conversion of CharDriverState. This is in a rougher state than I would like it to be but I wanted to get the concepts on the list as soon as possible.

My plan is to drop the Device parts from future versions of the series and just focus on backends to start with.

Quoted 7 lines

Please note that this series has an awful lot of ramifications. Most of our current command line options would become deprecated, the build system will change significantly, and a lot of our QMP functions will become deprecated.

It seems like a lot of change, but hopefully this series illustrates how we can do it very incrementally with value being added at each stage of the conversion.

I haven't looked in much detail at it yet, but it has still the same problem I was talking about last week: Patches 17-21 don't actually convert existing code, but they add new code. This means that we can't review only the changes, but have to review the whole code. It also makes conflicts with patches modifying the old version hard to even notice.

On another note, I'm not so sure if your renaming is really helpful. It doesn't matter that much with qemu-char because someone thought having the function pointers in CharDriverState was a good idea, but if you're consistent, the rename would go like this in the block layer:

BlockDriverState -> BlockDriver
BlockDriver -> BlockDriverClass

IMHO, that's not very helpful, but just going to create confusion. We could probably discuss other parts of the terminology, too, but let's save the bikeshedding for later.

Kevin

#25 lore raw
Quoted 18 lines · Kevin Wolf

Am 25.07.2011 03:44, schrieb Anthony Liguori:

Quoted 17 lines

Hi,

This series is the rough beginnings of the QEMU Object Model. This is basically qdev generalized on steroids.

This series includes the core infrastructure, a strawman Device type, and the beginnings of the conversion of CharDriverState. This is in a rougher state than I would like it to be but I wanted to get the concepts on the list as soon as possible.

My plan is to drop the Device parts from future versions of the series and just focus on backends to start with.

Please note that this series has an awful lot of ramifications. Most of our current command line options would become deprecated, the build system will change significantly, and a lot of our QMP functions will become deprecated.

Quoted 7 lines
Quoted 3 lines

It seems like a lot of change, but hopefully this series illustrates how we can do it very incrementally with value being added at each stage of the conversion.

I haven't looked in much detail at it yet, but it has still the same problem I was talking about last week: Patches 17-21 don't actually convert existing code, but they add new code.

Actually, it's mostly existing code. In terms of incremental conversion, the most straight forward way is to adds the new version side-by-side with the old version and then remove the old version.

Converting in device in place requires some gymnastics. If you think it's absolutely critical, I could try to do it but I'm not sure I agree it's the thing to do.

Quoted 5 lines

This means that we can't
review only the changes, but have to review the whole code. It also makes conflicts with patches modifying the old version hard to even notice.

Quoted 7 lines

On another note, I'm not so sure if your renaming is really helpful. It doesn't matter that much with qemu-char because someone thought having the function pointers in CharDriverState was a good idea, but if you're consistent, the rename would go like this in the block layer:

BlockDriverState -> BlockDriver
BlockDriver -> BlockDriverClass

I think we do need to introduce consistent naming conventions.

If those conventions are FooState and Foo, that could be okay, but the code base today is absolutely not consistent on it.

I think Foo and FooClass is better because Foo is the most common usage of the type and it's less characters to type.

Regards,

Anthony Liguori

Quoted 7 lines

IMHO, that's not very helpful, but just going to create confusion. We could probably discuss other parts of the terminology, too, but let's save the bikeshedding for later.

Kevin

#26 lore raw

Am 25.07.2011 14:45, schrieb Anthony Liguori:

Quoted 27 lines · Kevin Wolf
Quoted 18 lines

Am 25.07.2011 03:44, schrieb Anthony Liguori:

Quoted 17 lines

Hi,

This series is the rough beginnings of the QEMU Object Model. This is basically qdev generalized on steroids.

This series includes the core infrastructure, a strawman Device type, and the beginnings of the conversion of CharDriverState. This is in a rougher state than I would like it to be but I wanted to get the concepts on the list as soon as possible.

My plan is to drop the Device parts from future versions of the series and just focus on backends to start with.

Please note that this series has an awful lot of ramifications. Most of our current command line options would become deprecated, the build system will change significantly, and a lot of our QMP functions will become deprecated.

Quoted 7 lines
Quoted 3 lines

It seems like a lot of change, but hopefully this series illustrates how we can do it very incrementally with value being added at each stage of the conversion.

I haven't looked in much detail at it yet, but it has still the same problem I was talking about last week: Patches 17-21 don't actually convert existing code, but they add new code.

Quoted 7 lines

Actually, it's mostly existing code. In terms of incremental conversion, the most straight forward way is to adds the new version side-by-side with the old version and then remove the old version.

Converting in device in place requires some gymnastics. If you think it's absolutely critical, I could try to do it but I'm not sure I agree it's the thing to do.

Okay, if it isn't possible with reasonable effort, I guess we'll have to bite the bullet and give it a very careful manual review immediately before the merge.

By the way, I see that you create new directories. You probably have an idea of what the directory structure will look like after the whole conversion is completed. Can you share this idea with us?

Quoted 13 lines
Quoted 5 lines

This means that we can't
review only the changes, but have to review the whole code. It also makes conflicts with patches modifying the old version hard to even notice.

Quoted 7 lines

On another note, I'm not so sure if your renaming is really helpful. It doesn't matter that much with qemu-char because someone thought having the function pointers in CharDriverState was a good idea, but if you're consistent, the rename would go like this in the block layer:

BlockDriverState -> BlockDriver
BlockDriver -> BlockDriverClass

Quoted 7 lines

I think we do need to introduce consistent naming conventions.

If those conventions are FooState and Foo, that could be okay, but the code base today is absolutely not consistent on it.

I think Foo and FooClass is better because Foo is the most common usage of the type and it's less characters to type.

Maybe. But then, CharDriver is a really bad names for an instance. There is only one driver, which made it a good name for the class until now. Maybe CharBackend and CharBackendClass (or CharBackendDriver) would be a more sensible replacement that follows your pattern.

Kevin

#27 lore raw
Quoted 8 lines · Kevin Wolf

Am 25.07.2011 14:45, schrieb Anthony Liguori:
Okay, if it isn't possible with reasonable effort, I guess we'll have to bite the bullet and give it a very careful manual review immediately before the merge.

By the way, I see that you create new directories. You probably have an idea of what the directory structure will look like after the whole conversion is completed. Can you share this idea with us?

Just the logic extension of what we have already:

block/
chrdrv/
net/
qom/
qapi/
devices/
\ pc/

   | pci/
   | scsi/
   | etc.
Quoted 7 lines
Quoted 2 lines

I think Foo and FooClass is better because Foo is the most common usage of the type and it's less characters to type.

Maybe. But then, CharDriver is a really bad names for an instance. There is only one driver, which made it a good name for the class until now. Maybe CharBackend and CharBackendClass (or CharBackendDriver) would be a more sensible replacement that follows your pattern.

Good suggestion. I've been thinking that there's like to be a need for a generic Backend base class too so that would work well from a naming convention perspective.

Regards,

Anthony Liguori

Quoted 3 lines

Kevin

#28 lore raw
In reply to Anthony Liguori
Quoted 5 lines · Anthony Liguori

Hi,

This series is the rough beginnings of the QEMU Object Model. This is basically qdev generalized on steroids.

Quoted 7 lines

This series includes the core infrastructure, a strawman Device type, and the beginnings of the conversion of CharDriverState. This is in a rougher state than I would like it to be but I wanted to get the concepts on the list as soon as possible.

My plan is to drop the Device parts from future versions of the series and just focus on backends to start with.

I am not sure of how the Device and Char/Block/NetworkDriver bits relate to each other. It seems to me that they are two very different families of objects, and we should treat them differently.

For host devices (Char/Block/Network) we have a relatively simple interface but we need a richer way to create and destroy the objects at runtime. We have it already for block and network, we don't for char, but it is done ad hoc for each hierarchy. We do not have a deep hierarchy, in fact there is no hierarchy at all (only one abstract class per subsystem).

Honestly, it is not too bad. It may not be the cleanest code, but is it worth the kind of ramifications that your patch has? Of course, the answer could be "yes" if the same model can be applied to devices. Devices do have the same introspection needs more or less, and I like your ideas there. However, the requirements are very different in terms of composition.

Also because there is no hierarchy, composition in host devices can be done very easily. A decorator for char/block devices, such as a "tee" device, can treat the wrapped object(s) the same independent of the actual class. A simple vtable works very well. GObject would also do well, unifying the introspection at the cost of significantly more boilerplate.

(Of course, we could rewrite QEMU in Vala).

For *guest* devices, however, this is not the case. The PCI host needs to know that the device on the other end is a PCI device. Even the simplest bus, for example I2C, has methods defined on its children.

So, the most important point, it seems to me, is to support composition effectively. There need not be any hierarchy at all---not even the two-level hierarchy we have now, everything can inherit from DeviceState---but the combination between devices must be:

1) in a flexible manner, so that it can express complex topologies (as long as "plugs" and "sockets" have the same shape of course);

2) in an easily introspectable manner, so that migration and QMP and so on work very well in the presence of said topologies;

3) in a precise manner, so that the two devices being connected can interact effectively;

The current qdev fails completely at (1). (2) is very limited if you consider qdev only; qdev+VMState is at least decent, though nowhere near the potential of QOM.

However, qdev gets (3) right by making interaction between the parent and the child go through a bus object that knows the details of both. In particular, bus objects and their vtable structures are very effective in qdev because they provide flexibility and avoid impedence mismatch, with a very limited amount of boilerplate.

By contrast, the plug/socket model in QOM achieves (1) and (2), but in my opinion it fails at (3). The model for example is not effective in specifying the properties of the socket, which are roughly are the bus properties and the fields added by DeviceState abstract subclasses in the current qdev; it is not clear where they would live in QOM. Perhaps in the parent device or in an intermediate object between the parent and the child; if the latter, it looks like a lot of pointer chasing and a conversion nightmare.

Based on my earlier conversations with Peter, I thought a bit on how to do more incremental changes to qdev in order to overcome the inflexibility. Here is a rough overview of the steps:

1) make properties more flexible. In particular, we *absolutely* need array properties, either static or dynamic. The current special casing of GPIO pins is required exactly because we do not have arrays of properties.

Also, since arrays occur a lot in the device state, array properties would also be required to be able to introspect on run-time properties (which are now part of VMState only). However, I am not going to consider run-time introspection much more. It is "a simple matter of programming" if your general introspection design is done right.

2) add more kinds of first-class (user specifiable) properties. GPIO pins, for example, which are already part of qdev but cannot be specified by the user on the command line. Possibly memory regions too. Anything that can be used to configure a device (with respect to the
main bus or to its parent) should be a property.

3) at this point, you can get rid of the specialties of SysBus devices. IRQs are an array of GPIO properties, same for memory regions. SysBus
devices can use a naked DeviceState structure.

At this point, many embedded devices could be entirely described in terms of configuration files, except for legacy options (-serial kind) and for the few devices that attach directly to the CPU. This without the need to define artificial buses that do not exist in real hardware.

4) add support for compound properties. A compound properties is such that you define a property named (coincidence...) "bus" and you get automatically "bus.parent", "bus.addr", "bus.romfile", "bus.rombar" etc.

5) convert buses to compound properties. Rather than inheriting from PCIDevice, a PCI device would inherit straight from DeviceState and include a PCIDevice struct that defines the backlink from a device to its parent. Note that since we're using C, this is not a big change from what we're doing now! (Inheritance by containment is a special case of containment.) And it allows to define very flexibly a device that would have to sit on two or more buses in the current qdev model. More importantly, it keeps the effectiveness of the qbus ops model, while removing the constraint of a tree topology.

It is only when this is done, that we should reconsider introspection and see if it is useful/sensible to unify the host and guest device object models.

Because the host models we have now, with all the defects they may have, *work*. The guest models hardly work for anything but PCs, and even then only for the subset of devices which are interesting to hot-plug/unplug. And so it is from them that we should start designing.

Thoughts?

Paolo

#29 lore raw
Quoted 14 lines · Paolo Bonzini

For host devices (Char/Block/Network) we have a relatively simple interface but we need a richer way to create and destroy the objects at runtime. We have it already for block and network, we don't for char, but it is done ad hoc for each hierarchy. We do not have a deep hierarchy, in fact there is no hierarchy at all (only one abstract class per subsystem).

Honestly, it is not too bad. It may not be the cleanest code, but is it worth the kind of ramifications that your patch has? Of course, the answer could be "yes" if the same model can be applied to devices. Devices do have the same introspection needs more or less, and I like your ideas there. However, the requirements are very different in terms of composition.

Quoted 6 lines

Also because there is no hierarchy, composition in host devices can be done very easily. A decorator for char/block devices, such as a "tee" device, can treat the wrapped object(s) the same independent of the actual class. A simple vtable works very well. GObject would also do well, unifying the introspection at the cost of significantly more boilerplate.

The polymorphism model of QOM is identical to GObject so I'm not sure what you mean here.

In the case of tee, it's just an object with two sockets.

Quoted 5 lines

(Of course, we could rewrite QEMU in Vala).

For *guest* devices, however, this is not the case. The PCI host needs to know that the device on the other end is a PCI device. Even the simplest bus, for example I2C, has methods defined on its children.

I have PCI patches, but didn't post them in the series. Here's how it works:

The PCI host controller, the i440fx, has 32 sockets of PCIDevice. PCIDevice is a base class.

The PCI host controller implements a PCIBus interface. The PCIDevices have a socket of a PCIBus

Connecting a PCIDevice to the host bus involves setting the socket on the PCI host controller with the PCIDevice and then setting the PCIDevice's bus socket with the host controller.

A PCIDevice can also be a PCIBus by implementing the PCIBus interface. This is what enables a PCI bridge to make sense in this model.

If you're interested, the tree that has this is http://repo.or.cz/w/qemu/aliguori.git/tree/qdev2:/devices

Quoted 4 lines

So, the most important point, it seems to me, is to support composition effectively. There need not be any hierarchy at all---not even the two-level hierarchy we have now, everything can inherit from DeviceState---but the combination between devices must be:

I think composition is being overloaded here. When I say composition, I mean that one device is created out of multiple other devices. Something like the PIIX3 is composed of an RTC, UART, etc.

That's different that connecting up the links in the device tree graph.

Quoted 2 lines

1) in a flexible manner, so that it can express complex topologies (as long as "plugs" and "sockets" have the same shape of course);

Right, this is what we do today in QOM. Plugs and Sockets are typed. Those types can be interfaces or base classes so there's a lot of flexibility.

Quoted 2 lines

2) in an easily introspectable manner, so that migration and QMP and so on work very well in the presence of said topologies;

The 'qsh' tree can view the entire device model as a synthetic file system. Plugs are represented as sub directories and sockets as symbolic links. I plan on writing a quick FUSE file system too.

There is type information with all of the attributes that's not visible in this view but it's there nonetheless.

Quoted 14 lines

3) in a precise manner, so that the two devices being connected can interact effectively;

The current qdev fails completely at (1). (2) is very limited if you consider qdev only; qdev+VMState is at least decent, though nowhere near the potential of QOM.

However, qdev gets (3) right by making interaction between the parent and the child go through a bus object that knows the details of both. In particular, bus objects and their vtable structures are very effective in qdev because they provide flexibility and avoid impedence mismatch, with a very limited amount of boilerplate.

Quoted 5 lines

By contrast, the plug/socket model in QOM achieves (1) and (2), but in my opinion it fails at (3). The model for example is not effective in specifying the properties of the socket, which are roughly are the bus properties and the fields added by DeviceState abstract subclasses in the current qdev;

There are no properties of the socket.

If you look at something like adding a PCI device in qdev, you add a child and set properties of the child to identify how the device sits on the PCI bus.

I'd characterize this as awkward, at best. The slot index is not a property of the device, it's a property of how the device is connected to the PCI bus.

In my attempt at PCI modelling, I had something like:

struct I440FX
{
Device parent;

PciDevice slots[32];
};

Which means that to attach to bus 0, slot 3, fn 0, you do:

i440fx->slots[3] = mydevice

Likewise, if slot 4 contains a PCI-to-PCI bridge that ends up being bus 1, and you want to assign to bus 1, slot 2, fn 0:

i440fx->slots[4]->slots[2] = myotherdevice;

Now you may observe that this is awkward compared to saying "bus 1". But bus numbering is actually a guest concept, not a hardware concept. When constructing the device tree, the physical topology is actually what make sense in terms of constructing devices, not a guest derived numbering concept.

The same applies equally to IDE. You'd have:

struct IDEBus
{
IDEDevice *master, *slave;
};

struct IDEChipset
{
IDEBus primary;
IDEBus secondary;
};

This would result in:

ide->primary.master = disk1;
ide->secondary.master = cdrom;

Quoted 4 lines

it is not clear where they would live in QOM. Perhaps
in the parent device or in an intermediate object between the parent and the child; if the latter, it looks like a lot of pointer chasing and a conversion nightmare.

It's a characteristic of the property itself. It's definitely very different than how we do it today.

Quoted 11 lines

Based on my earlier conversations with Peter, I thought a bit on how to do more incremental changes to qdev in order to overcome the inflexibility. Here is a rough overview of the steps:

1) make properties more flexible. In particular, we *absolutely* need array properties, either static or dynamic. The current special casing of GPIO pins is required exactly because we do not have arrays of properties.

Quoted 5 lines

Also, since arrays occur a lot in the device state, array properties would also be required to be able to introspect on run-time properties (which are now part of VMState only). However, I am not going to consider run-time introspection much more. It is "a simple matter of programming" if your general introspection design is done right.

Arrays of properties already work in QOM. Part of the trouble with qdev today (and QObject for that matter), is that properties are a characteristic of a class, not an object. This is the primary difference between the QOM Plug and is required for proper array support.

Quoted 17 lines

2) add more kinds of first-class (user specifiable) properties. GPIO pins, for example, which are already part of qdev but cannot be specified by the user on the command line. Possibly memory regions too. Anything that can be used to configure a device (with respect to the main bus or to its parent) should be a property.

3) at this point, you can get rid of the specialties of SysBus devices. IRQs are an array of GPIO properties, same for memory regions. SysBus devices can use a naked DeviceState structure.

At this point, many embedded devices could be entirely described in terms of configuration files, except for legacy options (-serial kind) and for the few devices that attach directly to the CPU. This without the need to define artificial buses that do not exist in real hardware.

Quoted 3 lines

4) add support for compound properties. A compound properties is such that you define a property named (coincidence...) "bus" and you get automatically "bus.parent", "bus.addr", "bus.romfile", "bus.rombar" etc.

Because QOM uses visitors for properties, properties can be arbitrarily complicated structures. How that maps to command line arguments, I haven't thought through yet but you can certainly do:

plug_set(obj, "bus", { 'parent': x, 'addr': y, ...})

Quoted 10 lines

5) convert buses to compound properties. Rather than inheriting from PCIDevice, a PCI device would inherit straight from DeviceState and include a PCIDevice struct that defines the backlink from a device to its parent. Note that since we're using C, this is not a big change from what we're doing now! (Inheritance by containment is a special case of containment.) And it allows to define very flexibly a device that would have to sit on two or more buses in the current qdev model. More importantly, it keeps the effectiveness of the qbus ops model, while removing the constraint of a tree topology.

Interfaces are the right way to do this. Getting MI right is fairly hard and since qdev uses a simple container_of, it's not going to work very well. That's another advantage of QOM, casting from interfaces to objects Just Works.

Quoted 6 lines

It is only when this is done, that we should reconsider introspection and see if it is useful/sensible to unify the host and guest device object models.

Quoted 6 lines

Because the host models we have now, with all the defects they may have, *work*. The guest models hardly work for anything but PCs, and even then only for the subset of devices which are interesting to hot-plug/unplug. And so it is from them that we should start designing.

Thoughts?

I think all of the requirements you've outlined are currently handled in QOM. I think it would probably be a good idea to set up a wiki page that focused just on qdev-next requirements and that would give us a rigorious mechanism to evaluate how well QOM satisfies those requirements.

I haven't thought through how to do OQM incrementally with qdev. It's probably possible but I wanted to focus on the backends first before really attacking that.

Regards,

Anthony Liguori

Quoted 4 lines

Paolo

#30 lore raw
Quoted 9 lines · Anthony Liguori
Quoted 6 lines

Also because there is no hierarchy, composition in host devices can be done very easily. A decorator for char/block devices, such as a "tee" device, can treat the wrapped object(s) the same independent of the actual class. A simple vtable works very well. GObject would also do well, unifying the introspection at the cost of significantly more boilerplate.

The polymorphism model of QOM is identical to GObject so I'm not sure what you mean here.

GObject instead of QOM (just so that we have something that is already written).

Quoted 1 line

In the case of tee, it's just an object with two sockets.

Yes, understood.

Quoted 5 lines

I have PCI patches, but didn't post them in the series. Here's how it works:

The PCI host controller, the i440fx, has 32 sockets of PCIDevice. PCIDevice is a base class.

And as such it can add data members. But when a device is on two buses, you cannot have both of them adding data members. I know MI is hard to get right, and in fact I'm not proposing to do MI---not even interface inheritance. I don't want to have any base class but DeviceState.

Quoted 7 lines

The PCI host controller implements a PCIBus interface. The PCIDevices have a socket of a PCIBus

Connecting a PCIDevice to the host bus involves setting the socket on the PCI host controller with the PCIDevice and then setting the PCIDevice's bus socket with the host controller.

Quoted 5 lines

A PCIDevice can also be a PCIBus by implementing the PCIBus interface. This is what enables a PCI bridge to make sense in this model.

If you're interested, the tree that has this is
http://repo.or.cz/w/qemu/aliguori.git/tree/qdev2:/devices

Yes, this is pretty much what I had imagined. But it does not scale to a topology where you have two parents, both of which want to add data members.

Quoted 6 lines
Quoted 2 lines

1) in a flexible manner, so that it can express complex topologies (as long as "plugs" and "sockets" have the same shape of course);

Right, this is what we do today in QOM. Plugs and Sockets are typed. Those types can be interfaces or base classes so there's a lot of flexibility.

Interfaces (is-a) are less flexible than embedded objects (has-a).

Quoted 9 lines

There are no properties of the socket.

If you look at something like adding a PCI device in qdev, you add a child and set properties of the child to identify how the device sits on the PCI bus.

I'd characterize this as awkward, at best. The slot index is not a property of the device, it's a property of how the device is connected to the PCI bus.

Yes, for a PCI address I agree. But in a (parallel) SCSI bus, the LUN is logically a property of the device. Same as IDE when you used to set jumpers to choose master/slave. Or ISA interrupt lines.

Once you have something like this for a device that bridges two buses, interfaces require a lot of boilerplate for useless getters/setters.

Quoted 8 lines

i440fx->slots[3] = mydevice

Likewise, if slot 4 contains a PCI-to-PCI bridge that ends up being bus 1, and you want to assign to bus 1, slot 2, fn 0:

i440fx->slots[4]->slots[2] = myotherdevice;

Now you may observe that this is awkward compared to saying "bus 1".

No, I have no problem with that. :)

Quoted 4 lines

The same applies equally to IDE.

ide->primary.master = disk1;
ide->secondary.master = cdrom;

For IDE, an equally good model would be:

    ide->primary.add(disk1);
    disk1.masterSlave = MASTER;
    ide->secondary.add(cdrom);
    cdrom.masterSlave = MASTER;
Quoted 11 lines
Quoted 9 lines

5) convert buses to compound properties. Rather than inheriting from PCIDevice, a PCI device would inherit straight from DeviceState and include a PCIDevice struct that defines the backlink from a device to its parent. Note that since we're using C, this is not a big change from what we're doing now! (Inheritance by containment is a special case of containment.) And it allows to define very flexibly a device that would have to sit on two or more buses in the current qdev model. More importantly, it keeps the effectiveness of the qbus ops model, while removing the constraint of a tree topology.

Interfaces are the right way to do this. Getting MI right is fairly hard

But we don't need is-a, we need has-a. Multiple is-a is harder than single is-a. Multiple has-a does not add any complication.

Quoted 2 lines

I think all of the requirements you've outlined are currently handled in QOM.

They more than likely are. The question is whether they're handled in the most programmer-efficient manner, and whether the advantages of a single grand unified object model for host and guest devices is worth the effort.

Paolo

#31 lore raw
Quoted 21 lines · Paolo Bonzini
Quoted 9 lines · Anthony Liguori
Quoted 6 lines

Also because there is no hierarchy, composition in host devices can be done very easily. A decorator for char/block devices, such as a "tee" device, can treat the wrapped object(s) the same independent of the actual class. A simple vtable works very well. GObject would also do well, unifying the introspection at the cost of significantly more boilerplate.

The polymorphism model of QOM is identical to GObject so I'm not sure what you mean here.

GObject instead of QOM (just so that we have something that is already written).

Quoted 1 line

In the case of tee, it's just an object with two sockets.

Yes, understood.

Quoted 3 lines

I have PCI patches, but didn't post them in the series. Here's how it works:

Quoted 7 lines
Quoted 2 lines

The PCI host controller, the i440fx, has 32 sockets of PCIDevice. PCIDevice is a base class.

And as such it can add data members. But when a device is on two buses, you cannot have both of them adding data members. I know MI is hard to get right, and in fact I'm not proposing to do MI---not even interface inheritance. I don't want to have any base class but DeviceState.

I could use a concrete example here, but here's how this would be expressed:

class MyWeirdDevice : public MyBaseDevice, implements PciDevice, IsaDevice

{
    PciBus *pci_bus;
    IsaDevice *isa_bus;
};

Which actually models hw pretty well. A device that exists on two busses has to have two sockets that can accept the plugs from the busses they're joining.

It's pretty much exactly how it works in real life.

Quoted 11 lines
Quoted 11 lines

The PCI host controller implements a PCIBus interface. The PCIDevices have a socket of a PCIBus

Connecting a PCIDevice to the host bus involves setting the socket on the PCI host controller with the PCIDevice and then setting the PCIDevice's bus socket with the host controller.

A PCIDevice can also be a PCIBus by implementing the PCIBus interface. This is what enables a PCI bridge to make sense in this model.

Quoted 6 lines
Quoted 2 lines

If you're interested, the tree that has this is
http://repo.or.cz/w/qemu/aliguori.git/tree/qdev2:/devices

Yes, this is pretty much what I had imagined. But it does not scale to a topology where you have two parents, both of which want to add data members.

Which would be true MI. The problem with true MI is that you'll end up with a diamond if you try to have anything useful (like properties) in the base.

The common solution is to have the ability to has-a implementation of the interface.

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

1) in a flexible manner, so that it can express complex topologies (as long as "plugs" and "sockets" have the same shape of course);

Right, this is what we do today in QOM. Plugs and Sockets are typed. Those types can be interfaces or base classes so there's a lot of flexibility.

Interfaces (is-a) are less flexible than embedded objects (has-a).

It depends on what you're trying to model I guess. In some cases where the interface is more or less stateless or that state isn't common among implementations, interfaces are quite nice.

Quoted 10 lines
Quoted 9 lines

There are no properties of the socket.

If you look at something like adding a PCI device in qdev, you add a child and set properties of the child to identify how the device sits on the PCI bus.

I'd characterize this as awkward, at best. The slot index is not a property of the device, it's a property of how the device is connected to the PCI bus.

Quoted 5 lines

Yes, for a PCI address I agree. But in a (parallel) SCSI bus, the LUN is logically a property of the device.

Same as IDE when you used to set
jumpers to choose master/slave. Or ISA interrupt lines.

The ISA dip switches literally select which line of the bus gets routed to the device. All devices have access to all interrupt lines through the bus.

So when modelling, it makes sense to have the irq be a property of the device and then to have the bus interface expose the irqs. For instance:

struct IsaBusClass
{
void (*set_irq_level)(IsaBus *bus, int irq, bool level);
};

I don't know enough about SCSI to know whether it makes sense to have LUN be a property of the bus or the device. If LUN negotiation is aided by the controller and fixed after startup, then I think it makes sense for there to be a fixed number of sockets in the bus and then for the bus to do LUN assignment at realize (possibly looking at each device to see what the requested LUN is).

Quoted 2 lines

Once you have something like this for a device that bridges two buses, interfaces require a lot of boilerplate for useless getters/setters.

Can you elaborate?

Quoted 17 lines
Quoted 9 lines

i440fx->slots[3] = mydevice

Likewise, if slot 4 contains a PCI-to-PCI bridge that ends up being bus 1, and you want to assign to bus 1, slot 2, fn 0:

i440fx->slots[4]->slots[2] = myotherdevice;

Now you may observe that this is awkward compared to saying "bus 1".

No, I have no problem with that. :)

Quoted 4 lines

The same applies equally to IDE.

ide->primary.master = disk1;
ide->secondary.master = cdrom;

Quoted 6 lines

For IDE, an equally good model would be:

ide->primary.add(disk1);
disk1.masterSlave = MASTER;
ide->secondary.add(cdrom);
cdrom.masterSlave = MASTER;

There's a pin in the IDE cable that determines master or slave depending on whether it's raised high. You can think of it as a very simple MUX circuit where the pin decodes the single group of 40 wires into two distinct groups of 39 wires, each group being a different port on the bus.

I think modelling it that way makes more sense from an end user perspective since it prevents the possibility of have two master devices (which is incorrect).

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines

5) convert buses to compound properties. Rather than inheriting from PCIDevice, a PCI device would inherit straight from DeviceState and include a PCIDevice struct that defines the backlink from a device to its parent. Note that since we're using C, this is not a big change from what we're doing now! (Inheritance by containment is a special case of containment.) And it allows to define very flexibly a device that would have to sit on two or more buses in the current qdev model. More importantly, it keeps the effectiveness of the qbus ops model, while removing the constraint of a tree topology.

Quoted 4 lines
Quoted 1 line

Interfaces are the right way to do this. Getting MI right is fairly hard

But we don't need is-a, we need has-a. Multiple is-a is harder than single is-a. Multiple has-a does not add any complication.

Yeah, that's what plug properties are for :-) Making has-a work well is one of the issues I had with GObject. GObject is not very good for expressing has-a.

Quoted 8 lines
Quoted 3 lines

I think all of the requirements you've outlined are currently handled in QOM.

They more than likely are. The question is whether they're handled in the most programmer-efficient manner, and whether the advantages of a single grand unified object model for host and guest devices is worth the effort.

Indeed. I think that it's a no brainer for the backends and that's why I'm starting there.

Regards,

Anthony Liguori

Quoted 3 lines

Paolo

#32 lore raw
Quoted 14 lines · Anthony Liguori
Quoted 4 lines

And as such it can add data members. But when a device is on two buses, you cannot have both of them adding data members. I know MI is hard to get right, and in fact I'm not proposing to do MI---not even interface inheritance. I don't want to have any base class but DeviceState.

I could use a concrete example here, but here's how this would be expressed:

class MyWeirdDevice : public MyBaseDevice, implements PciDevice, IsaDevice {
PciBus *pci_bus;
IsaDevice *isa_bus;
};

Quoted 5 lines

Which actually models hw pretty well. A device that exists on two busses has to have two sockets that can accept the plugs from the busses they're joining.

It's pretty much exactly how it works in real life.

You could just as well say that real life works like this:

class PciSocket {
    PciBus *pci_bus;
    uint8_t *config;
    uint8_t *cmask;
    uint8_t *wmask;
    uint8_t *w1cmask;
    uint8_t *used;
    uint32_t devfn;
    char name[64];
    PCIIORegion io_regions[PCI_NUM_REGIONS];
    ...

};

class IsaSocket {
IsaBus *isa_bus;
uint32_t isairq[2]; // not sure this is a good idea, just
int nirqs; // mimicking qdev
uint16_t ioports[32];// statically assigned unlike PCI bars int nioports;
}

class MyWeirdDevice : public MyBaseDevice {
    PciSocket pci;
    IsaSocket isa;
};
Quoted 7 lines
Quoted 3 lines

Yes, this is pretty much what I had imagined. But it does not scale to a topology where you have two parents, both of which want to add data members.

Which would be true MI. The problem with true MI is that you'll end up with a diamond if you try to have anything useful (like properties) in the base.

See above for how you would avoid that.

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
Quoted 2 lines

1) in a flexible manner, so that it can express complex topologies (as long as "plugs" and "sockets" have the same shape of course);

Right, this is what we do today in QOM. Plugs and Sockets are typed. Those types can be interfaces or base classes so there's a lot of flexibility.

Quoted 5 lines
Quoted 1 line

Interfaces (is-a) are less flexible than embedded objects (has-a).

It depends on what you're trying to model I guess. In some cases where the interface is more or less stateless or that state isn't common among implementations, interfaces are quite nice.

Yes, I'm not sure this is the case here. :)

Quoted 7 lines
Quoted 2 lines

Same as IDE when you used to set
jumpers to choose master/slave. Or ISA interrupt lines.

The ISA dip switches literally select which line of the bus gets routed to the device. All devices have access to all interrupt lines through the bus.

Quoted 7 lines

So when modelling, it makes sense to have the irq be a property of the device and then to have the bus interface expose the irqs. For instance:

struct IsaBusClass
{
void (*set_irq_level)(IsaBus *bus, int irq, bool level); };

Agreed. Though I'm not sure that the same is true for all fields in qemu's current PCIDevice.

Quoted 4 lines
Quoted 2 lines

Once you have something like this for a device that bridges two buses, interfaces require a lot of boilerplate for useless getters/setters.

Can you elaborate?

If you store data (configuration space etc.) in the device, and the bus has to access it, you need getters/setters in the interface. Letting the bus hold an interior reference to the PciSocket (perhaps adding a single get_device_for_socket function to the PciSocketOps) solves the problem.

Quoted 7 lines
Quoted 7 lines
Quoted 4 lines

The same applies equally to IDE.

ide->primary.master = disk1;
ide->secondary.master = cdrom;

For IDE, an equally good model would be:

Quoted 7 lines
Quoted 4 lines

ide->primary.add(disk1);
disk1.masterSlave = MASTER;
ide->secondary.add(cdrom);
cdrom.masterSlave = MASTER;

There's a pin in the IDE cable that determines master or slave depending on whether it's raised high.

Yes, that's the "newer" way. There used to be jumpers to choose between master, slave and cable-select.

Quoted 3 lines

I think modelling it that way makes more sense from an end user perspective since it prevents the possibility of have two master devices (which is incorrect).

... but you could do that, if for some reason you wanted to model the jumper-based world. But this is a mostly irrelevant digression.

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Interfaces are the right way to do this. Getting MI right is fairly hard

But we don't need is-a, we need has-a. Multiple is-a is harder than single is-a. Multiple has-a does not add any complication.

Yeah, that's what plug properties are for :-)

I agree, but at the cost of pointer chasing and making it harder to implement get_device_for_socket for buses that need it (in the above sketch it can be a simple container_of).

Quoted 10 lines
Quoted 7 lines
Quoted 2 lines

I think all of the requirements you've outlined are currently handled in QOM.

They more than likely are. The question is whether they're handled in the most programmer-efficient manner, and whether the advantages of a single grand unified object model for host and guest devices is worth the effort.

Indeed. I think that it's a no brainer for the backends and that's why I'm starting there.

I don't think it's a no brainer. It's simply much easier, but right now it is also a solution in search of a problem (if all you want is dynamic creation of character devices, you could do that without a generic object model).

If starting from a blank slate, I would be much more enthusiastic. But all that QEMU does _not_ need is yet another incomplete transition.

Paolo

#33 lore raw
Quoted 46 lines · Paolo Bonzini
Quoted 15 lines · Anthony Liguori
Quoted 4 lines

And as such it can add data members. But when a device is on two buses, you cannot have both of them adding data members. I know MI is hard to get right, and in fact I'm not proposing to do MI---not even interface inheritance. I don't want to have any base class but DeviceState.

I could use a concrete example here, but here's how this would be expressed:

class MyWeirdDevice : public MyBaseDevice, implements PciDevice, IsaDevice
{
PciBus *pci_bus;
IsaDevice *isa_bus;
};

Quoted 5 lines

Which actually models hw pretty well. A device that exists on two busses has to have two sockets that can accept the plugs from the busses they're joining.

It's pretty much exactly how it works in real life.

You could just as well say that real life works like this:

class PciSocket {
PciBus *pci_bus;
uint8_t *config;
uint8_t *cmask;
uint8_t *wmask;
uint8_t *w1cmask;
uint8_t *used;
uint32_t devfn;
char name[64];
PCIIORegion io_regions[PCI_NUM_REGIONS];
...

};

class IsaSocket {
IsaBus *isa_bus;
uint32_t isairq[2]; // not sure this is a good idea, just int nirqs; // mimicking qdev
uint16_t ioports[32];// statically assigned unlike PCI bars int nioports;
}

Quoted 4 lines

class MyWeirdDevice : public MyBaseDevice {
PciSocket pci;
IsaSocket isa;
};

Hrm, I'm not sure I buy that entirely. I think it would be:

class MyWeirdPciView : public PciDevice {
PciBus *bus;
MyWeirdDevice *dev;
};

class MyWeirdIsaView : public IsaDevice {
IsaBus *bus;
MyWeirdDevice *dev;
};

class MyWeirdDevice : public MyBaseDevice {
MyWeirdPciView pci;
MyWeirdIsaView isa;
}

The views are basically bridges between PCI/ISA and an internal interface (MyWeirdDevice).

I don't think having a generic PciSocket class that offloads PCI knowledge to another device is the right model (assuming that's why you're suggesting). It's basically proxying PCI to another device.

Quoted 9 lines
Quoted 4 lines
Quoted 2 lines

Once you have something like this for a device that bridges two buses, interfaces require a lot of boilerplate for useless getters/setters.

Can you elaborate?

If you store data (configuration space etc.) in the device, and the bus has to access it, you need getters/setters in the interface. Letting the bus hold an interior reference to the PciSocket (perhaps adding a single get_device_for_socket function to the PciSocketOps) solves the problem.

I don't think the proxy design pattern is the right thing to use. 95% of the time, the device is intrinsically a PCI device. The other 5% of the time, the device has a well defined interface, and then there is effectively a PCI bridge. But that PCI bridge isn't generic, it's specific to that custom interface.

Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
Quoted 4 lines

The same applies equally to IDE.

ide->primary.master = disk1;
ide->secondary.master = cdrom;

For IDE, an equally good model would be:

ide->primary.add(disk1);
disk1.masterSlave = MASTER;
ide->secondary.add(cdrom);
cdrom.masterSlave = MASTER;

Quoted 5 lines
Quoted 2 lines

There's a pin in the IDE cable that determines master or slave depending on whether it's raised high.

Yes, that's the "newer" way. There used to be jumpers to choose between master, slave and cable-select.

That jumper raises the bit on the wire.

Quoted 11 lines
Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

Interfaces are the right way to do this. Getting MI right is fairly hard

But we don't need is-a, we need has-a. Multiple is-a is harder than single is-a. Multiple has-a does not add any complication.

Yeah, that's what plug properties are for :-)

I agree, but at the cost of pointer chasing and making it harder to implement get_device_for_socket for buses that need it (in the above sketch it can be a simple container_of).

Can we be a bit more concrete as I'm having a hard time following your logic. You're assuming a generic PciSocket class, right? I think that's not the right approach, as an example:

class Rtl8139PciBridge : public PciDevice
{
Rtl8139 rtldev;
};

class Rtl8139IsaBridge : public IsaDevice
{
Rtl8139 rtldev;
};

With Avi's new memory API, we'd have:

class Rtl8139 : public Device
{
MemoryRegion region[2];
Pin irq;
};

And then the construction code for Rtl8139PciBridge would register the regions as bars, and connect the PCI lnk to rtldev.irq.

The ISA code would do something similar.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
Quoted 3 lines

I think all of the requirements you've outlined are currently handled in
QOM.

They more than likely are. The question is whether they're handled in the most programmer-efficient manner, and whether the advantages of a single grand unified object model for host and guest devices is worth the effort.

Quoted 7 lines
Quoted 2 lines

Indeed. I think that it's a no brainer for the backends and that's why I'm starting there.

I don't think it's a no brainer. It's simply much easier, but right now it is also a solution in search of a problem (if all you want is dynamic creation of character devices, you could do that without a generic object model).

And that solves the problem yet again for one layer. But what about block, fsdev, and DisplayState? We can keep reinventing the wheel over and over again in slightly different ways or we can try to do something that will work for more things.

We need more commonality in QEMU. Things are hard to follow because every subsystem is an island.

Quoted 2 lines

If starting from a blank slate, I would be much more enthusiastic. But all that QEMU does _not_ need is yet another incomplete transition.

This is an oversimplification and an argument that needs to end.

We need lots of new transitions, we need to strive to make things better. But we need to do things in such a way that:

(1) we have a good idea of what we're going to end up with at the end
of the day

(2) there is incremental value being added to QEMU at every step of
the way

This cannot be done by simply hacking some bits here and there. It requires design, planning, and flag days when appropriate.

If you look at QAPI, we only merged the bits that had value for a specific feature (guest agent). The remaining bits (QMP conversion), has been completely, but will be merged all at once. The mistake we can make in an effort like this is introduce a partial conversion that has no value in and of itself.

Because there's little incentive to help with partial conversions if there isn't an immediate return on investment. That's why I've stuck with focusing on the char layer to start with. It's value that stands on its own.

That's the thing we need to focus on. The problem with our past attempts at making large changes is that we didn't deconstruct it in such a way that each phase added clear value.

Regards,

Anthony Liguori

Quoted 3 lines

Paolo

#34 lore raw
Quoted 43 lines · Anthony Liguori
Quoted 25 lines · Paolo Bonzini

On 07/26/2011 05:34 PM, Anthony Liguori wrote:
You could just as well say that real life works like this:

class PciSocket {
PciBus *pci_bus;
uint8_t *config;
uint8_t *cmask;
uint8_t *wmask;
uint8_t *w1cmask;
uint8_t *used;
uint32_t devfn;
char name[64];
PCIIORegion io_regions[PCI_NUM_REGIONS];
...

};

class IsaSocket {
IsaBus *isa_bus;
uint32_t isairq[2]; // not sure this is a good idea, just int nirqs; // mimicking qdev
uint16_t ioports[32];// statically assigned unlike PCI bars int nioports;
}

Quoted 4 lines

class MyWeirdDevice : public MyBaseDevice {
PciSocket pci;
IsaSocket isa;
};

Hrm, I'm not sure I buy that entirely. I think it would be:

class MyWeirdPciView : public PciDevice {
PciBus *bus;
MyWeirdDevice *dev;
};

class MyWeirdIsaView : public IsaDevice {
IsaBus *bus;
MyWeirdDevice *dev;
};

Quoted 7 lines

class MyWeirdDevice : public MyBaseDevice {
MyWeirdPciView pci;
MyWeirdIsaView isa;
}

The views are basically bridges between PCI/ISA and an internal interface (MyWeirdDevice).

That's yet another possibility. There are two difference with what I had written:

1) the back-pointer from MyWeird*View to MyWeirdDevice replaced by container_of. That's cosmetic;

2) I'm not considering the sockets to be separate devices. That's the difference between "proxying PCI to another device" (wrong, hardware does not do that) and "isolating PCI knowledge within a sub-object of the device" (just an encapsulation choice, hardware is irrelevant).

Quoted 2 lines

I don't think the proxy design pattern is the right thing to use. 95% of the time, the device is intrinsically a PCI device.

It's not a proxy. It's replacing inheritance with containment to get the flexibility of data MI without the complexity of diamond hierarchies.

Quoted 4 lines

The other 5% of the
time, the device has a well defined interface, and then there is effectively a PCI bridge. But that PCI bridge isn't generic, it's specific to that custom interface.

Yes, that can be represented by composition if you wish (an ISASerialState containing an 8250 is the canonical example; the 8139 example below is another).

Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

There's a pin in the IDE cable that determines master or slave depending on whether it's raised high.

Yes, that's the "newer" way. There used to be jumpers to choose between master, slave and cable-select.

That jumper raises the bit on the wire.

Ah ok, I was confusing it with the cable-select wire. My point was that you can choose the jumper representation (low-level) or the cable-select representation (high-level, actually matches modern hardware, even better from the user POV). One is easier to manage and better in all aspects, but both make sense. It's irrelevant to this discussion anyway.

Quoted 34 lines
Quoted 11 lines
Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

Interfaces are the right way to do this. Getting MI right is fairly hard

But we don't need is-a, we need has-a. Multiple is-a is harder than single is-a. Multiple has-a does not add any complication.

Yeah, that's what plug properties are for :-)

I agree, but at the cost of pointer chasing and making it harder to implement get_device_for_socket for buses that need it (in the above sketch it can be a simple container_of).

Can we be a bit more concrete as I'm having a hard time following your logic. You're assuming a generic PciSocket class, right? I think that's not the right approach, as an example:

class Rtl8139PciBridge : public PciDevice
{
Rtl8139 rtldev;
};

class Rtl8139IsaBridge : public IsaDevice
{
Rtl8139 rtldev;
};

With Avi's new memory API, we'd have:

class Rtl8139 : public Device
{
MemoryRegion region[2];
Pin irq;
};

Quoted 4 lines

And then the construction code for Rtl8139PciBridge would register the regions as bars, and connect the PCI lnk to rtldev.irq.

The ISA code would do something similar.

Yes, this looks nice (modulo s/Rtl8139/Rtl8139 */). But it is not that much more flexible than qdev 1.0.

You're right that for the case of two parents above we were looking at a contrived example. The Goldfish platform provides a more interesting one. There you have an interrupt controller and a bus enumerator device. Most devices are connected to both, but conflating them is wrong for many reasons;

1) the bus enumerator itself uses an interrupt (raised on hotplug);

2) you can enumerate devices that do not have an interrupt line, and you shouldn't need to connect such a device to an interrupt controller;

3) the interrupt controller and bus enumerator use two separate MMIO areas;

4) in principle, other devices could use the interrupt controller (which is the only component connected to the CPU's interrupt line) without being enumerated.

5) A device with two interrupts has two "interrupt interfaces" and only one "enumerator interface".

6) The enumerator interface does not have bus semantics. The enumerator also enumerates itself so it would act as both the bus host and a device on the bus.

Composition then lets you use something like this:

    class GoldfishPIC : Device {
        Pin parent;
        GoldfishInterruptPin *children[32];
        Pin (*init_socket_for_irq_num) (GoldfishInterruptPin *, int);
    };

    class GoldfishInterruptPin {
        GoldfishPIC *pic;
        Pin irqnum;
    };

    class GoldfishEnumerator : Device {
        GoldfishInterruptPin        irq;
        GoldfishBusDeviceInfo       info;
        List<GoldfishBusDeviceInfo> allDevices;
        ...
    };

    class GoldfishBusDeviceInfo {
        GoldfishEnumerator *parent;
        char *name;
        int id;
        ram_addr_t mmio;
        int mmio_size;
        int irq_base;
        int irq_count;
    };

    class GoldfishTTY : Device {
        GoldfishInterruptPin irq;
        GoldfishBusDeviceInfo info;
        CharDev *chardev;
    };

Here you do not need a bus to mediate the access between the TTY device and its parents, it would only introduce unnecessary complication (boilerplate and pointer chasing). It also would not match hardware at all in the case of the enumerator.

Quoted 8 lines
Quoted 7 lines
Quoted 2 lines

Indeed. I think that it's a no brainer for the backends and that's why I'm starting there.

I don't think it's a no brainer. It's simply much easier, but right now it is also a solution in search of a problem (if all you want is dynamic creation of character devices, you could do that without a generic object model).

Quoted 7 lines

And that solves the problem yet again for one layer. But what about block, fsdev, and DisplayState? We can keep reinventing the wheel over and over again in slightly different ways or we can try to do something that will work for more things.

We need more commonality in QEMU. Things are hard to follow because every subsystem is an island.

I am not saying you're wrong. I am saying it is very hard to do it on a mature (no matter how messy) code base.

Quoted 10 lines

We need lots of new transitions, we need to strive to make things better. But we need to do things in such a way that:

(1) we have a good idea of what we're going to end up with at the end of the day

(2) there is incremental value being added to QEMU at every step of the way

This cannot be done by simply hacking some bits here and there. It requires design, planning, and flag days when appropriate.

Agreed. The problem I have with QOM is (2). I am not sure we do get incremental value at every step of the way. We do get incremental value in the char layer, but we also get additional complexity until the transition is over.

Paolo

#35 lore raw
Quoted 20 lines · Paolo Bonzini

Yes, this looks nice (modulo s/Rtl8139/Rtl8139 */). But it is not that much more flexible than qdev 1.0.

You're right that for the case of two parents above we were looking at a contrived example. The Goldfish platform provides a more interesting one. There you have an interrupt controller and a bus enumerator device. Most devices are connected to both, but conflating them is wrong for many reasons;

1) the bus enumerator itself uses an interrupt (raised on hotplug);

2) you can enumerate devices that do not have an interrupt line, and you shouldn't need to connect such a device to an interrupt controller;

3) the interrupt controller and bus enumerator use two separate MMIO areas;

4) in principle, other devices could use the interrupt controller (which is the only component connected to the CPU's interrupt line) without being enumerated.

Quoted 6 lines

5) A device with two interrupts has two "interrupt interfaces" and only one "enumerator interface".

6) The enumerator interface does not have bus semantics. The enumerator also enumerates itself so it would act as both the bus host and a device on the bus.

I think I understand what your saying here. But interrupt routing is an interesting problem and I've been thinking about it differently then we do it today.

The core is:

class Pin : public Device {
bool level;
};

You can connect a signal to the level to detect edge changes. You can also connect two pins together such that if one raises high, the other raises high.

An interrupt controller looks like:

struct InterruptController
{
Pin *irq[256];
};

In the simple case, you have:

struct UART : public Device
{
Pin irq;
};

And then you'd set the irq by doing:

apic = new InterruptController()
uart = new UART()

apic->irq[0] = &uart->irq;

Or at the qmp layer:

(qemu) plug_get uart irq
uart::irq
(qemu) plug_set apic irq[0] uart::irq

I mention this because I don't think your example below assumes a model like this.

Quoted 7 lines

Composition then lets you use something like this:

class GoldfishPIC : Device {
Pin parent;
GoldfishInterruptPin *children[32];
Pin (*init_socket_for_irq_num) (GoldfishInterruptPin *, int); };

So the idea here is that the PIC will multiplex a bunch of interrupts into a single line? I would do this simply as:

class GoldfishPIC : Device {
Pin out;
Pin *in[32];
};

The IRQ number is implicit in the socket index, no? I'm also not sure that there's a strong need to have a typed Pin.

Quoted 13 lines

class GoldfishInterruptPin {
GoldfishPIC *pic;
Pin irqnum;
};

class GoldfishEnumerator : Device {
GoldfishInterruptPin irq;
GoldfishBusDeviceInfo info;
List<GoldfishBusDeviceInfo> allDevices;
...
};

Quoted 9 lines

class GoldfishBusDeviceInfo {
GoldfishEnumerator *parent;
char *name;
int id;
ram_addr_t mmio;
int mmio_size;
int irq_base;
int irq_count;
};

Is the enumerator something that has an interface to devices where the devices hold this info? Or is the enumerator just a bank of flash that's preprogrammed with fixed info?

If it's the later, I would suggest that we model is in that fashion. No need to teach every single device about the enumerator if they wouldn't normally have information about it.

Quoted 9 lines
Quoted 9 lines

We need lots of new transitions, we need to strive to make things better. But we need to do things in such a way that:

(1) we have a good idea of what we're going to end up with at the end of the day

(2) there is incremental value being added to QEMU at every step of the way

Quoted 7 lines
Quoted 2 lines

This cannot be done by simply hacking some bits here and there. It requires design, planning, and flag days when appropriate.

Agreed. The problem I have with QOM is (2). I am not sure we do get incremental value at every step of the way. We do get incremental value in the char layer, but we also get additional complexity until the transition is over.

So roughly speaking, my plan is:

1) Char layer
- we get dynamic add of CDS, which enables hot plug of virtio-serial
- we get ability to change CDS properties dynamically

2) Block layer
- we get -blockdev

3) Display layer
- we get dynamic add of VGA devices

4) fsdev
- dynamic add of virtio-9p devices

5) network layer
- no new features, but better commonality

At each phase, we also get significantly better modularity. The block layer is already good here, but the other backends aren't.

My only real concern is how to attack the device layer incrementally. I don't think it's impossible but it requires careful thought.

I think we can probably retrofit DeviceState as a QOM base class and just systematically convert the types over to QOM. The next step would be to change the property registration to be QOM-like. I think they we could probably push out a lot of what's in DeviceState today into another base class, then introduce a better Device base class. Since a lot of subsystems should just inherit from Device, that gives us a nice way to attack things one subsystem at a time.

I think an approach like this can have incremental value. The first step of retrofitting is pretty systematic and allows for devices be created and composed through the plug interfaces. I think we could pretty much eliminate machines after this phase which would be a huge win for compatibility.

Regards,

Anthony Liguori

Quoted 3 lines

Paolo

#36 lore raw
Quoted 3 lines · Anthony Liguori

So the idea here is that the PIC will multiplex a bunch of interrupts
into a single line?

Yes, but the device needs to know the interrupt number so it can expose it through the enumerator interface. So the configuration cannot be simply

   pic->irq[n] = tty->irq;

Logically, it's more similar to the ISA case, but I doubt the PIC distributes all interrupts to everyone in real hardware.

Quoted 3 lines

Is the enumerator something that has an interface to devices where the devices hold this info? Or is the enumerator just a bank of flash that's preprogrammed with fixed info?

The former, at least in theory. Not sure if it also works that way in real hardware, but that's the model it exposes and the way the Android guys implemented it.

The device model provides hotplug support, so it is definitely not just flash. Not sure again if this support is used in the hardware.

Quoted 1 line

At each phase, we also get significantly better modularity.

Fine, but when do we decide it's good enough to merge it? And what if it turns out that it's not suitable for devices? We unified some things, but we also dug ourselves in NIH when we could have used GObject. (GObject definitely does not work for devices, but at least we don't need to write the infrastructure).

Quoted 2 lines

My only real concern is how to attack the device layer incrementally. I don't think it's impossible but it requires careful thought.

No idea here, honestly. :)

Paolo

#37 lore raw
Quoted 17 lines · Paolo Bonzini
Quoted 3 lines · Anthony Liguori

So the idea here is that the PIC will multiplex a bunch of interrupts into a single line?

Yes, but the device needs to know the interrupt number so it can expose it through the enumerator interface. So the configuration cannot be simply

pic->irq[n] = tty->irq;

Logically, it's more similar to the ISA case, but I doubt the PIC distributes all interrupts to everyone in real hardware.

Quoted 3 lines

Is the enumerator something that has an interface to devices where the devices hold this info? Or is the enumerator just a bank of flash that's preprogrammed with fixed info?

Quoted 6 lines

The former, at least in theory. Not sure if it also works that way in real hardware, but that's the model it exposes and the way the Android guys implemented it.

The device model provides hotplug support, so it is definitely not just flash. Not sure again if this support is used in the hardware.

Sounds like I need to read a little about how this enumerator works. I can't see how this would all operate without the enumerating being some form of a bus.

Quoted 4 lines
Quoted 2 lines

At each phase, we also get significantly better modularity.

Fine, but when do we decide it's good enough to merge it?

I think we should evaluate the complexity vs. value trade off with the character device layer (when fully converted) and make the decision in a vacuum.

If the complexity seems too high, I can try to also convert the block layer and we can reevaluate. I believe that just with the character device layer, it's a net win and I don't think it can be dramatically simplified. The patches are actually not a lot of code. The only complexity is conceptual and that's because it takes into account a lot of different problems.

I can even pair things down a bit by removing support for Interfaces and simplifying class initialization of need be for the first merge.

Quoted 5 lines

And what if it
turns out that it's not suitable for devices? We unified some things, but we also dug ourselves in NIH when we could have used GObject. (GObject definitely does not work for devices, but at least we don't need to write the infrastructure).

I tried to use GObject btw, I can share the results with you if you'd like. Even with backends, I couldn't make properties work. GObject uses GValues for properties which roughly models immutable values in a variant. But I couldn't find a reasonable way to express Plugs and Sockets in terms of GValues.

I expect that at some point in the future, GObject will grow GVariant properties. But I still think GVariant isn't quite what it needs to be since it still assumes immutable variants that can be copied.

I thought about just using GType but I thought using GType without using GObject was probably not a great long term plan as I doubt anyone else does this.

Regards,

Anthony Liguori

Quoted 8 lines
Quoted 3 lines

My only real concern is how to attack the device layer incrementally. I don't think it's impossible but it requires careful thought.

No idea here, honestly. :)

Paolo

#38 lore raw
In reply to Paolo Bonzini
Quoted 13 lines · Paolo Bonzini
Quoted 3 lines · Anthony Liguori

So the idea here is that the PIC will multiplex a bunch of interrupts into a single line?

Yes, but the device needs to know the interrupt number so it can expose it through the enumerator interface. So the configuration cannot be simply

pic->irq[n] = tty->irq;

Logically, it's more similar to the ISA case, but I doubt the PIC distributes all interrupts to everyone in real hardware.

Quoted 7 lines
Quoted 3 lines

Is the enumerator something that has an interface to devices where the devices hold this info? Or is the enumerator just a bank of flash that's preprogrammed with fixed info?

The former, at least in theory. Not sure if it also works that way in real hardware, but that's the model it exposes and the way the Android guys implemented it.

I can't really find what you're describing. I think all the specs are on http://www.milkymist.org/mmsoc.html

It's seems like there are a couple different kinds of busses, and that there is a CSR bus that is used to access configuration information but I believe only for CSR devices (which are low speed).

Can you point me towards the current code for this?

Regards,

Anthony Liguori

#39 lore raw
Quoted 19 lines · Anthony Liguori
Quoted 18 lines · Paolo Bonzini
Quoted 3 lines · Anthony Liguori

So the idea here is that the PIC will multiplex a bunch of interrupts into a single line?

Yes, but the device needs to know the interrupt number so it can expose it through the enumerator interface. So the configuration cannot be simply

pic->irq[n] = tty->irq;

Logically, it's more similar to the ISA case, but I doubt the PIC distributes all interrupts to everyone in real hardware.

Quoted 3 lines

Is the enumerator something that has an interface to devices where the devices hold this info? Or is the enumerator just a bank of flash that's preprogrammed with fixed info?

Quoted 6 lines
Quoted 3 lines

The former, at least in theory. Not sure if it also works that way in real hardware, but that's the model it exposes and the way the Android guys implemented it.

I can't really find what you're describing. I think all the specs are on
http://www.milkymist.org/mmsoc.html

That's milkymist, not GoldFish.

You can see the code at https://github.com/patricksjackson/qemu/blob/android/hw/goldfish_device.c (see also https://github.com/patricksjackson/qemu/blob/android/hw/goldfish_device.h for the structs composing the list).

Paolo

#40 lore raw
Quoted 20 lines · Paolo Bonzini
Quoted 19 lines · Anthony Liguori
Quoted 18 lines · Paolo Bonzini
Quoted 3 lines · Anthony Liguori

So the idea here is that the PIC will multiplex a bunch of interrupts into a single line?

Yes, but the device needs to know the interrupt number so it can expose it through the enumerator interface. So the configuration cannot be simply

pic->irq[n] = tty->irq;

Logically, it's more similar to the ISA case, but I doubt the PIC distributes all interrupts to everyone in real hardware.

Quoted 3 lines

Is the enumerator something that has an interface to devices where the devices hold this info? Or is the enumerator just a bank of flash that's preprogrammed with fixed info?

Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

The former, at least in theory. Not sure if it also works that way in real hardware, but that's the model it exposes and the way the Android guys implemented it.

I can't really find what you're describing. I think all the specs are on
http://www.milkymist.org/mmsoc.html

That's milkymist, not GoldFish.

Oh, Goldfish is fake. It's not real hardware.

The enumerator device is not a real device. It's weird because it's imaginary and was designed specifically within QEMU.

It's not a good example for discussing modelling.

Regards,

Anthony Liguori

Quoted 9 lines

You can see the code at
https://github.com/patricksjackson/qemu/blob/android/hw/goldfish_device.c (see also
https://github.com/patricksjackson/qemu/blob/android/hw/goldfish_device.h for the structs composing the list).

Paolo

#41 lore raw
Quoted 10 lines · Anthony Liguori
Quoted 3 lines
Quoted 1 line

That's milkymist, not GoldFish.

Oh, Goldfish is fake. It's not real hardware.

The enumerator device is not a real device. It's weird because it's imaginary and was designed specifically within QEMU.

It's not a good example for discussing modelling.

There are plenty of PV interfaces implemented by QEMU. Would you say the same of virtio?

Paolo

#42 lore raw
Quoted 7 lines · Paolo Bonzini
Quoted 6 lines · Anthony Liguori
Quoted 3 lines
Quoted 1 line

That's milkymist, not GoldFish.

Oh, Goldfish is fake. It's not real hardware.

Quoted 7 lines
Quoted 4 lines

The enumerator device is not a real device. It's weird because it's imaginary and was designed specifically within QEMU.

It's not a good example for discussing modelling.

There are plenty of PV interfaces implemented by QEMU. Would you say the same of virtio?

Virtio was designed to look like real hardware.

I would say that trying to fit XenStore into QOM would not be a good exercise.

Regards,

Anthony Liguori

Quoted 3 lines

Paolo

#43 lore raw
Quoted 8 lines · Anthony Liguori
Quoted 3 lines

There are plenty of PV interfaces implemented by QEMU. Would you say the same of virtio?

Virtio was designed to look like real hardware.

I would say that trying to fit XenStore into QOM would not be a good exercise.

No doubt about that. :) I'd put a lot more hope into Goldfish though.

Paolo

#44 lore raw
Quoted 11 lines · Paolo Bonzini
Quoted 8 lines · Anthony Liguori
Quoted 3 lines

There are plenty of PV interfaces implemented by QEMU. Would you say the same of virtio?

Virtio was designed to look like real hardware.

I would say that trying to fit XenStore into QOM would not be a good exercise.

No doubt about that. :) I'd put a lot more hope into Goldfish though.

What's unclear to me about the Goldfish enumerator is whether it should be filled out through interaction with hardware devices or via some other mechanism.

In many ways, it's similar to ACPI and a Device Tree. In both of those cases, firmware actually is responsible for constructing those tables.

Regards,

Anthony Liguori

Quoted 3 lines

Paolo

#45 lore raw
Quoted 8 lines · Anthony Liguori
Quoted 1 line

No doubt about that. :) I'd put a lot more hope into Goldfish though.

What's unclear to me about the Goldfish enumerator is whether it should be filled out through interaction with hardware devices or via some other mechanism.

In many ways, it's similar to ACPI and a Device Tree. In both of those cases, firmware actually is responsible for constructing those tables.

Yes, it is a flat device tree.

Since it supports hotplug (at least in theory, the Android emulator predates qdev so it doesn't support it), I would say it is more similar to PCI configuration space. The difference is that IRQ numbers and MMIO base addresses are handed out by hardware (by a piece of the SoC) rather than by the firmware.

So yes, the hardware would have some kind of bus to talk to the devices and arbitrate hotplug/hotunplug. The only peculiarity being that the bus enumerator hardcodes itself in the list it exposes, in addition to the devices on the bus.

But that still means that the devices have two views:

1) the enumerator's view is either "this is my name, my MMIO base, my IRQ base" or "I need 4k of MMIO and 1 IRQ line, please tell me where/which are those", depending on the device;

2) the PIC's view is "please bring this IRQ line up/down" (the device says which line, since the enumerator can assign those dynamically).

The PIC's view is more complicated than a Pin, and more similar to ISA.

Paolo

#46 lore raw
Quoted 23 lines · Paolo Bonzini
Quoted 8 lines · Anthony Liguori
Quoted 1 line

No doubt about that. :) I'd put a lot more hope into Goldfish though.

What's unclear to me about the Goldfish enumerator is whether it should be filled out through interaction with hardware devices or via some other mechanism.

In many ways, it's similar to ACPI and a Device Tree. In both of those cases, firmware actually is responsible for constructing those tables.

Yes, it is a flat device tree.

Since it supports hotplug (at least in theory, the Android emulator predates qdev so it doesn't support it), I would say it is more similar to PCI configuration space. The difference is that IRQ numbers and MMIO base addresses are handed out by hardware (by a piece of the SoC) rather than by the firmware.

So yes, the hardware would have some kind of bus to talk to the devices and arbitrate hotplug/hotunplug. The only peculiarity being that the bus enumerator hardcodes itself in the list it exposes, in addition to the devices on the bus.

Quoted 5 lines

But that still means that the devices have two views:

1) the enumerator's view is either "this is my name, my MMIO base, my IRQ base" or "I need 4k of MMIO and 1 IRQ line, please tell me where/which are those", depending on the device;

I think it's important to ask, how would this be implemented in hardware. The only way I can see is to teach each device about this interface and then have a common bus. That implies that you have:

class GoldfishEnumerator : public Device {
     GoldfishDevice *slots[N];
};
interface GoldfishDevice {
     const char *get_name();
     uint64_t get_mmio_base();
     ...
};

class GoldfishNic : public Device, implements GoldfishDevice

{
    const char *get_name(void) {
        return "nic";
    }
};

With respect to hotplug, that means that you have to hot plug the device to multiple busses.

Quoted 4 lines

2) the PIC's view is "please bring this IRQ line up/down" (the device says which line, since the enumerator can assign those dynamically).

The PIC's view is more complicated than a Pin, and more similar to ISA.

ISA is just a pin. The ISA bus extender literally has five pins corresponding to the ISA IRQs 7, 6, 5, 4, 3.

EISA adds 5 more pins for 10, 11, 12, 14, 15.

ISA devices "choose" their IRQ line by hardwiring their IRQ output pin to a specific IRQ line on the bus.

Regards,

Anthony Liguori

Quoted 3 lines

Paolo

#47 lore raw
Quoted 5 lines · Anthony Liguori

The only way I can see is to teach each device about this interface and then have a common bus. That implies that you have:

class GoldfishEnumerator : public Device {
      GoldfishDevice *slots[N];

FWIW, there's no hardcoded limit in the interface, and the list of devices is unordered. But that only means you should attach it with

plug-set goldfish_tty::enumerator goldfish_enum

rather than

plug-set goldfish_enum::slots[12] goldfish_tty

If you can confirm that, that's fine.

Quoted 8 lines

};

interface GoldfishDevice {
      const char *get_name();
      uint64_t get_mmio_base();
      ...
};
Quoted 5 lines

class GoldfishNic : public Device, implements GoldfishDevice

{
     const char *get_name(void) {
         return "nic";
     }
     uint64_t mmio_base;
     uint64_t get_mmio_base() { return mmio_base; }
     uint64_t set_mmio_base(uint64_t addr) { mmio_base = addr; }
Quoted 1 line

};

And that's exactly my point. It's a "stupid" interface full of getters/setters, which is what you get if you use only interface inheritance instead of, where appropriate, data containment.

Interfaces should be reserved for what really depends on the _implementation_ of the GoldfishNic, not for accessing a bunch of numbers. There is no implementation-dependent detail of that kind in the GoldfishDevice (unlike other buses, even simple ones like I2C).

Quoted 4 lines
Quoted 1 line

The PIC's view is more complicated than a Pin, and more similar to ISA.

ISA is just a pin. The ISA bus extender literally has five pins corresponding to the ISA IRQs 7, 6, 5, 4, 3.

ISA is many pins. :) Goldfish looks similar (32 pins).

Paolo

#48 lore raw
Quoted 10 lines · Paolo Bonzini
Quoted 5 lines · Anthony Liguori

The only way I can see is to teach each device about this interface and then have a common bus. That implies that you have:

class GoldfishEnumerator : public Device {
GoldfishDevice *slots[N];

FWIW, there's no hardcoded limit in the interface, and the list of devices is unordered. But that only means you should attach it with

Quoted 7 lines

plug-set goldfish_tty::enumerator goldfish_enum

rather than

plug-set goldfish_enum::slots[12] goldfish_tty

If you can confirm that, that's fine.

Yes, you can certainly have an enumerator socket that when set, automatically connects the appropriate properties in the enumerator.

That way you don't have to connect things by hand.

Quoted 18 lines
Quoted 8 lines

};

interface GoldfishDevice {
const char *get_name();
uint64_t get_mmio_base();
...
};

Quoted 5 lines

class GoldfishNic : public Device, implements GoldfishDevice {
const char *get_name(void) {
return "nic";
}

uint64_t mmio_base;
uint64_t get_mmio_base() { return mmio_base; } uint64_t set_mmio_base(uint64_t addr) { mmio_base = addr; }

Quoted 6 lines
Quoted 1 line

};

And that's exactly my point. It's a "stupid" interface full of getters/setters, which is what you get if you use only interface inheritance instead of, where appropriate, data containment.

You can certainly do:

struct GoldfishEnumInfo

{
    const char *name;
    uint64_t mmio_base;
};
interface GoldfishDevice {
    GoldfishEnumInfo *get_info();
}

And then:

GoldfishEnumInfo *goldfish_nic_get_info(GoldFishNic *nic)

{
    return nic->enuminfo;
}
Quoted 3 lines

Interfaces should be reserved for what really depends on the _implementation_ of the GoldfishNic, not for accessing a bunch of numbers.

Just define an interface that returns a struct then. It's no more complicated than that.

What I struggle with is whether you're suggesting that the info isn't part of the device or whether it is part of the device and you just think that we shouldn't need 10 different accessors.

Quoted 9 lines

There is no implementation-dependent detail of that kind in the GoldfishDevice (unlike other buses, even simple ones like I2C).

Quoted 4 lines
Quoted 1 line

The PIC's view is more complicated than a Pin, and more similar to ISA.

ISA is just a pin. The ISA bus extender literally has five pins corresponding to the ISA IRQs 7, 6, 5, 4, 3.

ISA is many pins. :) Goldfish looks similar (32 pins).

Sorry, I meant to say ISA IRQs are just exposed as pins.

My real point is, doing:

class IsaDevice : public Device {
Pin irq[16];
};

class MyIsaDevice : public IsaDevice {
int irq_index;
};

And then doing:

my_isa_device->irq_index = 5;

Is a very good way to model ISA IRQ selection.

You can simplify it by having a single IRQ output for each ISA device instead of any possible IRQ and then route the IRQ as part of the bus connection.

Regards,

Anthony Liguori

Quoted 2 lines

Paolo

#49 lore raw
Quoted 2 lines · Anthony Liguori

Just define an interface that returns a struct then. It's no more complicated than that.

Ok, so we're debating whether to: 1) add an interface returning a pointer to an internal struct; 2) include in the internal struct a pointer-to-function that does a container_of and returns the outer Device object. Otherwise, we're on the same page. I'm quite relieved. ;)

I can see advantages to both approach. The main advantage to (2) is that it scales better when you have multiple interfaces of the same kind exposed by the device. You cannot implement an interface twice.

Paolo

#50 lore raw
In reply to Anthony Liguori
Quoted 6 lines · Anthony Liguori

In my attempt at PCI modelling, I had something like:

struct I440FX
{
  Device parent;

Quoted 6 lines

  PciDevice slots[32];
};

Which means that to attach to bus 0, slot 3, fn 0, you do:

i440fx->slots[3] = mydevice

So what I don't really understand about this model is why the PCI connection is "privileged" in the sense that 'mydevice' is actually an instance of something you can stick directly into one of the PCIBus device's slots. I would expect that 'mydevice' would have a bunch of (effectively) interfaces it exposed, and you'd connect i440fx->slots[3] to mydevice.pciconnector or something. [Which ought to both let the PCIBus call functions implemented by the device, and vice versa.]

(What would a model of a two-PCI-slot graphics card look like?)

Maybe it would be better to use some other example. After all, the cases like PCI are the ones our device model already handles pretty well, so the interesting cases to look at are where we're not so good at it. What does the implementation of omap2_gpio look like, for instance? (it's not qdev at the moment but there's a set of patches on the list which make it so; the guts of the qdevification are http://patchwork.ozlabs.org/patch/103905/ .)
That's a device which exposes:
* 4,5, or 6 MMIO regions (depending on how many 'modules' the particular revision you ask for has)
* a variably sized array of gpio inputs
* ditto, gpio outputs
* for each 'module', three specific named outgoing gpio lines "mpu_irq", "dsp_irq" and "wakeup"
* a number of omap_clk connections, where an omap_clk* represents a connection to the OMAP clock tree, and in practice is an interface where the omap_gpio can (a) call a function to ask "what rate is this clock running at?" and (b) provide a gpio line which will be raised when the clock ticks. [omap_gpio doesn't actually use its clock connections but other omap devices do; they're interesting because we have function calls going in both directions over the interface.]

None of these exposed interfaces are particularly obviously more important than any of the others -- they're just all things that might need to be wired up.

I'm particularly interested in how much effort is involved in defining ad-hoc platform-specific interface types like omap_clk.

-- PMM

#51 lore raw
Quoted 10 lines · Peter Maydell
Quoted 9 lines · Anthony Liguori

In my attempt at PCI modelling, I had something like:

struct I440FX

{
   Device parent;

   PciDevice slots[32];
};
Quoted 8 lines
Quoted 3 lines

Which means that to attach to bus 0, slot 3, fn 0, you do:

i440fx->slots[3] = mydevice

So what I don't really understand about this model is why the PCI connection is "privileged" in the sense that 'mydevice' is actually an instance of something you can stick directly into one of the PCIBus device's slots.

Oh, it's not privileged at all. It just happens to be that modelling something simple is simple. That's goodness.

The example that I used for most of my early testing was meant to be a bit more interesting. I created a Source, Sink, XorGate, AndGate, and OrGate and then used a config file to build a full working 8-bit adder.

You can see this at:

http://repo.or.cz/w/qemu/aliguori.git/blob/refs/heads/qdev2

Check out devices/gates and vm.cfg.

Here's a rough model of how it works:

struct XorGate
{
Device parent;
Pin out;
Pin *in[2];
};

In XorGate's initfn, it registers three properties, 'in[0]' and 'in[1]' as 'socket<Pin>'s and 'out' as 'plug<Pin>'.

When XorGate is realized, it makes sure that both in[0] and in[1] have been set (sockets are RW whereas plugs are RO). It then connects to the edge event on the in[0] and in[1] pins and when either event fires, it will compute a value, and set the level of out.

XorGate is-a Device, but so is Pin. The following things are valid:

(qemu) plug_create xor-gate gate0
(qemu) plug_create xor-gate gate1
(qemu) plug_create xor-gate gate2
(qemu) plug_get gate1 out
gate1::out
(qemu) plug_set xor-gate in[0] gate1::out
(qemu) plug_get gate2 out
gate2::out
(qemu) plug_set xor-gate in[1] gate2::out

Which creates a simple tree of two xor gates who's outputs are tied to another xor gate. Or:

XorGate /

- XorGate /        \
          \
           XorGate /
                   \

The 'out' property of XorGate is really a child device. All devices (all plugs for that matter) have a global namespace. By convention, uniqueness in name is guaranteed for child devices by reserving the '::' separator and naming children based on 'parentname::propertyname'. But for correctness, the right way to figure out the name of a child is by reading the property.

So to answer your above question, a multi PCI slot graphics adapter is simply:

struct GraphicsSlot {
PciDevice parent;
};

struct MultislotGraphicsCard {
Device parent;

GraphicsSlot slot[2];
};

Then conceptually:

mgc = new MultislotGraphicsCard();

i440fx->slot[1] = mgc.slot[0];
i440fx->slot[2] = mgc.slot[1];

You do not need to ever assign a device directly to a socket. This is a fundamental different between QOM and qdev. There is no concept of "parent bus". There's no concept of parent--even with composition. Devices can have links to zero or more other Devices. They can also create devices within themselves but those devices don't have any special knowledge of that fact.

Quoted 7 lines

I would expect that 'mydevice' would have a bunch of
(effectively) interfaces it exposed, and you'd connect i440fx->slots[3] to mydevice.pciconnector or something. [Which ought to both let the PCIBus call functions implemented by the device, and vice versa.]

(What would a model of a two-PCI-slot graphics card look like?)

Quoted 12 lines

Maybe it would be better to use some other example. After all, the cases like PCI are the ones our device model already handles pretty well, so the interesting cases to look at are where we're not so good at it. What does the implementation of omap2_gpio look like, for instance? (it's not qdev at the moment but there's a set of patches on the list which make it so; the guts of the qdevification are http://patchwork.ozlabs.org/patch/103905/ .)
That's a device which exposes:
* 4,5, or 6 MMIO regions (depending on how many 'modules' the particular revision you ask for has)
* a variably sized array of gpio inputs
* ditto, gpio outputs

struct OmapGpio

{
    Device parent;

    size_t nb_regions;
    MemoryRegion *regions;

    size_t nb_out;
    Pin *out;

    size_t nb_in;
    Pin **in;
};

void omap_gpio_set_nb_out(OmapGpio *obj, size_t value); void omap_gpio_set_nb_in(OmapGpio *obj, size_t value); void omap_gpio_set_nb_regions(OmapGpio *obj, size_t value);

At initfn(), you register three integer properties, 'nb_out', 'nb_in', 'nb_regions'.

In the respective setters, you allocate the appropriate array and then unregister the old properties, and then register teh new ones. For instance:

void omap_gpio_set_nb_out(OmapGpio *obj, size_t value) {
/* remove old properties */

   for (i = 0; i < obj->nb_out; i++) {
       plug_del_property_plug(PLUG(obj), "out[%d]", i);

}

   obj->out = realloc(obj->out, new_size);
   obj->nb_out = value;

/* add new properties */

   for (i = 0; i < obj->nb_out; i++) {
       plug_add_property_plug(PLUG(obj), &obj->pin[i],
                              TYPE_PIN, "out[%d]", i);

}
}

This would let you work with the device like this:

[OmapGpio "gpio"]
nb_out = 4
nb_in = 2
in[0] = "foo.out[0]"
in[1] = "foo.out[1]"

[OmapFoo "foo"]
bar = "gpio.out[3]"

It's exactly this use-case which makes GObject unsuitable. Properties need to be associated with the instance, not the class. qdev also suffers from this problem.

Regards,

Anthony Liguori

Quoted 21 lines

* for each 'module', three specific named outgoing gpio lines

    "mpu_irq", "dsp_irq" and "wakeup"

* a number of omap_clk connections, where an omap_clk* represents a connection to the OMAP clock tree, and in practice is an interface where the omap_gpio can (a) call a function to ask "what rate is this clock running at?" and (b) provide a gpio line which will be raised when the clock ticks. [omap_gpio doesn't actually use its clock connections but other omap devices do; they're interesting because we have function calls going in both directions over the interface.]

None of these exposed interfaces are particularly obviously more important than any of the others -- they're just all things that might need to be wired up.

I'm particularly interested in how much effort is involved in defining ad-hoc platform-specific interface types like omap_clk.

-- PMM