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