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