I noticed writing a new container device that the "container
inits child objects in-place in its device struct" coding
style results in a lot of boilerplate in device init:

  object_initialize() to init the child
  object_property_add_child() to make the child a child of the parent
  qdev_set_parent_bus() to put the child on the sysbus default bus

If you forget the second of these then things sort of
work but trying to add a child to the child will segfault;
if you forget the third then the device won't get reset.

Patch 1 provides a simple helper function sysbus_init_child()
which does all these things for you, reducing the boilerplate
and making it harder to get wrong.

Code that used to look like this:
    object_initialize(&s->ic, sizeof(s->ic), TYPE_BCM2835_IC);
    object_property_add_child(obj, "ic", OBJECT(&s->ic), NULL);
    qdev_set_parent_bus(DEVICE(&s->ic), sysbus_get_default());
can now look like this:
    sysbus_init_child(obj, "ic", &s->ic, sizeof(s->ic), TYPE_BCM2835_IC);

Patch 2 is a demonstration of it being used in bcm2835_peripherals.c.
I scripted it with a quick Coccinelle script, so there are a
couple of places where it missed opportunities to use the new
function. If people like the function we can apply it more widely,
but I didn't want to go in and hand-tweak code until we have
consensus that it's useful, has parameters in the right order, etc.

thanks
-- PMM

Peter Maydell (2):
  hw/sysbus.h: New sysbus_init_child() helper function
  hw/arm/bcm2835_peripherals: Use sysbus_init_child()

 include/hw/sysbus.h          | 12 ++++++++++++
 hw/arm/bcm2835_peripherals.c | 36 ++++++++++++------------------------
 hw/core/sysbus.c             | 14 ++++++++++++++
 3 files changed, 38 insertions(+), 24 deletions(-)

-- 
2.16.1


Reply via email to