xref: /openbmc/qemu/docs/devel/qom.rst (revision 7d87775f)
1.. _qom:
2
3===========================
4The QEMU Object Model (QOM)
5===========================
6
7.. highlight:: c
8
9The QEMU Object Model provides a framework for registering user creatable
10types and instantiating objects from those types.  QOM provides the following
11features:
12
13- System for dynamically registering types
14- Support for single-inheritance of types
15- Multiple inheritance of stateless interfaces
16- Mapping internal members to publicly exposed properties
17
18The root object class is TYPE_OBJECT which provides for the basic
19object methods.
20
21The QOM tree
22============
23
24The QOM tree is a composition tree which represents all of the objects
25that make up a QEMU "machine". You can view this tree by running
26``info qom-tree`` in the :ref:`QEMU monitor`. It will contain both
27objects created by the machine itself as well those created due to
28user configuration.
29
30Creating a QOM class
31====================
32
33A simple minimal device implementation may look something like below:
34
35.. code-block:: c
36   :caption: Creating a minimal type
37
38   #include "qdev.h"
39
40   #define TYPE_MY_DEVICE "my-device"
41
42   // No new virtual functions: we can reuse the typedef for the
43   // superclass.
44   typedef DeviceClass MyDeviceClass;
45   typedef struct MyDevice
46   {
47       DeviceState parent_obj;
48
49       int reg0, reg1, reg2;
50   } MyDevice;
51
52   static const TypeInfo my_device_info = {
53       .name = TYPE_MY_DEVICE,
54       .parent = TYPE_DEVICE,
55       .instance_size = sizeof(MyDevice),
56   };
57
58   static void my_device_register_types(void)
59   {
60       type_register_static(&my_device_info);
61   }
62
63   type_init(my_device_register_types)
64
65In the above example, we create a simple type that is described by #TypeInfo.
66#TypeInfo describes information about the type including what it inherits
67from, the instance and class size, and constructor/destructor hooks.
68
69The TYPE_DEVICE class is the parent class for all modern devices
70implemented in QEMU and adds some specific methods to handle QEMU
71device model. This includes managing the lifetime of devices from
72creation through to when they become visible to the guest and
73eventually unrealized.
74
75Alternatively several static types could be registered using helper macro
76DEFINE_TYPES()
77
78.. code-block:: c
79
80   static const TypeInfo device_types_info[] = {
81       {
82           .name = TYPE_MY_DEVICE_A,
83           .parent = TYPE_DEVICE,
84           .instance_size = sizeof(MyDeviceA),
85       },
86       {
87           .name = TYPE_MY_DEVICE_B,
88           .parent = TYPE_DEVICE,
89           .instance_size = sizeof(MyDeviceB),
90       },
91   };
92
93   DEFINE_TYPES(device_types_info)
94
95Every type has an #ObjectClass associated with it.  #ObjectClass derivatives
96are instantiated dynamically but there is only ever one instance for any
97given type.  The #ObjectClass typically holds a table of function pointers
98for the virtual methods implemented by this type.
99
100Using object_new(), a new #Object derivative will be instantiated.  You can
101cast an #Object to a subclass (or base-class) type using
102object_dynamic_cast().  You typically want to define macro wrappers around
103OBJECT_CHECK() and OBJECT_CLASS_CHECK() to make it easier to convert to a
104specific type:
105
106.. code-block:: c
107   :caption: Typecasting macros
108
109   #define MY_DEVICE_GET_CLASS(obj) \
110      OBJECT_GET_CLASS(MyDeviceClass, obj, TYPE_MY_DEVICE)
111   #define MY_DEVICE_CLASS(klass) \
112      OBJECT_CLASS_CHECK(MyDeviceClass, klass, TYPE_MY_DEVICE)
113   #define MY_DEVICE(obj) \
114      OBJECT_CHECK(MyDevice, obj, TYPE_MY_DEVICE)
115
116In case the ObjectClass implementation can be built as module a
117module_obj() line must be added to make sure qemu loads the module
118when the object is needed.
119
120.. code-block:: c
121
122   module_obj(TYPE_MY_DEVICE);
123
124Class Initialization
125--------------------
126
127Before an object is initialized, the class for the object must be
128initialized.  There is only one class object for all instance objects
129that is created lazily.
130
131Classes are initialized by first initializing any parent classes (if
132necessary).  After the parent class object has initialized, it will be
133copied into the current class object and any additional storage in the
134class object is zero filled.
135
136The effect of this is that classes automatically inherit any virtual
137function pointers that the parent class has already initialized.  All
138other fields will be zero filled.
139
140Once all of the parent classes have been initialized, #TypeInfo::class_init
141is called to let the class being instantiated provide default initialize for
142its virtual functions.  Here is how the above example might be modified
143to introduce an overridden virtual function:
144
145.. code-block:: c
146   :caption: Overriding a virtual function
147
148   #include "qdev.h"
149
150   void my_device_class_init(ObjectClass *klass, void *class_data)
151   {
152       DeviceClass *dc = DEVICE_CLASS(klass);
153       dc->reset = my_device_reset;
154   }
155
156   static const TypeInfo my_device_info = {
157       .name = TYPE_MY_DEVICE,
158       .parent = TYPE_DEVICE,
159       .instance_size = sizeof(MyDevice),
160       .class_init = my_device_class_init,
161   };
162
163Introducing new virtual methods requires a class to define its own
164struct and to add a .class_size member to the #TypeInfo.  Each method
165will also have a wrapper function to call it easily:
166
167.. code-block:: c
168   :caption: Defining an abstract class
169
170   #include "qdev.h"
171
172   typedef struct MyDeviceClass
173   {
174       DeviceClass parent_class;
175
176       void (*frobnicate) (MyDevice *obj);
177   } MyDeviceClass;
178
179   static const TypeInfo my_device_info = {
180       .name = TYPE_MY_DEVICE,
181       .parent = TYPE_DEVICE,
182       .instance_size = sizeof(MyDevice),
183       .abstract = true, // or set a default in my_device_class_init
184       .class_size = sizeof(MyDeviceClass),
185   };
186
187   void my_device_frobnicate(MyDevice *obj)
188   {
189       MyDeviceClass *klass = MY_DEVICE_GET_CLASS(obj);
190
191       klass->frobnicate(obj);
192   }
193
194Interfaces
195----------
196
197Interfaces allow a limited form of multiple inheritance.  Instances are
198similar to normal types except for the fact that are only defined by
199their classes and never carry any state.  As a consequence, a pointer to
200an interface instance should always be of incomplete type in order to be
201sure it cannot be dereferenced.  That is, you should define the
202'typedef struct SomethingIf SomethingIf' so that you can pass around
203``SomethingIf *si`` arguments, but not define a ``struct SomethingIf { ... }``.
204The only things you can validly do with a ``SomethingIf *`` are to pass it as
205an argument to a method on its corresponding SomethingIfClass, or to
206dynamically cast it to an object that implements the interface.
207
208Methods
209-------
210
211A *method* is a function within the namespace scope of
212a class. It usually operates on the object instance by passing it as a
213strongly-typed first argument.
214If it does not operate on an object instance, it is dubbed
215*class method*.
216
217Methods cannot be overloaded. That is, the #ObjectClass and method name
218uniquely identity the function to be called; the signature does not vary
219except for trailing varargs.
220
221Methods are always *virtual*. Overriding a method in
222#TypeInfo.class_init of a subclass leads to any user of the class obtained
223via OBJECT_GET_CLASS() accessing the overridden function.
224The original function is not automatically invoked. It is the responsibility
225of the overriding class to determine whether and when to invoke the method
226being overridden.
227
228To invoke the method being overridden, the preferred solution is to store
229the original value in the overriding class before overriding the method.
230This corresponds to ``{super,base}.method(...)`` in Java and C#
231respectively; this frees the overriding class from hardcoding its parent
232class, which someone might choose to change at some point.
233
234.. code-block:: c
235   :caption: Overriding a virtual method
236
237   typedef struct MyState MyState;
238
239   typedef void (*MyDoSomething)(MyState *obj);
240
241   typedef struct MyClass {
242       ObjectClass parent_class;
243
244       MyDoSomething do_something;
245   } MyClass;
246
247   static void my_do_something(MyState *obj)
248   {
249       // do something
250   }
251
252   static void my_class_init(ObjectClass *oc, void *data)
253   {
254       MyClass *mc = MY_CLASS(oc);
255
256       mc->do_something = my_do_something;
257   }
258
259   static const TypeInfo my_type_info = {
260       .name = TYPE_MY,
261       .parent = TYPE_OBJECT,
262       .instance_size = sizeof(MyState),
263       .class_size = sizeof(MyClass),
264       .class_init = my_class_init,
265   };
266
267   typedef struct DerivedClass {
268       MyClass parent_class;
269
270       MyDoSomething parent_do_something;
271   } DerivedClass;
272
273   static void derived_do_something(MyState *obj)
274   {
275       DerivedClass *dc = DERIVED_GET_CLASS(obj);
276
277       // do something here
278       dc->parent_do_something(obj);
279       // do something else here
280   }
281
282   static void derived_class_init(ObjectClass *oc, void *data)
283   {
284       MyClass *mc = MY_CLASS(oc);
285       DerivedClass *dc = DERIVED_CLASS(oc);
286
287       dc->parent_do_something = mc->do_something;
288       mc->do_something = derived_do_something;
289   }
290
291   static const TypeInfo derived_type_info = {
292       .name = TYPE_DERIVED,
293       .parent = TYPE_MY,
294       .class_size = sizeof(DerivedClass),
295       .class_init = derived_class_init,
296   };
297
298Alternatively, object_class_by_name() can be used to obtain the class and
299its non-overridden methods for a specific type. This would correspond to
300``MyClass::method(...)`` in C++.
301
302One example of such methods is ``DeviceClass.reset``. More examples
303can be found at :ref:`device-life-cycle`.
304
305Standard type declaration and definition macros
306===============================================
307
308A lot of the code outlined above follows a standard pattern and naming
309convention. To reduce the amount of boilerplate code that needs to be
310written for a new type there are two sets of macros to generate the
311common parts in a standard format.
312
313A type is declared using the OBJECT_DECLARE macro family. In types
314which do not require any virtual functions in the class, the
315OBJECT_DECLARE_SIMPLE_TYPE macro is suitable, and is commonly placed
316in the header file:
317
318.. code-block:: c
319   :caption: Declaring a simple type
320
321   OBJECT_DECLARE_SIMPLE_TYPE(MyDevice, MY_DEVICE)
322
323This is equivalent to the following:
324
325.. code-block:: c
326   :caption: Expansion from declaring a simple type
327
328   typedef struct MyDevice MyDevice;
329   typedef struct MyDeviceClass MyDeviceClass;
330
331   G_DEFINE_AUTOPTR_CLEANUP_FUNC(MyDeviceClass, object_unref)
332
333   #define MY_DEVICE_GET_CLASS(void *obj) \
334           OBJECT_GET_CLASS(MyDeviceClass, obj, TYPE_MY_DEVICE)
335   #define MY_DEVICE_CLASS(void *klass) \
336           OBJECT_CLASS_CHECK(MyDeviceClass, klass, TYPE_MY_DEVICE)
337   #define MY_DEVICE(void *obj)
338           OBJECT_CHECK(MyDevice, obj, TYPE_MY_DEVICE)
339
340   struct MyDeviceClass {
341       DeviceClass parent_class;
342   };
343
344The 'struct MyDevice' needs to be declared separately.
345If the type requires virtual functions to be declared in the class
346struct, then the alternative OBJECT_DECLARE_TYPE() macro can be
347used. This does the same as OBJECT_DECLARE_SIMPLE_TYPE(), but without
348the 'struct MyDeviceClass' definition.
349
350To implement the type, the OBJECT_DEFINE macro family is available.
351For the simplest case of a leaf class which doesn't need any of its
352own virtual functions (i.e. which was declared with OBJECT_DECLARE_SIMPLE_TYPE)
353the OBJECT_DEFINE_SIMPLE_TYPE macro is suitable:
354
355.. code-block:: c
356   :caption: Defining a simple type
357
358   OBJECT_DEFINE_SIMPLE_TYPE(MyDevice, my_device, MY_DEVICE, DEVICE)
359
360This is equivalent to the following:
361
362.. code-block:: c
363   :caption: Expansion from defining a simple type
364
365   static void my_device_finalize(Object *obj);
366   static void my_device_class_init(ObjectClass *oc, void *data);
367   static void my_device_init(Object *obj);
368
369   static const TypeInfo my_device_info = {
370       .parent = TYPE_DEVICE,
371       .name = TYPE_MY_DEVICE,
372       .instance_size = sizeof(MyDevice),
373       .instance_init = my_device_init,
374       .instance_finalize = my_device_finalize,
375       .class_init = my_device_class_init,
376   };
377
378   static void
379   my_device_register_types(void)
380   {
381       type_register_static(&my_device_info);
382   }
383   type_init(my_device_register_types);
384
385This is sufficient to get the type registered with the type
386system, and the three standard methods now need to be implemented
387along with any other logic required for the type.
388
389If the class needs its own virtual methods, or has some other
390per-class state it needs to store in its own class struct,
391then you can use the OBJECT_DEFINE_TYPE macro. This does the
392same thing as OBJECT_DEFINE_SIMPLE_TYPE, but it also sets the
393class_size of the type to the size of the class struct.
394
395.. code-block:: c
396   :caption: Defining a type which needs a class struct
397
398   OBJECT_DEFINE_TYPE(MyDevice, my_device, MY_DEVICE, DEVICE)
399
400If the type needs to implement one or more interfaces, then the
401OBJECT_DEFINE_SIMPLE_TYPE_WITH_INTERFACES() and
402OBJECT_DEFINE_TYPE_WITH_INTERFACES() macros can be used instead.
403These accept an array of interface type names. The difference between
404them is that the former is for simple leaf classes that don't need
405a class struct, and the latter is for when you will be defining
406a class struct.
407
408.. code-block:: c
409   :caption: Defining a simple type implementing interfaces
410
411   OBJECT_DEFINE_SIMPLE_TYPE_WITH_INTERFACES(MyDevice, my_device,
412                                             MY_DEVICE, DEVICE,
413                                             { TYPE_USER_CREATABLE },
414                                             { NULL })
415
416.. code-block:: c
417   :caption: Defining a type implementing interfaces
418
419   OBJECT_DEFINE_TYPE_WITH_INTERFACES(MyDevice, my_device,
420                                      MY_DEVICE, DEVICE,
421                                      { TYPE_USER_CREATABLE },
422                                      { NULL })
423
424If the type is not intended to be instantiated, then the
425OBJECT_DEFINE_ABSTRACT_TYPE() macro can be used instead:
426
427.. code-block:: c
428   :caption: Defining a simple abstract type
429
430   OBJECT_DEFINE_ABSTRACT_TYPE(MyDevice, my_device,
431                               MY_DEVICE, DEVICE)
432
433.. _device-life-cycle:
434
435Device Life-cycle
436=================
437
438As class initialisation cannot fail devices have an two additional
439methods to handle the creation of dynamic devices. The ``realize``
440function is called with ``Error **`` pointer which should be set if
441the device cannot complete its setup. Otherwise on successful
442completion of the ``realize`` method the device object is added to the
443QOM tree and made visible to the guest.
444
445The reverse function is ``unrealize`` and should be were clean-up
446code lives to tidy up after the system is done with the device.
447
448All devices can be instantiated by C code, however only some can
449created dynamically via the command line or monitor.
450
451Likewise only some can be unplugged after creation and need an
452explicit ``unrealize`` implementation. This is determined by the
453``user_creatable`` variable in the root ``DeviceClass`` structure.
454Devices can only be unplugged if their ``parent_bus`` has a registered
455``HotplugHandler``.
456
457API Reference
458=============
459
460See the :ref:`QOM API<qom-api>` and :ref:`QDEV API<qdev-api>`
461documents for the complete API description.
462