xref: /openbmc/qemu/monitor/qmp.c (revision 87d67fad)
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 "trace.h"
35 
36 /*
37  * qmp_dispatcher_co_busy is used for synchronisation between the
38  * monitor thread and the main thread to ensure that the dispatcher
39  * coroutine never gets scheduled a second time when it's already
40  * scheduled (scheduling the same coroutine twice is forbidden).
41  *
42  * It is true if the coroutine will process at least one more request
43  * before going to sleep.  Either it has been kicked already, or it
44  * is active and processing requests.  Additional requests may therefore
45  * be pushed onto mon->qmp_requests, and @qmp_dispatcher_co_shutdown may
46  * be set without further ado.  @qmp_dispatcher_co must not be woken up
47  * in this case.
48  *
49  * If false, you have to wake up @qmp_dispatcher_co after pushing new
50  * requests. You also have to set @qmp_dispatcher_co_busy to true
51  * before waking up the coroutine.
52  *
53  * The coroutine will automatically change this variable back to false
54  * before it yields.  Nobody else may set the variable to false.
55  *
56  * Access must be atomic for thread safety.
57  */
58 static bool qmp_dispatcher_co_busy = true;
59 
60 struct QMPRequest {
61     /* Owner of the request */
62     MonitorQMP *mon;
63     /*
64      * Request object to be handled or Error to be reported
65      * (exactly one of them is non-null)
66      */
67     QObject *req;
68     Error *err;
69 };
70 typedef struct QMPRequest QMPRequest;
71 
72 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
73 
qmp_oob_enabled(MonitorQMP * mon)74 static bool qmp_oob_enabled(MonitorQMP *mon)
75 {
76     return mon->capab[QMP_CAPABILITY_OOB];
77 }
78 
monitor_qmp_caps_reset(MonitorQMP * mon)79 static void monitor_qmp_caps_reset(MonitorQMP *mon)
80 {
81     memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
82     memset(mon->capab, 0, sizeof(mon->capab));
83     mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
84 }
85 
qmp_request_free(QMPRequest * req)86 static void qmp_request_free(QMPRequest *req)
87 {
88     qobject_unref(req->req);
89     error_free(req->err);
90     g_free(req);
91 }
92 
93 /* Caller must hold mon->qmp.qmp_queue_lock */
monitor_qmp_cleanup_req_queue_locked(MonitorQMP * mon)94 static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
95 {
96     while (!g_queue_is_empty(mon->qmp_requests)) {
97         qmp_request_free(g_queue_pop_head(mon->qmp_requests));
98     }
99 }
100 
monitor_qmp_cleanup_queue_and_resume(MonitorQMP * mon)101 static void monitor_qmp_cleanup_queue_and_resume(MonitorQMP *mon)
102 {
103     QEMU_LOCK_GUARD(&mon->qmp_queue_lock);
104 
105     /*
106      * Same condition as in monitor_qmp_dispatcher_co(), but before
107      * removing an element from the queue (hence no `- 1`).
108      * Also, the queue should not be empty either, otherwise the
109      * monitor hasn't been suspended yet (or was already resumed).
110      */
111     bool need_resume = (!qmp_oob_enabled(mon) ||
112         mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX)
113         && !g_queue_is_empty(mon->qmp_requests);
114 
115     monitor_qmp_cleanup_req_queue_locked(mon);
116 
117     if (need_resume) {
118         /*
119          * handle_qmp_command() suspended the monitor because the
120          * request queue filled up, to be resumed when the queue has
121          * space again.  We just emptied it; resume the monitor.
122          *
123          * Without this, the monitor would remain suspended forever
124          * when we get here while the monitor is suspended.  An
125          * unfortunately timed CHR_EVENT_CLOSED can do the trick.
126          */
127         monitor_resume(&mon->common);
128     }
129 
130 }
131 
qmp_send_response(MonitorQMP * mon,const QDict * rsp)132 void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
133 {
134     const QObject *data = QOBJECT(rsp);
135     GString *json;
136 
137     json = qobject_to_json_pretty(data, mon->pretty);
138     assert(json != NULL);
139     trace_monitor_qmp_respond(mon, json->str);
140 
141     g_string_append_c(json, '\n');
142     monitor_puts(&mon->common, json->str);
143 
144     g_string_free(json, true);
145 }
146 
147 /*
148  * Emit QMP response @rsp to @mon.
149  * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
150  * Nothing is emitted then.
151  */
monitor_qmp_respond(MonitorQMP * mon,QDict * rsp)152 static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
153 {
154     if (rsp) {
155         qmp_send_response(mon, rsp);
156     }
157 }
158 
159 /*
160  * Runs outside of coroutine context for OOB commands, but in
161  * coroutine context for everything else.
162  */
monitor_qmp_dispatch(MonitorQMP * mon,QObject * req)163 static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
164 {
165     QDict *rsp;
166     QDict *error;
167 
168     rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon),
169                        &mon->common);
170 
171     if (mon->commands == &qmp_cap_negotiation_commands) {
172         error = qdict_get_qdict(rsp, "error");
173         if (error
174             && !g_strcmp0(qdict_get_try_str(error, "class"),
175                     QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
176             /* Provide a more useful error message */
177             qdict_del(error, "desc");
178             qdict_put_str(error, "desc", "Expecting capabilities negotiation"
179                           " with 'qmp_capabilities'");
180         }
181     }
182 
183     monitor_qmp_respond(mon, rsp);
184     qobject_unref(rsp);
185 }
186 
187 /*
188  * Pop a QMP request from a monitor request queue.
189  * Return the request, or NULL all request queues are empty.
190  * We are using round-robin fashion to pop the request, to avoid
191  * processing commands only on a very busy monitor.  To achieve that,
192  * when we process one request on a specific monitor, we put that
193  * monitor to the end of mon_list queue.
194  *
195  * Note: if the function returned with non-NULL, then the caller will
196  * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
197  * to release it.
198  */
monitor_qmp_requests_pop_any_with_lock(void)199 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
200 {
201     QMPRequest *req_obj = NULL;
202     Monitor *mon;
203     MonitorQMP *qmp_mon;
204 
205     QTAILQ_FOREACH(mon, &mon_list, entry) {
206         if (!monitor_is_qmp(mon)) {
207             continue;
208         }
209 
210         qmp_mon = container_of(mon, MonitorQMP, common);
211         qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
212         req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
213         if (req_obj) {
214             /* With the lock of corresponding queue held */
215             break;
216         }
217         qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
218     }
219 
220     if (req_obj) {
221         /*
222          * We found one request on the monitor. Degrade this monitor's
223          * priority to lowest by re-inserting it to end of queue.
224          */
225         QTAILQ_REMOVE(&mon_list, mon, entry);
226         QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
227     }
228 
229     return req_obj;
230 }
231 
monitor_qmp_dispatcher_pop_any(void)232 static QMPRequest *monitor_qmp_dispatcher_pop_any(void)
233 {
234     while (true) {
235         /*
236          * To avoid double scheduling, busy is true on entry to
237          * monitor_qmp_dispatcher_co(), and must be set again before
238          * aio_co_wake()-ing it.
239          */
240         assert(qatomic_read(&qmp_dispatcher_co_busy) == true);
241 
242         /*
243          * Mark the dispatcher as not busy already here so that we
244          * don't miss any new requests coming in the middle of our
245          * processing.
246          *
247          * Clear qmp_dispatcher_co_busy before reading request.
248          */
249         qatomic_set_mb(&qmp_dispatcher_co_busy, false);
250 
251         WITH_QEMU_LOCK_GUARD(&monitor_lock) {
252             QMPRequest *req_obj;
253 
254             /* On shutdown, don't take any more requests from the queue */
255             if (qmp_dispatcher_co_shutdown) {
256                 return NULL;
257             }
258 
259             req_obj = monitor_qmp_requests_pop_any_with_lock();
260             if (req_obj) {
261                 return req_obj;
262             }
263         }
264 
265         /*
266          * No more requests to process.  Wait to be reentered from
267          * handle_qmp_command() when it pushes more requests, or
268          * from monitor_cleanup() when it requests shutdown.
269          */
270         qemu_coroutine_yield();
271     }
272 }
273 
monitor_qmp_dispatcher_co(void * data)274 void coroutine_fn monitor_qmp_dispatcher_co(void *data)
275 {
276     QMPRequest *req_obj;
277     QDict *rsp;
278     bool oob_enabled;
279     MonitorQMP *mon;
280 
281     while ((req_obj = monitor_qmp_dispatcher_pop_any()) != NULL) {
282         trace_monitor_qmp_in_band_dequeue(req_obj,
283                                           req_obj->mon->qmp_requests->length);
284 
285         /*
286          * @req_obj has a request, we hold req_obj->mon->qmp_queue_lock
287          */
288 
289         mon = req_obj->mon;
290 
291         /*
292          * We need to resume the monitor if handle_qmp_command()
293          * suspended it.  Two cases:
294          * 1. OOB enabled: mon->qmp_requests has no more space
295          *    Resume right away, so that OOB commands can get executed while
296          *    this request is being processed.
297          * 2. OOB disabled: always
298          *    Resume only after we're done processing the request,
299          * We need to save qmp_oob_enabled() for later, because
300          * qmp_qmp_capabilities() can change it.
301          */
302         oob_enabled = qmp_oob_enabled(mon);
303         if (oob_enabled
304             && mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
305             monitor_resume(&mon->common);
306         }
307 
308         /*
309          * Drop the queue mutex now, before yielding, otherwise we might
310          * deadlock if the main thread tries to lock it.
311          */
312         qemu_mutex_unlock(&mon->qmp_queue_lock);
313 
314         if (qatomic_xchg(&qmp_dispatcher_co_busy, true) == true) {
315             /*
316              * Someone rescheduled us (probably because a new requests
317              * came in), but we didn't actually yield. Do that now,
318              * only to be immediately reentered and removed from the
319              * list of scheduled coroutines.
320              */
321             qemu_coroutine_yield();
322         }
323 
324         /* Process request */
325         if (req_obj->req) {
326             if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_IN_BAND)) {
327                 QDict *qdict = qobject_to(QDict, req_obj->req);
328                 QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
329                 GString *id_json;
330 
331                 id_json = id ? qobject_to_json(id) : g_string_new(NULL);
332                 trace_monitor_qmp_cmd_in_band(id_json->str);
333                 g_string_free(id_json, true);
334             }
335             monitor_qmp_dispatch(mon, req_obj->req);
336         } else {
337             assert(req_obj->err);
338             trace_monitor_qmp_err_in_band(error_get_pretty(req_obj->err));
339             rsp = qmp_error_response(req_obj->err);
340             req_obj->err = NULL;
341             monitor_qmp_respond(mon, rsp);
342             qobject_unref(rsp);
343         }
344 
345         if (!oob_enabled) {
346             monitor_resume(&mon->common);
347         }
348 
349         qmp_request_free(req_obj);
350     }
351     qatomic_set(&qmp_dispatcher_co, NULL);
352 }
353 
qmp_dispatcher_co_wake(void)354 void qmp_dispatcher_co_wake(void)
355 {
356     /* Write request before reading qmp_dispatcher_co_busy.  */
357     smp_mb__before_rmw();
358 
359     if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
360         aio_co_wake(qmp_dispatcher_co);
361     }
362 }
363 
handle_qmp_command(void * opaque,QObject * req,Error * err)364 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
365 {
366     MonitorQMP *mon = opaque;
367     QDict *qdict = qobject_to(QDict, req);
368     QMPRequest *req_obj;
369 
370     assert(!req != !err);
371 
372     if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
373         GString *req_json = qobject_to_json(req);
374         trace_handle_qmp_command(mon, req_json->str);
375         g_string_free(req_json, true);
376     }
377 
378     if (qdict && qmp_is_oob(qdict)) {
379         /* OOB commands are executed immediately */
380         if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_OUT_OF_BAND)) {
381             QObject *id = qdict_get(qdict, "id");
382             GString *id_json;
383 
384             id_json = id ? qobject_to_json(id) : g_string_new(NULL);
385             trace_monitor_qmp_cmd_out_of_band(id_json->str);
386             g_string_free(id_json, true);
387         }
388         monitor_qmp_dispatch(mon, req);
389         qobject_unref(req);
390         return;
391     }
392 
393     req_obj = g_new0(QMPRequest, 1);
394     req_obj->mon = mon;
395     req_obj->req = req;
396     req_obj->err = err;
397 
398     /* Protect qmp_requests and fetching its length. */
399     WITH_QEMU_LOCK_GUARD(&mon->qmp_queue_lock) {
400 
401         /*
402          * Suspend the monitor when we can't queue more requests after
403          * this one.  Dequeuing in monitor_qmp_dispatcher_co() or
404          * monitor_qmp_cleanup_queue_and_resume() will resume it.
405          * Note that when OOB is disabled, we queue at most one command,
406          * for backward compatibility.
407          */
408         if (!qmp_oob_enabled(mon) ||
409             mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
410             monitor_suspend(&mon->common);
411         }
412 
413         /*
414          * Put the request to the end of queue so that requests will be
415          * handled in time order.  Ownership for req_obj, req,
416          * etc. will be delivered to the handler side.
417          */
418         trace_monitor_qmp_in_band_enqueue(req_obj, mon,
419                                           mon->qmp_requests->length);
420         assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
421         g_queue_push_tail(mon->qmp_requests, req_obj);
422     }
423 
424     /* Kick the dispatcher routine */
425     qmp_dispatcher_co_wake();
426 }
427 
monitor_qmp_read(void * opaque,const uint8_t * buf,int size)428 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
429 {
430     MonitorQMP *mon = opaque;
431 
432     json_message_parser_feed(&mon->parser, (const char *) buf, size);
433 }
434 
qmp_greeting(MonitorQMP * mon)435 static QDict *qmp_greeting(MonitorQMP *mon)
436 {
437     QList *cap_list = qlist_new();
438     QObject *ver = NULL;
439     QDict *args;
440     QMPCapability cap;
441 
442     args = qdict_new();
443     qmp_marshal_query_version(args, &ver, NULL);
444     qobject_unref(args);
445 
446     for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
447         if (mon->capab_offered[cap]) {
448             qlist_append_str(cap_list, QMPCapability_str(cap));
449         }
450     }
451 
452     return qdict_from_jsonf_nofail(
453         "{'QMP': {'version': %p, 'capabilities': %p}}",
454         ver, cap_list);
455 }
456 
monitor_qmp_event(void * opaque,QEMUChrEvent event)457 static void monitor_qmp_event(void *opaque, QEMUChrEvent event)
458 {
459     QDict *data;
460     MonitorQMP *mon = opaque;
461 
462     switch (event) {
463     case CHR_EVENT_OPENED:
464         mon->commands = &qmp_cap_negotiation_commands;
465         monitor_qmp_caps_reset(mon);
466         data = qmp_greeting(mon);
467         qmp_send_response(mon, data);
468         qobject_unref(data);
469         break;
470     case CHR_EVENT_CLOSED:
471         /*
472          * Note: this is only useful when the output of the chardev
473          * backend is still open.  For example, when the backend is
474          * stdio, it's possible that stdout is still open when stdin
475          * is closed.
476          */
477         monitor_qmp_cleanup_queue_and_resume(mon);
478         json_message_parser_destroy(&mon->parser);
479         json_message_parser_init(&mon->parser, handle_qmp_command,
480                                  mon, NULL);
481         monitor_fdsets_cleanup();
482         break;
483     case CHR_EVENT_BREAK:
484     case CHR_EVENT_MUX_IN:
485     case CHR_EVENT_MUX_OUT:
486         /* Ignore */
487         break;
488     }
489 }
490 
monitor_data_destroy_qmp(MonitorQMP * mon)491 void monitor_data_destroy_qmp(MonitorQMP *mon)
492 {
493     json_message_parser_destroy(&mon->parser);
494     qemu_mutex_destroy(&mon->qmp_queue_lock);
495     monitor_qmp_cleanup_req_queue_locked(mon);
496     g_queue_free(mon->qmp_requests);
497 }
498 
monitor_qmp_setup_handlers_bh(void * opaque)499 static void monitor_qmp_setup_handlers_bh(void *opaque)
500 {
501     MonitorQMP *mon = opaque;
502     GMainContext *context;
503 
504     assert(mon->common.use_io_thread);
505     context = iothread_get_g_main_context(mon_iothread);
506     assert(context);
507     qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
508                              monitor_qmp_read, monitor_qmp_event,
509                              NULL, &mon->common, context, true);
510     monitor_list_append(&mon->common);
511 }
512 
monitor_init_qmp(Chardev * chr,bool pretty,Error ** errp)513 void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
514 {
515     MonitorQMP *mon = g_new0(MonitorQMP, 1);
516 
517     if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
518         g_free(mon);
519         return;
520     }
521     qemu_chr_fe_set_echo(&mon->common.chr, true);
522 
523     /* Note: we run QMP monitor in I/O thread when @chr supports that */
524     monitor_data_init(&mon->common, true, false,
525                       qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
526 
527     mon->pretty = pretty;
528 
529     qemu_mutex_init(&mon->qmp_queue_lock);
530     mon->qmp_requests = g_queue_new();
531 
532     json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
533     if (mon->common.use_io_thread) {
534         /*
535          * Make sure the old iowatch is gone.  It's possible when
536          * e.g. the chardev is in client mode, with wait=on.
537          */
538         remove_fd_in_watch(chr);
539         /*
540          * We can't call qemu_chr_fe_set_handlers() directly here
541          * since chardev might be running in the monitor I/O
542          * thread.  Schedule a bottom half.
543          */
544         aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
545                                 monitor_qmp_setup_handlers_bh, mon);
546         /* The bottom half will add @mon to @mon_list */
547     } else {
548         qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
549                                  monitor_qmp_read, monitor_qmp_event,
550                                  NULL, &mon->common, NULL, true);
551         monitor_list_append(&mon->common);
552     }
553 }
554