1 /*
2  *  qdev vm change state handlers
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License,
7  *  or (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include "qemu/osdep.h"
19 #include "hw/qdev-core.h"
20 #include "sysemu/runstate.h"
21 
22 static int qdev_get_dev_tree_depth(DeviceState *dev)
23 {
24     int depth;
25 
26     for (depth = 0; dev; depth++) {
27         BusState *bus = dev->parent_bus;
28 
29         if (!bus) {
30             break;
31         }
32 
33         dev = bus->parent;
34     }
35 
36     return depth;
37 }
38 
39 /**
40  * qdev_add_vm_change_state_handler:
41  * @dev: the device that owns this handler
42  * @cb: the callback function to be invoked
43  * @opaque: user data passed to the callback function
44  *
45  * This function works like qemu_add_vm_change_state_handler() except callbacks
46  * are invoked in qdev tree depth order.  Ordering is desirable when callbacks
47  * of children depend on their parent's callback having completed first.
48  *
49  * For example, when qdev_add_vm_change_state_handler() is used, a host
50  * controller's callback is invoked before the children on its bus when the VM
51  * starts running.  The order is reversed when the VM stops running.
52  *
53  * Returns: an entry to be freed with qemu_del_vm_change_state_handler()
54  */
55 VMChangeStateEntry *qdev_add_vm_change_state_handler(DeviceState *dev,
56                                                      VMChangeStateHandler *cb,
57                                                      void *opaque)
58 {
59     return qdev_add_vm_change_state_handler_full(dev, cb, NULL, opaque);
60 }
61 
62 /*
63  * Exactly like qdev_add_vm_change_state_handler() but passes a prepare_cb
64  * argument too.
65  */
66 VMChangeStateEntry *qdev_add_vm_change_state_handler_full(
67     DeviceState *dev, VMChangeStateHandler *cb,
68     VMChangeStateHandler *prepare_cb, void *opaque)
69 {
70     int depth = qdev_get_dev_tree_depth(dev);
71 
72     return qemu_add_vm_change_state_handler_prio_full(cb, prepare_cb, opaque,
73                                                       depth);
74 }
75