xref: /openbmc/qemu/monitor/qmp.c (revision 41725fa7)
1 /*
2  * QEMU monitor
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 
27 #include "chardev/char-io.h"
28 #include "monitor-internal.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-commands-control.h"
31 #include "qapi/qmp/qdict.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qlist.h"
34 #include "qapi/qmp/qstring.h"
35 #include "trace.h"
36 
37 struct QMPRequest {
38     /* Owner of the request */
39     MonitorQMP *mon;
40     /*
41      * Request object to be handled or Error to be reported
42      * (exactly one of them is non-null)
43      */
44     QObject *req;
45     Error *err;
46 };
47 typedef struct QMPRequest QMPRequest;
48 
49 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
50 
51 static bool qmp_oob_enabled(MonitorQMP *mon)
52 {
53     return mon->capab[QMP_CAPABILITY_OOB];
54 }
55 
56 static void monitor_qmp_caps_reset(MonitorQMP *mon)
57 {
58     memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
59     memset(mon->capab, 0, sizeof(mon->capab));
60     mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
61 }
62 
63 static void qmp_request_free(QMPRequest *req)
64 {
65     qobject_unref(req->req);
66     error_free(req->err);
67     g_free(req);
68 }
69 
70 /* Caller must hold mon->qmp.qmp_queue_lock */
71 static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
72 {
73     while (!g_queue_is_empty(mon->qmp_requests)) {
74         qmp_request_free(g_queue_pop_head(mon->qmp_requests));
75     }
76 }
77 
78 static void monitor_qmp_cleanup_queue_and_resume(MonitorQMP *mon)
79 {
80     qemu_mutex_lock(&mon->qmp_queue_lock);
81 
82     /*
83      * Same condition as in monitor_qmp_bh_dispatcher(), but before
84      * removing an element from the queue (hence no `- 1`).
85      * Also, the queue should not be empty either, otherwise the
86      * monitor hasn't been suspended yet (or was already resumed).
87      */
88     bool need_resume = (!qmp_oob_enabled(mon) ||
89         mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX)
90         && !g_queue_is_empty(mon->qmp_requests);
91 
92     monitor_qmp_cleanup_req_queue_locked(mon);
93 
94     if (need_resume) {
95         /*
96          * handle_qmp_command() suspended the monitor because the
97          * request queue filled up, to be resumed when the queue has
98          * space again.  We just emptied it; resume the monitor.
99          *
100          * Without this, the monitor would remain suspended forever
101          * when we get here while the monitor is suspended.  An
102          * unfortunately timed CHR_EVENT_CLOSED can do the trick.
103          */
104         monitor_resume(&mon->common);
105     }
106 
107     qemu_mutex_unlock(&mon->qmp_queue_lock);
108 }
109 
110 void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
111 {
112     const QObject *data = QOBJECT(rsp);
113     QString *json;
114 
115     json = mon->pretty ? qobject_to_json_pretty(data) : qobject_to_json(data);
116     assert(json != NULL);
117 
118     qstring_append_chr(json, '\n');
119     monitor_puts(&mon->common, qstring_get_str(json));
120 
121     qobject_unref(json);
122 }
123 
124 /*
125  * Emit QMP response @rsp to @mon.
126  * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
127  * Nothing is emitted then.
128  */
129 static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
130 {
131     if (rsp) {
132         qmp_send_response(mon, rsp);
133     }
134 }
135 
136 static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
137 {
138     QDict *rsp;
139     QDict *error;
140 
141     rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon),
142                        &mon->common);
143 
144     if (mon->commands == &qmp_cap_negotiation_commands) {
145         error = qdict_get_qdict(rsp, "error");
146         if (error
147             && !g_strcmp0(qdict_get_try_str(error, "class"),
148                     QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
149             /* Provide a more useful error message */
150             qdict_del(error, "desc");
151             qdict_put_str(error, "desc", "Expecting capabilities negotiation"
152                           " with 'qmp_capabilities'");
153         }
154     }
155 
156     monitor_qmp_respond(mon, rsp);
157     qobject_unref(rsp);
158 }
159 
160 /*
161  * Pop a QMP request from a monitor request queue.
162  * Return the request, or NULL all request queues are empty.
163  * We are using round-robin fashion to pop the request, to avoid
164  * processing commands only on a very busy monitor.  To achieve that,
165  * when we process one request on a specific monitor, we put that
166  * monitor to the end of mon_list queue.
167  *
168  * Note: if the function returned with non-NULL, then the caller will
169  * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
170  * to release it.
171  */
172 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
173 {
174     QMPRequest *req_obj = NULL;
175     Monitor *mon;
176     MonitorQMP *qmp_mon;
177 
178     qemu_mutex_lock(&monitor_lock);
179 
180     QTAILQ_FOREACH(mon, &mon_list, entry) {
181         if (!monitor_is_qmp(mon)) {
182             continue;
183         }
184 
185         qmp_mon = container_of(mon, MonitorQMP, common);
186         qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
187         req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
188         if (req_obj) {
189             /* With the lock of corresponding queue held */
190             break;
191         }
192         qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
193     }
194 
195     if (req_obj) {
196         /*
197          * We found one request on the monitor. Degrade this monitor's
198          * priority to lowest by re-inserting it to end of queue.
199          */
200         QTAILQ_REMOVE(&mon_list, mon, entry);
201         QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
202     }
203 
204     qemu_mutex_unlock(&monitor_lock);
205 
206     return req_obj;
207 }
208 
209 void monitor_qmp_bh_dispatcher(void *data)
210 {
211     QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
212     QDict *rsp;
213     bool need_resume;
214     MonitorQMP *mon;
215 
216     if (!req_obj) {
217         return;
218     }
219 
220     mon = req_obj->mon;
221     /*  qmp_oob_enabled() might change after "qmp_capabilities" */
222     need_resume = !qmp_oob_enabled(mon) ||
223         mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
224     qemu_mutex_unlock(&mon->qmp_queue_lock);
225     if (req_obj->req) {
226         QDict *qdict = qobject_to(QDict, req_obj->req);
227         QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
228         trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
229         monitor_qmp_dispatch(mon, req_obj->req);
230     } else {
231         assert(req_obj->err);
232         rsp = qmp_error_response(req_obj->err);
233         req_obj->err = NULL;
234         monitor_qmp_respond(mon, rsp);
235         qobject_unref(rsp);
236     }
237 
238     if (need_resume) {
239         /* Pairs with the monitor_suspend() in handle_qmp_command() */
240         monitor_resume(&mon->common);
241     }
242     qmp_request_free(req_obj);
243 
244     /* Reschedule instead of looping so the main loop stays responsive */
245     qemu_bh_schedule(qmp_dispatcher_bh);
246 }
247 
248 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
249 {
250     MonitorQMP *mon = opaque;
251     QObject *id = NULL;
252     QDict *qdict;
253     QMPRequest *req_obj;
254 
255     assert(!req != !err);
256 
257     qdict = qobject_to(QDict, req);
258     if (qdict) {
259         id = qdict_get(qdict, "id");
260     } /* else will fail qmp_dispatch() */
261 
262     if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
263         QString *req_json = qobject_to_json(req);
264         trace_handle_qmp_command(mon, qstring_get_str(req_json));
265         qobject_unref(req_json);
266     }
267 
268     if (qdict && qmp_is_oob(qdict)) {
269         /* OOB commands are executed immediately */
270         trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
271         monitor_qmp_dispatch(mon, req);
272         qobject_unref(req);
273         return;
274     }
275 
276     req_obj = g_new0(QMPRequest, 1);
277     req_obj->mon = mon;
278     req_obj->req = req;
279     req_obj->err = err;
280 
281     /* Protect qmp_requests and fetching its length. */
282     qemu_mutex_lock(&mon->qmp_queue_lock);
283 
284     /*
285      * Suspend the monitor when we can't queue more requests after
286      * this one.  Dequeuing in monitor_qmp_bh_dispatcher() or
287      * monitor_qmp_cleanup_queue_and_resume() will resume it.
288      * Note that when OOB is disabled, we queue at most one command,
289      * for backward compatibility.
290      */
291     if (!qmp_oob_enabled(mon) ||
292         mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
293         monitor_suspend(&mon->common);
294     }
295 
296     /*
297      * Put the request to the end of queue so that requests will be
298      * handled in time order.  Ownership for req_obj, req,
299      * etc. will be delivered to the handler side.
300      */
301     assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
302     g_queue_push_tail(mon->qmp_requests, req_obj);
303     qemu_mutex_unlock(&mon->qmp_queue_lock);
304 
305     /* Kick the dispatcher routine */
306     qemu_bh_schedule(qmp_dispatcher_bh);
307 }
308 
309 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
310 {
311     MonitorQMP *mon = opaque;
312 
313     json_message_parser_feed(&mon->parser, (const char *) buf, size);
314 }
315 
316 static QDict *qmp_greeting(MonitorQMP *mon)
317 {
318     QList *cap_list = qlist_new();
319     QObject *ver = NULL;
320     QDict *args;
321     QMPCapability cap;
322 
323     args = qdict_new();
324     qmp_marshal_query_version(args, &ver, NULL);
325     qobject_unref(args);
326 
327     for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
328         if (mon->capab_offered[cap]) {
329             qlist_append_str(cap_list, QMPCapability_str(cap));
330         }
331     }
332 
333     return qdict_from_jsonf_nofail(
334         "{'QMP': {'version': %p, 'capabilities': %p}}",
335         ver, cap_list);
336 }
337 
338 static void monitor_qmp_event(void *opaque, QEMUChrEvent event)
339 {
340     QDict *data;
341     MonitorQMP *mon = opaque;
342 
343     switch (event) {
344     case CHR_EVENT_OPENED:
345         mon->commands = &qmp_cap_negotiation_commands;
346         monitor_qmp_caps_reset(mon);
347         data = qmp_greeting(mon);
348         qmp_send_response(mon, data);
349         qobject_unref(data);
350         mon_refcount++;
351         break;
352     case CHR_EVENT_CLOSED:
353         /*
354          * Note: this is only useful when the output of the chardev
355          * backend is still open.  For example, when the backend is
356          * stdio, it's possible that stdout is still open when stdin
357          * is closed.
358          */
359         monitor_qmp_cleanup_queue_and_resume(mon);
360         json_message_parser_destroy(&mon->parser);
361         json_message_parser_init(&mon->parser, handle_qmp_command,
362                                  mon, NULL);
363         mon_refcount--;
364         monitor_fdsets_cleanup();
365         break;
366     case CHR_EVENT_BREAK:
367     case CHR_EVENT_MUX_IN:
368     case CHR_EVENT_MUX_OUT:
369         /* Ignore */
370         break;
371     }
372 }
373 
374 void monitor_data_destroy_qmp(MonitorQMP *mon)
375 {
376     json_message_parser_destroy(&mon->parser);
377     qemu_mutex_destroy(&mon->qmp_queue_lock);
378     monitor_qmp_cleanup_req_queue_locked(mon);
379     g_queue_free(mon->qmp_requests);
380 }
381 
382 static void monitor_qmp_setup_handlers_bh(void *opaque)
383 {
384     MonitorQMP *mon = opaque;
385     GMainContext *context;
386 
387     assert(mon->common.use_io_thread);
388     context = iothread_get_g_main_context(mon_iothread);
389     assert(context);
390     qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
391                              monitor_qmp_read, monitor_qmp_event,
392                              NULL, &mon->common, context, true);
393     monitor_list_append(&mon->common);
394 }
395 
396 void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
397 {
398     MonitorQMP *mon = g_new0(MonitorQMP, 1);
399 
400     if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
401         g_free(mon);
402         return;
403     }
404     qemu_chr_fe_set_echo(&mon->common.chr, true);
405 
406     /* Note: we run QMP monitor in I/O thread when @chr supports that */
407     monitor_data_init(&mon->common, true, false,
408                       qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
409 
410     mon->pretty = pretty;
411 
412     qemu_mutex_init(&mon->qmp_queue_lock);
413     mon->qmp_requests = g_queue_new();
414 
415     json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
416     if (mon->common.use_io_thread) {
417         /*
418          * Make sure the old iowatch is gone.  It's possible when
419          * e.g. the chardev is in client mode, with wait=on.
420          */
421         remove_fd_in_watch(chr);
422         /*
423          * We can't call qemu_chr_fe_set_handlers() directly here
424          * since chardev might be running in the monitor I/O
425          * thread.  Schedule a bottom half.
426          */
427         aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
428                                 monitor_qmp_setup_handlers_bh, mon);
429         /* The bottom half will add @mon to @mon_list */
430     } else {
431         qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
432                                  monitor_qmp_read, monitor_qmp_event,
433                                  NULL, &mon->common, NULL, true);
434         monitor_list_append(&mon->common);
435     }
436 }
437