xref: /openbmc/qemu/monitor/qmp.c (revision 64552b6b)
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-misc.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_queues(MonitorQMP *mon)
79 {
80     qemu_mutex_lock(&mon->qmp_queue_lock);
81     monitor_qmp_cleanup_req_queue_locked(mon);
82     qemu_mutex_unlock(&mon->qmp_queue_lock);
83 }
84 
85 void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
86 {
87     const QObject *data = QOBJECT(rsp);
88     QString *json;
89 
90     json = mon->pretty ? qobject_to_json_pretty(data) : qobject_to_json(data);
91     assert(json != NULL);
92 
93     qstring_append_chr(json, '\n');
94     monitor_puts(&mon->common, qstring_get_str(json));
95 
96     qobject_unref(json);
97 }
98 
99 /*
100  * Emit QMP response @rsp with ID @id to @mon.
101  * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
102  * Nothing is emitted then.
103  */
104 static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
105 {
106     if (rsp) {
107         qmp_send_response(mon, rsp);
108     }
109 }
110 
111 static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
112 {
113     Monitor *old_mon;
114     QDict *rsp;
115     QDict *error;
116 
117     old_mon = cur_mon;
118     cur_mon = &mon->common;
119 
120     rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon));
121 
122     cur_mon = old_mon;
123 
124     if (mon->commands == &qmp_cap_negotiation_commands) {
125         error = qdict_get_qdict(rsp, "error");
126         if (error
127             && !g_strcmp0(qdict_get_try_str(error, "class"),
128                     QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
129             /* Provide a more useful error message */
130             qdict_del(error, "desc");
131             qdict_put_str(error, "desc", "Expecting capabilities negotiation"
132                           " with 'qmp_capabilities'");
133         }
134     }
135 
136     monitor_qmp_respond(mon, rsp);
137     qobject_unref(rsp);
138 }
139 
140 /*
141  * Pop a QMP request from a monitor request queue.
142  * Return the request, or NULL all request queues are empty.
143  * We are using round-robin fashion to pop the request, to avoid
144  * processing commands only on a very busy monitor.  To achieve that,
145  * when we process one request on a specific monitor, we put that
146  * monitor to the end of mon_list queue.
147  *
148  * Note: if the function returned with non-NULL, then the caller will
149  * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
150  * to release it.
151  */
152 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
153 {
154     QMPRequest *req_obj = NULL;
155     Monitor *mon;
156     MonitorQMP *qmp_mon;
157 
158     qemu_mutex_lock(&monitor_lock);
159 
160     QTAILQ_FOREACH(mon, &mon_list, entry) {
161         if (!monitor_is_qmp(mon)) {
162             continue;
163         }
164 
165         qmp_mon = container_of(mon, MonitorQMP, common);
166         qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
167         req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
168         if (req_obj) {
169             /* With the lock of corresponding queue held */
170             break;
171         }
172         qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
173     }
174 
175     if (req_obj) {
176         /*
177          * We found one request on the monitor. Degrade this monitor's
178          * priority to lowest by re-inserting it to end of queue.
179          */
180         QTAILQ_REMOVE(&mon_list, mon, entry);
181         QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
182     }
183 
184     qemu_mutex_unlock(&monitor_lock);
185 
186     return req_obj;
187 }
188 
189 void monitor_qmp_bh_dispatcher(void *data)
190 {
191     QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
192     QDict *rsp;
193     bool need_resume;
194     MonitorQMP *mon;
195 
196     if (!req_obj) {
197         return;
198     }
199 
200     mon = req_obj->mon;
201     /*  qmp_oob_enabled() might change after "qmp_capabilities" */
202     need_resume = !qmp_oob_enabled(mon) ||
203         mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
204     qemu_mutex_unlock(&mon->qmp_queue_lock);
205     if (req_obj->req) {
206         QDict *qdict = qobject_to(QDict, req_obj->req);
207         QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
208         trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
209         monitor_qmp_dispatch(mon, req_obj->req);
210     } else {
211         assert(req_obj->err);
212         rsp = qmp_error_response(req_obj->err);
213         req_obj->err = NULL;
214         monitor_qmp_respond(mon, rsp);
215         qobject_unref(rsp);
216     }
217 
218     if (need_resume) {
219         /* Pairs with the monitor_suspend() in handle_qmp_command() */
220         monitor_resume(&mon->common);
221     }
222     qmp_request_free(req_obj);
223 
224     /* Reschedule instead of looping so the main loop stays responsive */
225     qemu_bh_schedule(qmp_dispatcher_bh);
226 }
227 
228 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
229 {
230     MonitorQMP *mon = opaque;
231     QObject *id = NULL;
232     QDict *qdict;
233     QMPRequest *req_obj;
234 
235     assert(!req != !err);
236 
237     qdict = qobject_to(QDict, req);
238     if (qdict) {
239         id = qdict_get(qdict, "id");
240     } /* else will fail qmp_dispatch() */
241 
242     if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
243         QString *req_json = qobject_to_json(req);
244         trace_handle_qmp_command(mon, qstring_get_str(req_json));
245         qobject_unref(req_json);
246     }
247 
248     if (qdict && qmp_is_oob(qdict)) {
249         /* OOB commands are executed immediately */
250         trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
251         monitor_qmp_dispatch(mon, req);
252         qobject_unref(req);
253         return;
254     }
255 
256     req_obj = g_new0(QMPRequest, 1);
257     req_obj->mon = mon;
258     req_obj->req = req;
259     req_obj->err = err;
260 
261     /* Protect qmp_requests and fetching its length. */
262     qemu_mutex_lock(&mon->qmp_queue_lock);
263 
264     /*
265      * Suspend the monitor when we can't queue more requests after
266      * this one.  Dequeuing in monitor_qmp_bh_dispatcher() will resume
267      * it.  Note that when OOB is disabled, we queue at most one
268      * command, for backward compatibility.
269      */
270     if (!qmp_oob_enabled(mon) ||
271         mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
272         monitor_suspend(&mon->common);
273     }
274 
275     /*
276      * Put the request to the end of queue so that requests will be
277      * handled in time order.  Ownership for req_obj, req,
278      * etc. will be delivered to the handler side.
279      */
280     assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
281     g_queue_push_tail(mon->qmp_requests, req_obj);
282     qemu_mutex_unlock(&mon->qmp_queue_lock);
283 
284     /* Kick the dispatcher routine */
285     qemu_bh_schedule(qmp_dispatcher_bh);
286 }
287 
288 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
289 {
290     MonitorQMP *mon = opaque;
291 
292     json_message_parser_feed(&mon->parser, (const char *) buf, size);
293 }
294 
295 static QDict *qmp_greeting(MonitorQMP *mon)
296 {
297     QList *cap_list = qlist_new();
298     QObject *ver = NULL;
299     QMPCapability cap;
300 
301     qmp_marshal_query_version(NULL, &ver, NULL);
302 
303     for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
304         if (mon->capab_offered[cap]) {
305             qlist_append_str(cap_list, QMPCapability_str(cap));
306         }
307     }
308 
309     return qdict_from_jsonf_nofail(
310         "{'QMP': {'version': %p, 'capabilities': %p}}",
311         ver, cap_list);
312 }
313 
314 static void monitor_qmp_event(void *opaque, int event)
315 {
316     QDict *data;
317     MonitorQMP *mon = opaque;
318 
319     switch (event) {
320     case CHR_EVENT_OPENED:
321         mon->commands = &qmp_cap_negotiation_commands;
322         monitor_qmp_caps_reset(mon);
323         data = qmp_greeting(mon);
324         qmp_send_response(mon, data);
325         qobject_unref(data);
326         mon_refcount++;
327         break;
328     case CHR_EVENT_CLOSED:
329         /*
330          * Note: this is only useful when the output of the chardev
331          * backend is still open.  For example, when the backend is
332          * stdio, it's possible that stdout is still open when stdin
333          * is closed.
334          */
335         monitor_qmp_cleanup_queues(mon);
336         json_message_parser_destroy(&mon->parser);
337         json_message_parser_init(&mon->parser, handle_qmp_command,
338                                  mon, NULL);
339         mon_refcount--;
340         monitor_fdsets_cleanup();
341         break;
342     }
343 }
344 
345 void monitor_data_destroy_qmp(MonitorQMP *mon)
346 {
347     json_message_parser_destroy(&mon->parser);
348     qemu_mutex_destroy(&mon->qmp_queue_lock);
349     monitor_qmp_cleanup_req_queue_locked(mon);
350     g_queue_free(mon->qmp_requests);
351 }
352 
353 static void monitor_qmp_setup_handlers_bh(void *opaque)
354 {
355     MonitorQMP *mon = opaque;
356     GMainContext *context;
357 
358     assert(mon->common.use_io_thread);
359     context = iothread_get_g_main_context(mon_iothread);
360     assert(context);
361     qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
362                              monitor_qmp_read, monitor_qmp_event,
363                              NULL, &mon->common, context, true);
364     monitor_list_append(&mon->common);
365 }
366 
367 void monitor_init_qmp(Chardev *chr, bool pretty)
368 {
369     MonitorQMP *mon = g_new0(MonitorQMP, 1);
370 
371     /* Note: we run QMP monitor in I/O thread when @chr supports that */
372     monitor_data_init(&mon->common, true, false,
373                       qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
374 
375     mon->pretty = pretty;
376 
377     qemu_mutex_init(&mon->qmp_queue_lock);
378     mon->qmp_requests = g_queue_new();
379 
380     qemu_chr_fe_init(&mon->common.chr, chr, &error_abort);
381     qemu_chr_fe_set_echo(&mon->common.chr, true);
382 
383     json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
384     if (mon->common.use_io_thread) {
385         /*
386          * Make sure the old iowatch is gone.  It's possible when
387          * e.g. the chardev is in client mode, with wait=on.
388          */
389         remove_fd_in_watch(chr);
390         /*
391          * We can't call qemu_chr_fe_set_handlers() directly here
392          * since chardev might be running in the monitor I/O
393          * thread.  Schedule a bottom half.
394          */
395         aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
396                                 monitor_qmp_setup_handlers_bh, mon);
397         /* The bottom half will add @mon to @mon_list */
398     } else {
399         qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
400                                  monitor_qmp_read, monitor_qmp_event,
401                                  NULL, &mon->common, NULL, true);
402         monitor_list_append(&mon->common);
403     }
404 }
405