Docs/RCU: Correct sample code of qatomic_rcu_set
[qemu/ar7.git] / monitor / qmp.c
blob8f91af32bee022587aac056326aef3b1d9fbd210
1 /*
2 * QEMU monitor
4 * Copyright (c) 2003-2004 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
25 #include "qemu/osdep.h"
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"
36 struct QMPRequest {
37 /* Owner of the request */
38 MonitorQMP *mon;
40 * Request object to be handled or Error to be reported
41 * (exactly one of them is non-null)
43 QObject *req;
44 Error *err;
46 typedef struct QMPRequest QMPRequest;
48 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
50 static bool qmp_oob_enabled(MonitorQMP *mon)
52 return mon->capab[QMP_CAPABILITY_OOB];
55 static void monitor_qmp_caps_reset(MonitorQMP *mon)
57 memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
58 memset(mon->capab, 0, sizeof(mon->capab));
59 mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
62 static void qmp_request_free(QMPRequest *req)
64 qobject_unref(req->req);
65 error_free(req->err);
66 g_free(req);
69 /* Caller must hold mon->qmp.qmp_queue_lock */
70 static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
72 while (!g_queue_is_empty(mon->qmp_requests)) {
73 qmp_request_free(g_queue_pop_head(mon->qmp_requests));
77 static void monitor_qmp_cleanup_queue_and_resume(MonitorQMP *mon)
79 qemu_mutex_lock(&mon->qmp_queue_lock);
82 * Same condition as in monitor_qmp_bh_dispatcher(), but before
83 * removing an element from the queue (hence no `- 1`).
84 * Also, the queue should not be empty either, otherwise the
85 * monitor hasn't been suspended yet (or was already resumed).
87 bool need_resume = (!qmp_oob_enabled(mon) ||
88 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX)
89 && !g_queue_is_empty(mon->qmp_requests);
91 monitor_qmp_cleanup_req_queue_locked(mon);
93 if (need_resume) {
95 * handle_qmp_command() suspended the monitor because the
96 * request queue filled up, to be resumed when the queue has
97 * space again. We just emptied it; resume the monitor.
99 * Without this, the monitor would remain suspended forever
100 * when we get here while the monitor is suspended. An
101 * unfortunately timed CHR_EVENT_CLOSED can do the trick.
103 monitor_resume(&mon->common);
106 qemu_mutex_unlock(&mon->qmp_queue_lock);
109 void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
111 const QObject *data = QOBJECT(rsp);
112 GString *json;
114 json = qobject_to_json_pretty(data, mon->pretty);
115 assert(json != NULL);
117 g_string_append_c(json, '\n');
118 monitor_puts(&mon->common, json->str);
120 g_string_free(json, true);
124 * Emit QMP response @rsp to @mon.
125 * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
126 * Nothing is emitted then.
128 static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
130 if (rsp) {
131 qmp_send_response(mon, rsp);
136 * Runs outside of coroutine context for OOB commands, but in
137 * coroutine context for everything else.
139 static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
141 QDict *rsp;
142 QDict *error;
144 rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon),
145 &mon->common);
147 if (mon->commands == &qmp_cap_negotiation_commands) {
148 error = qdict_get_qdict(rsp, "error");
149 if (error
150 && !g_strcmp0(qdict_get_try_str(error, "class"),
151 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
152 /* Provide a more useful error message */
153 qdict_del(error, "desc");
154 qdict_put_str(error, "desc", "Expecting capabilities negotiation"
155 " with 'qmp_capabilities'");
159 monitor_qmp_respond(mon, rsp);
160 qobject_unref(rsp);
164 * Pop a QMP request from a monitor request queue.
165 * Return the request, or NULL all request queues are empty.
166 * We are using round-robin fashion to pop the request, to avoid
167 * processing commands only on a very busy monitor. To achieve that,
168 * when we process one request on a specific monitor, we put that
169 * monitor to the end of mon_list queue.
171 * Note: if the function returned with non-NULL, then the caller will
172 * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
173 * to release it.
175 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
177 QMPRequest *req_obj = NULL;
178 Monitor *mon;
179 MonitorQMP *qmp_mon;
181 qemu_mutex_lock(&monitor_lock);
183 QTAILQ_FOREACH(mon, &mon_list, entry) {
184 if (!monitor_is_qmp(mon)) {
185 continue;
188 qmp_mon = container_of(mon, MonitorQMP, common);
189 qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
190 req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
191 if (req_obj) {
192 /* With the lock of corresponding queue held */
193 break;
195 qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
198 if (req_obj) {
200 * We found one request on the monitor. Degrade this monitor's
201 * priority to lowest by re-inserting it to end of queue.
203 QTAILQ_REMOVE(&mon_list, mon, entry);
204 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
207 qemu_mutex_unlock(&monitor_lock);
209 return req_obj;
212 void coroutine_fn monitor_qmp_dispatcher_co(void *data)
214 QMPRequest *req_obj = NULL;
215 QDict *rsp;
216 bool need_resume;
217 MonitorQMP *mon;
219 while (true) {
220 assert(qatomic_mb_read(&qmp_dispatcher_co_busy) == true);
223 * Mark the dispatcher as not busy already here so that we
224 * don't miss any new requests coming in the middle of our
225 * processing.
227 qatomic_mb_set(&qmp_dispatcher_co_busy, false);
229 while (!(req_obj = monitor_qmp_requests_pop_any_with_lock())) {
231 * No more requests to process. Wait to be reentered from
232 * handle_qmp_command() when it pushes more requests, or
233 * from monitor_cleanup() when it requests shutdown.
235 if (!qmp_dispatcher_co_shutdown) {
236 qemu_coroutine_yield();
239 * busy must be set to true again by whoever
240 * rescheduled us to avoid double scheduling
242 assert(qatomic_xchg(&qmp_dispatcher_co_busy, false) == true);
246 * qmp_dispatcher_co_shutdown may have changed if we
247 * yielded and were reentered from monitor_cleanup()
249 if (qmp_dispatcher_co_shutdown) {
250 return;
254 if (qatomic_xchg(&qmp_dispatcher_co_busy, true) == true) {
256 * Someone rescheduled us (probably because a new requests
257 * came in), but we didn't actually yield. Do that now,
258 * only to be immediately reentered and removed from the
259 * list of scheduled coroutines.
261 qemu_coroutine_yield();
265 * Move the coroutine from iohandler_ctx to qemu_aio_context for
266 * executing the command handler so that it can make progress if it
267 * involves an AIO_WAIT_WHILE().
269 aio_co_schedule(qemu_get_aio_context(), qmp_dispatcher_co);
270 qemu_coroutine_yield();
272 mon = req_obj->mon;
273 /* qmp_oob_enabled() might change after "qmp_capabilities" */
274 need_resume = !qmp_oob_enabled(mon) ||
275 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
276 qemu_mutex_unlock(&mon->qmp_queue_lock);
277 if (req_obj->req) {
278 if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_IN_BAND)) {
279 QDict *qdict = qobject_to(QDict, req_obj->req);
280 QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
281 GString *id_json;
283 id_json = id ? qobject_to_json(id) : g_string_new(NULL);
284 trace_monitor_qmp_cmd_in_band(id_json->str);
285 g_string_free(id_json, true);
287 monitor_qmp_dispatch(mon, req_obj->req);
288 } else {
289 assert(req_obj->err);
290 rsp = qmp_error_response(req_obj->err);
291 req_obj->err = NULL;
292 monitor_qmp_respond(mon, rsp);
293 qobject_unref(rsp);
296 if (need_resume) {
297 /* Pairs with the monitor_suspend() in handle_qmp_command() */
298 monitor_resume(&mon->common);
300 qmp_request_free(req_obj);
303 * Yield and reschedule so the main loop stays responsive.
305 * Move back to iohandler_ctx so that nested event loops for
306 * qemu_aio_context don't start new monitor commands.
308 aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
309 qemu_coroutine_yield();
313 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
315 MonitorQMP *mon = opaque;
316 QDict *qdict = qobject_to(QDict, req);
317 QMPRequest *req_obj;
319 assert(!req != !err);
321 if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
322 GString *req_json = qobject_to_json(req);
323 trace_handle_qmp_command(mon, req_json->str);
324 g_string_free(req_json, true);
327 if (qdict && qmp_is_oob(qdict)) {
328 /* OOB commands are executed immediately */
329 if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_OUT_OF_BAND)) {
330 QObject *id = qdict_get(qdict, "id");
331 GString *id_json;
333 id_json = id ? qobject_to_json(id) : g_string_new(NULL);
334 trace_monitor_qmp_cmd_out_of_band(id_json->str);
335 g_string_free(id_json, true);
337 monitor_qmp_dispatch(mon, req);
338 qobject_unref(req);
339 return;
342 req_obj = g_new0(QMPRequest, 1);
343 req_obj->mon = mon;
344 req_obj->req = req;
345 req_obj->err = err;
347 /* Protect qmp_requests and fetching its length. */
348 qemu_mutex_lock(&mon->qmp_queue_lock);
351 * Suspend the monitor when we can't queue more requests after
352 * this one. Dequeuing in monitor_qmp_bh_dispatcher() or
353 * monitor_qmp_cleanup_queue_and_resume() will resume it.
354 * Note that when OOB is disabled, we queue at most one command,
355 * for backward compatibility.
357 if (!qmp_oob_enabled(mon) ||
358 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
359 monitor_suspend(&mon->common);
363 * Put the request to the end of queue so that requests will be
364 * handled in time order. Ownership for req_obj, req,
365 * etc. will be delivered to the handler side.
367 assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
368 g_queue_push_tail(mon->qmp_requests, req_obj);
369 qemu_mutex_unlock(&mon->qmp_queue_lock);
371 /* Kick the dispatcher routine */
372 if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
373 aio_co_wake(qmp_dispatcher_co);
377 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
379 MonitorQMP *mon = opaque;
381 json_message_parser_feed(&mon->parser, (const char *) buf, size);
384 static QDict *qmp_greeting(MonitorQMP *mon)
386 QList *cap_list = qlist_new();
387 QObject *ver = NULL;
388 QDict *args;
389 QMPCapability cap;
391 args = qdict_new();
392 qmp_marshal_query_version(args, &ver, NULL);
393 qobject_unref(args);
395 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
396 if (mon->capab_offered[cap]) {
397 qlist_append_str(cap_list, QMPCapability_str(cap));
401 return qdict_from_jsonf_nofail(
402 "{'QMP': {'version': %p, 'capabilities': %p}}",
403 ver, cap_list);
406 static void monitor_qmp_event(void *opaque, QEMUChrEvent event)
408 QDict *data;
409 MonitorQMP *mon = opaque;
411 switch (event) {
412 case CHR_EVENT_OPENED:
413 mon->commands = &qmp_cap_negotiation_commands;
414 monitor_qmp_caps_reset(mon);
415 data = qmp_greeting(mon);
416 qmp_send_response(mon, data);
417 qobject_unref(data);
418 mon_refcount++;
419 break;
420 case CHR_EVENT_CLOSED:
422 * Note: this is only useful when the output of the chardev
423 * backend is still open. For example, when the backend is
424 * stdio, it's possible that stdout is still open when stdin
425 * is closed.
427 monitor_qmp_cleanup_queue_and_resume(mon);
428 json_message_parser_destroy(&mon->parser);
429 json_message_parser_init(&mon->parser, handle_qmp_command,
430 mon, NULL);
431 mon_refcount--;
432 monitor_fdsets_cleanup();
433 break;
434 case CHR_EVENT_BREAK:
435 case CHR_EVENT_MUX_IN:
436 case CHR_EVENT_MUX_OUT:
437 /* Ignore */
438 break;
442 void monitor_data_destroy_qmp(MonitorQMP *mon)
444 json_message_parser_destroy(&mon->parser);
445 qemu_mutex_destroy(&mon->qmp_queue_lock);
446 monitor_qmp_cleanup_req_queue_locked(mon);
447 g_queue_free(mon->qmp_requests);
450 static void monitor_qmp_setup_handlers_bh(void *opaque)
452 MonitorQMP *mon = opaque;
453 GMainContext *context;
455 assert(mon->common.use_io_thread);
456 context = iothread_get_g_main_context(mon_iothread);
457 assert(context);
458 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
459 monitor_qmp_read, monitor_qmp_event,
460 NULL, &mon->common, context, true);
461 monitor_list_append(&mon->common);
464 void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
466 MonitorQMP *mon = g_new0(MonitorQMP, 1);
468 if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
469 g_free(mon);
470 return;
472 qemu_chr_fe_set_echo(&mon->common.chr, true);
474 /* Note: we run QMP monitor in I/O thread when @chr supports that */
475 monitor_data_init(&mon->common, true, false,
476 qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
478 mon->pretty = pretty;
480 qemu_mutex_init(&mon->qmp_queue_lock);
481 mon->qmp_requests = g_queue_new();
483 json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
484 if (mon->common.use_io_thread) {
486 * Make sure the old iowatch is gone. It's possible when
487 * e.g. the chardev is in client mode, with wait=on.
489 remove_fd_in_watch(chr);
491 * We can't call qemu_chr_fe_set_handlers() directly here
492 * since chardev might be running in the monitor I/O
493 * thread. Schedule a bottom half.
495 aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
496 monitor_qmp_setup_handlers_bh, mon);
497 /* The bottom half will add @mon to @mon_list */
498 } else {
499 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
500 monitor_qmp_read, monitor_qmp_event,
501 NULL, &mon->common, NULL, true);
502 monitor_list_append(&mon->common);