blob: 15f97538ef2b4f3522e7a4140f09a815202a2ec4 [file] [log] [blame]
Kevin Wolf1d95db72019-06-13 17:34:02 +02001/*
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#include "monitor-internal.h"
27#include "qapi/error.h"
Kevin Wolff2098722020-02-24 15:30:04 +010028#include "qapi/opts-visitor.h"
Kevin Wolf1d95db72019-06-13 17:34:02 +020029#include "qapi/qapi-emit-events.h"
Kevin Wolff2098722020-02-24 15:30:04 +010030#include "qapi/qapi-visit-control.h"
Kevin Wolf1d95db72019-06-13 17:34:02 +020031#include "qapi/qmp/qdict.h"
Kevin Wolf1d95db72019-06-13 17:34:02 +020032#include "qemu/error-report.h"
33#include "qemu/option.h"
34#include "sysemu/qtest.h"
35#include "trace.h"
36
37/*
38 * To prevent flooding clients, events can be throttled. The
39 * throttling is calculated globally, rather than per-Monitor
40 * instance.
41 */
42typedef struct MonitorQAPIEventState {
43 QAPIEvent event; /* Throttling state for this event type and... */
44 QDict *data; /* ... data, see qapi_event_throttle_equal() */
45 QEMUTimer *timer; /* Timer for handling delayed events */
46 QDict *qdict; /* Delayed event (if any) */
47} MonitorQAPIEventState;
48
49typedef struct {
50 int64_t rate; /* Minimum time (in ns) between two events */
51} MonitorQAPIEventConf;
52
53/* Shared monitor I/O thread */
54IOThread *mon_iothread;
55
Kevin Wolf9ce44e22020-10-05 17:58:50 +020056/* Coroutine to dispatch the requests received from I/O thread */
57Coroutine *qmp_dispatcher_co;
58
59/* Set to true when the dispatcher coroutine should terminate */
60bool qmp_dispatcher_co_shutdown;
61
62/*
63 * qmp_dispatcher_co_busy is used for synchronisation between the
64 * monitor thread and the main thread to ensure that the dispatcher
65 * coroutine never gets scheduled a second time when it's already
66 * scheduled (scheduling the same coroutine twice is forbidden).
67 *
68 * It is true if the coroutine is active and processing requests.
69 * Additional requests may then be pushed onto mon->qmp_requests,
70 * and @qmp_dispatcher_co_shutdown may be set without further ado.
71 * @qmp_dispatcher_co_busy must not be woken up in this case.
72 *
73 * If false, you also have to set @qmp_dispatcher_co_busy to true and
74 * wake up @qmp_dispatcher_co after pushing the new requests.
75 *
76 * The coroutine will automatically change this variable back to false
77 * before it yields. Nobody else may set the variable to false.
78 *
79 * Access must be atomic for thread safety.
80 */
81bool qmp_dispatcher_co_busy;
Kevin Wolf1d95db72019-06-13 17:34:02 +020082
Kevin Wolfe69ee452020-10-05 17:58:48 +020083/*
84 * Protects mon_list, monitor_qapi_event_state, coroutine_mon,
85 * monitor_destroyed.
86 */
Kevin Wolf1d95db72019-06-13 17:34:02 +020087QemuMutex monitor_lock;
88static GHashTable *monitor_qapi_event_state;
Kevin Wolfe69ee452020-10-05 17:58:48 +020089static GHashTable *coroutine_mon; /* Maps Coroutine* to Monitor* */
Kevin Wolf1d95db72019-06-13 17:34:02 +020090
91MonitorList mon_list;
92int mon_refcount;
93static bool monitor_destroyed;
94
Kevin Wolf947e4742020-10-05 17:58:44 +020095Monitor *monitor_cur(void)
96{
Kevin Wolfe69ee452020-10-05 17:58:48 +020097 Monitor *mon;
98
99 qemu_mutex_lock(&monitor_lock);
100 mon = g_hash_table_lookup(coroutine_mon, qemu_coroutine_self());
101 qemu_mutex_unlock(&monitor_lock);
102
103 return mon;
Kevin Wolf947e4742020-10-05 17:58:44 +0200104}
105
106/**
107 * Sets a new current monitor and returns the old one.
Kevin Wolfe69ee452020-10-05 17:58:48 +0200108 *
109 * If a non-NULL monitor is set for a coroutine, another call
110 * resetting it to NULL is required before the coroutine terminates,
111 * otherwise a stale entry would remain in the hash table.
Kevin Wolf947e4742020-10-05 17:58:44 +0200112 */
Kevin Wolfe69ee452020-10-05 17:58:48 +0200113Monitor *monitor_set_cur(Coroutine *co, Monitor *mon)
Kevin Wolf947e4742020-10-05 17:58:44 +0200114{
Kevin Wolfe69ee452020-10-05 17:58:48 +0200115 Monitor *old_monitor = monitor_cur();
Kevin Wolf947e4742020-10-05 17:58:44 +0200116
Kevin Wolfe69ee452020-10-05 17:58:48 +0200117 qemu_mutex_lock(&monitor_lock);
118 if (mon) {
119 g_hash_table_replace(coroutine_mon, co, mon);
120 } else {
121 g_hash_table_remove(coroutine_mon, co);
122 }
123 qemu_mutex_unlock(&monitor_lock);
124
Kevin Wolf947e4742020-10-05 17:58:44 +0200125 return old_monitor;
126}
Kevin Wolf1d95db72019-06-13 17:34:02 +0200127
128/**
129 * Is the current monitor, if any, a QMP monitor?
130 */
131bool monitor_cur_is_qmp(void)
132{
Kevin Wolf947e4742020-10-05 17:58:44 +0200133 Monitor *cur_mon = monitor_cur();
134
Kevin Wolf1d95db72019-06-13 17:34:02 +0200135 return cur_mon && monitor_is_qmp(cur_mon);
136}
137
138/**
139 * Is @mon is using readline?
140 * Note: not all HMP monitors use readline, e.g., gdbserver has a
141 * non-interactive HMP monitor, so readline is not used there.
142 */
Kevin Wolf92082412019-06-13 17:34:03 +0200143static inline bool monitor_uses_readline(const MonitorHMP *mon)
Kevin Wolf1d95db72019-06-13 17:34:02 +0200144{
Kevin Wolf92082412019-06-13 17:34:03 +0200145 return mon->use_readline;
Kevin Wolf1d95db72019-06-13 17:34:02 +0200146}
147
148static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
149{
Kevin Wolf92082412019-06-13 17:34:03 +0200150 if (monitor_is_qmp(mon)) {
151 return false;
152 }
153
154 return !monitor_uses_readline(container_of(mon, MonitorHMP, common));
Kevin Wolf1d95db72019-06-13 17:34:02 +0200155}
156
Marc-André Lureaubf7b1ea2021-08-04 17:01:14 +0400157static gboolean monitor_unblocked(void *do_not_use, GIOCondition cond,
Kevin Wolf1d95db72019-06-13 17:34:02 +0200158 void *opaque)
159{
160 Monitor *mon = opaque;
161
Paolo Bonzinie37548e2023-05-17 14:47:55 +0200162 QEMU_LOCK_GUARD(&mon->mon_lock);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200163 mon->out_watch = 0;
164 monitor_flush_locked(mon);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200165 return FALSE;
166}
167
168/* Caller must hold mon->mon_lock */
Paolo Bonzini4cb96b92023-05-17 14:46:49 +0200169void monitor_flush_locked(Monitor *mon)
Kevin Wolf1d95db72019-06-13 17:34:02 +0200170{
171 int rc;
172 size_t len;
173 const char *buf;
174
175 if (mon->skip_flush) {
176 return;
177 }
178
Markus Armbruster20076f42020-12-11 18:11:34 +0100179 buf = mon->outbuf->str;
180 len = mon->outbuf->len;
Kevin Wolf1d95db72019-06-13 17:34:02 +0200181
182 if (len && !mon->mux_out) {
183 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
184 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
185 /* all flushed or error */
Markus Armbruster20076f42020-12-11 18:11:34 +0100186 g_string_truncate(mon->outbuf, 0);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200187 return;
188 }
189 if (rc > 0) {
190 /* partial write */
Markus Armbruster20076f42020-12-11 18:11:34 +0100191 g_string_erase(mon->outbuf, 0, rc);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200192 }
193 if (mon->out_watch == 0) {
194 mon->out_watch =
195 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
196 monitor_unblocked, mon);
197 }
198 }
199}
200
201void monitor_flush(Monitor *mon)
202{
Paolo Bonzinie37548e2023-05-17 14:47:55 +0200203 QEMU_LOCK_GUARD(&mon->mon_lock);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200204 monitor_flush_locked(mon);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200205}
206
207/* flush at every end of line */
Paolo Bonzini4cb96b92023-05-17 14:46:49 +0200208int monitor_puts_locked(Monitor *mon, const char *str)
Kevin Wolf1d95db72019-06-13 17:34:02 +0200209{
210 int i;
211 char c;
212
Kevin Wolf1d95db72019-06-13 17:34:02 +0200213 for (i = 0; str[i]; i++) {
214 c = str[i];
215 if (c == '\n') {
Markus Armbruster20076f42020-12-11 18:11:34 +0100216 g_string_append_c(mon->outbuf, '\r');
Kevin Wolf1d95db72019-06-13 17:34:02 +0200217 }
Markus Armbruster20076f42020-12-11 18:11:34 +0100218 g_string_append_c(mon->outbuf, c);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200219 if (c == '\n') {
220 monitor_flush_locked(mon);
221 }
222 }
Kevin Wolf1d95db72019-06-13 17:34:02 +0200223
224 return i;
225}
226
Paolo Bonzini4cb96b92023-05-17 14:46:49 +0200227int monitor_puts(Monitor *mon, const char *str)
228{
229 QEMU_LOCK_GUARD(&mon->mon_lock);
230 return monitor_puts_locked(mon, str);
231}
232
Kevin Wolf1d95db72019-06-13 17:34:02 +0200233int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
234{
235 char *buf;
236 int n;
237
238 if (!mon) {
239 return -1;
240 }
241
242 if (monitor_is_qmp(mon)) {
243 return -1;
244 }
245
246 buf = g_strdup_vprintf(fmt, ap);
247 n = monitor_puts(mon, buf);
248 g_free(buf);
249 return n;
250}
251
252int monitor_printf(Monitor *mon, const char *fmt, ...)
253{
254 int ret;
255
256 va_list ap;
257 va_start(ap, fmt);
258 ret = monitor_vprintf(mon, fmt, ap);
259 va_end(ap);
260 return ret;
261}
262
Markus Armbrusterdd00d7f2023-01-24 13:19:41 +0100263void monitor_printc(Monitor *mon, int c)
264{
265 monitor_printf(mon, "'");
266 switch(c) {
267 case '\'':
268 monitor_printf(mon, "\\'");
269 break;
270 case '\\':
271 monitor_printf(mon, "\\\\");
272 break;
273 case '\n':
274 monitor_printf(mon, "\\n");
275 break;
276 case '\r':
277 monitor_printf(mon, "\\r");
278 break;
279 default:
280 if (c >= 32 && c <= 126) {
281 monitor_printf(mon, "%c", c);
282 } else {
283 monitor_printf(mon, "\\x%02x", c);
284 }
285 break;
286 }
287 monitor_printf(mon, "'");
288}
289
Kevin Wolf1d95db72019-06-13 17:34:02 +0200290/*
291 * Print to current monitor if we have one, else to stderr.
292 */
293int error_vprintf(const char *fmt, va_list ap)
294{
Kevin Wolf947e4742020-10-05 17:58:44 +0200295 Monitor *cur_mon = monitor_cur();
296
Kevin Wolf1d95db72019-06-13 17:34:02 +0200297 if (cur_mon && !monitor_cur_is_qmp()) {
298 return monitor_vprintf(cur_mon, fmt, ap);
299 }
300 return vfprintf(stderr, fmt, ap);
301}
302
303int error_vprintf_unless_qmp(const char *fmt, va_list ap)
304{
Kevin Wolf947e4742020-10-05 17:58:44 +0200305 Monitor *cur_mon = monitor_cur();
306
Kevin Wolf1d95db72019-06-13 17:34:02 +0200307 if (!cur_mon) {
308 return vfprintf(stderr, fmt, ap);
309 }
310 if (!monitor_cur_is_qmp()) {
311 return monitor_vprintf(cur_mon, fmt, ap);
312 }
313 return -1;
314}
315
Marc-André Lureau756a98d2022-04-20 17:26:13 +0400316int error_printf_unless_qmp(const char *fmt, ...)
317{
318 va_list ap;
319 int ret;
320
321 va_start(ap, fmt);
322 ret = error_vprintf_unless_qmp(fmt, ap);
323 va_end(ap);
324 return ret;
325}
Kevin Wolf1d95db72019-06-13 17:34:02 +0200326
327static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
328 /* Limit guest-triggerable events to 1 per second */
329 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
330 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
331 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
332 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
333 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
334 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
David Hildenbrand722a3c72020-06-26 09:22:44 +0200335 [QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE] = { 1000 * SCALE_MS },
Kevin Wolf1d95db72019-06-13 17:34:02 +0200336};
337
338/*
339 * Return the clock to use for recording an event's time.
340 * It's QEMU_CLOCK_REALTIME, except for qtests it's
341 * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
342 * Beware: result is invalid before configure_accelerator().
343 */
344static inline QEMUClockType monitor_get_event_clock(void)
345{
346 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
347}
348
349/*
350 * Broadcast an event to all monitors.
351 * @qdict is the event object. Its member "event" must match @event.
352 * Caller must hold monitor_lock.
353 */
354static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
355{
356 Monitor *mon;
357 MonitorQMP *qmp_mon;
358
359 trace_monitor_protocol_event_emit(event, qdict);
360 QTAILQ_FOREACH(mon, &mon_list, entry) {
361 if (!monitor_is_qmp(mon)) {
362 continue;
363 }
364
365 qmp_mon = container_of(mon, MonitorQMP, common);
366 if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
367 qmp_send_response(qmp_mon, qdict);
368 }
369 }
370}
371
372static void monitor_qapi_event_handler(void *opaque);
373
374/*
375 * Queue a new event for emission to Monitor instances,
376 * applying any rate limiting if required.
377 */
378static void
379monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
380{
381 MonitorQAPIEventConf *evconf;
382 MonitorQAPIEventState *evstate;
383
384 assert(event < QAPI_EVENT__MAX);
385 evconf = &monitor_qapi_event_conf[event];
386 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
387
Mahmoud Mandoura8e2ab52021-03-11 05:15:34 +0200388 QEMU_LOCK_GUARD(&monitor_lock);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200389
390 if (!evconf->rate) {
391 /* Unthrottled event */
392 monitor_qapi_event_emit(event, qdict);
393 } else {
394 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
395 MonitorQAPIEventState key = { .event = event, .data = data };
396
397 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
398 assert(!evstate || timer_pending(evstate->timer));
399
400 if (evstate) {
401 /*
402 * Timer is pending for (at least) evconf->rate ns after
403 * last send. Store event for sending when timer fires,
404 * replacing a prior stored event if any.
405 */
406 qobject_unref(evstate->qdict);
407 evstate->qdict = qobject_ref(qdict);
408 } else {
409 /*
410 * Last send was (at least) evconf->rate ns ago.
411 * Send immediately, and arm the timer to call
412 * monitor_qapi_event_handler() in evconf->rate ns. Any
413 * events arriving before then will be delayed until then.
414 */
415 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
416
417 monitor_qapi_event_emit(event, qdict);
418
419 evstate = g_new(MonitorQAPIEventState, 1);
420 evstate->event = event;
421 evstate->data = qobject_ref(data);
422 evstate->qdict = NULL;
423 evstate->timer = timer_new_ns(monitor_get_event_clock(),
424 monitor_qapi_event_handler,
425 evstate);
426 g_hash_table_add(monitor_qapi_event_state, evstate);
427 timer_mod_ns(evstate->timer, now + evconf->rate);
428 }
429 }
Kevin Wolf1d95db72019-06-13 17:34:02 +0200430}
431
432void qapi_event_emit(QAPIEvent event, QDict *qdict)
433{
434 /*
435 * monitor_qapi_event_queue_no_reenter() is not reentrant: it
436 * would deadlock on monitor_lock. Work around by queueing
437 * events in thread-local storage.
438 * TODO: remove this, make it re-enter safe.
439 */
440 typedef struct MonitorQapiEvent {
441 QAPIEvent event;
442 QDict *qdict;
443 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
444 } MonitorQapiEvent;
445 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
446 static __thread bool reentered;
447 MonitorQapiEvent *ev;
448
449 if (!reentered) {
450 QSIMPLEQ_INIT(&event_queue);
451 }
452
453 ev = g_new(MonitorQapiEvent, 1);
454 ev->qdict = qobject_ref(qdict);
455 ev->event = event;
456 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
457 if (reentered) {
458 return;
459 }
460
461 reentered = true;
462
463 while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
464 QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
465 monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
466 qobject_unref(ev->qdict);
467 g_free(ev);
468 }
469
470 reentered = false;
471}
472
473/*
474 * This function runs evconf->rate ns after sending a throttled
475 * event.
476 * If another event has since been stored, send it.
477 */
478static void monitor_qapi_event_handler(void *opaque)
479{
480 MonitorQAPIEventState *evstate = opaque;
481 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
482
483 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
Mahmoud Mandoura8e2ab52021-03-11 05:15:34 +0200484 QEMU_LOCK_GUARD(&monitor_lock);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200485
486 if (evstate->qdict) {
487 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
488
489 monitor_qapi_event_emit(evstate->event, evstate->qdict);
490 qobject_unref(evstate->qdict);
491 evstate->qdict = NULL;
492 timer_mod_ns(evstate->timer, now + evconf->rate);
493 } else {
494 g_hash_table_remove(monitor_qapi_event_state, evstate);
495 qobject_unref(evstate->data);
496 timer_free(evstate->timer);
497 g_free(evstate);
498 }
Kevin Wolf1d95db72019-06-13 17:34:02 +0200499}
500
501static unsigned int qapi_event_throttle_hash(const void *key)
502{
503 const MonitorQAPIEventState *evstate = key;
504 unsigned int hash = evstate->event * 255;
505
506 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
507 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
508 }
509
510 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
511 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
512 }
513
David Hildenbrand77ae2302021-09-29 18:24:45 +0200514 if (evstate->event == QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE) {
515 hash += g_str_hash(qdict_get_str(evstate->data, "qom-path"));
516 }
517
Kevin Wolf1d95db72019-06-13 17:34:02 +0200518 return hash;
519}
520
521static gboolean qapi_event_throttle_equal(const void *a, const void *b)
522{
523 const MonitorQAPIEventState *eva = a;
524 const MonitorQAPIEventState *evb = b;
525
526 if (eva->event != evb->event) {
527 return FALSE;
528 }
529
530 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
531 return !strcmp(qdict_get_str(eva->data, "id"),
532 qdict_get_str(evb->data, "id"));
533 }
534
535 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
536 return !strcmp(qdict_get_str(eva->data, "node-name"),
537 qdict_get_str(evb->data, "node-name"));
538 }
539
David Hildenbrand77ae2302021-09-29 18:24:45 +0200540 if (eva->event == QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE) {
541 return !strcmp(qdict_get_str(eva->data, "qom-path"),
542 qdict_get_str(evb->data, "qom-path"));
543 }
544
Kevin Wolf1d95db72019-06-13 17:34:02 +0200545 return TRUE;
546}
547
548int monitor_suspend(Monitor *mon)
549{
550 if (monitor_is_hmp_non_interactive(mon)) {
551 return -ENOTTY;
552 }
553
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100554 qatomic_inc(&mon->suspend_cnt);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200555
556 if (mon->use_io_thread) {
557 /*
558 * Kick I/O thread to make sure this takes effect. It'll be
559 * evaluated again in prepare() of the watch object.
560 */
561 aio_notify(iothread_get_aio_context(mon_iothread));
562 }
563
564 trace_monitor_suspend(mon, 1);
565 return 0;
566}
567
568static void monitor_accept_input(void *opaque)
569{
570 Monitor *mon = opaque;
571
Paolo Bonzini6ee7c822023-03-03 13:32:13 +0100572 qemu_mutex_lock(&mon->mon_lock);
573 if (!monitor_is_qmp(mon) && mon->reset_seen) {
Paolo Bonzinic5d0c552023-05-17 17:19:03 +0200574 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
575 assert(hmp_mon->rs);
Paolo Bonzini6ee7c822023-03-03 13:32:13 +0100576 readline_restart(hmp_mon->rs);
577 qemu_mutex_unlock(&mon->mon_lock);
Paolo Bonzinic5d0c552023-05-17 17:19:03 +0200578 readline_show_prompt(hmp_mon->rs);
Paolo Bonzini6ee7c822023-03-03 13:32:13 +0100579 } else {
580 qemu_mutex_unlock(&mon->mon_lock);
Paolo Bonzinic5d0c552023-05-17 17:19:03 +0200581 }
582
Kevin Wolf1d95db72019-06-13 17:34:02 +0200583 qemu_chr_fe_accept_input(&mon->chr);
584}
585
586void monitor_resume(Monitor *mon)
587{
588 if (monitor_is_hmp_non_interactive(mon)) {
589 return;
590 }
591
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100592 if (qatomic_dec_fetch(&mon->suspend_cnt) == 0) {
Kevin Wolf1d95db72019-06-13 17:34:02 +0200593 AioContext *ctx;
594
595 if (mon->use_io_thread) {
596 ctx = iothread_get_aio_context(mon_iothread);
597 } else {
598 ctx = qemu_get_aio_context();
599 }
600
Kevin Wolf1d95db72019-06-13 17:34:02 +0200601 aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
602 }
603
604 trace_monitor_suspend(mon, -1);
605}
606
607int monitor_can_read(void *opaque)
608{
609 Monitor *mon = opaque;
610
Paolo Bonzini6ee7c822023-03-03 13:32:13 +0100611 return !qatomic_read(&mon->suspend_cnt);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200612}
613
614void monitor_list_append(Monitor *mon)
615{
616 qemu_mutex_lock(&monitor_lock);
617 /*
618 * This prevents inserting new monitors during monitor_cleanup().
619 * A cleaner solution would involve the main thread telling other
620 * threads to terminate, waiting for their termination.
621 */
622 if (!monitor_destroyed) {
623 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
624 mon = NULL;
625 }
626 qemu_mutex_unlock(&monitor_lock);
627
628 if (mon) {
629 monitor_data_destroy(mon);
630 g_free(mon);
631 }
632}
633
634static void monitor_iothread_init(void)
635{
636 mon_iothread = iothread_create("mon_iothread", &error_abort);
637}
638
Kevin Wolf92082412019-06-13 17:34:03 +0200639void monitor_data_init(Monitor *mon, bool is_qmp, bool skip_flush,
Kevin Wolf1d95db72019-06-13 17:34:02 +0200640 bool use_io_thread)
641{
642 if (use_io_thread && !mon_iothread) {
643 monitor_iothread_init();
644 }
645 qemu_mutex_init(&mon->mon_lock);
Kevin Wolf92082412019-06-13 17:34:03 +0200646 mon->is_qmp = is_qmp;
Markus Armbruster20076f42020-12-11 18:11:34 +0100647 mon->outbuf = g_string_new(NULL);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200648 mon->skip_flush = skip_flush;
649 mon->use_io_thread = use_io_thread;
Kevin Wolf1d95db72019-06-13 17:34:02 +0200650}
651
652void monitor_data_destroy(Monitor *mon)
653{
654 g_free(mon->mon_cpu_path);
655 qemu_chr_fe_deinit(&mon->chr, false);
656 if (monitor_is_qmp(mon)) {
657 monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
658 } else {
659 readline_free(container_of(mon, MonitorHMP, common)->rs);
660 }
Markus Armbruster20076f42020-12-11 18:11:34 +0100661 g_string_free(mon->outbuf, true);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200662 qemu_mutex_destroy(&mon->mon_lock);
663}
664
Kevin Wolf1d95db72019-06-13 17:34:02 +0200665void monitor_cleanup(void)
666{
667 /*
Kevin Wolf357bda92020-10-13 14:50:27 +0200668 * The dispatcher needs to stop before destroying the monitor and
669 * the I/O thread.
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200670 *
671 * We need to poll both qemu_aio_context and iohandler_ctx to make
672 * sure that the dispatcher coroutine keeps making progress and
673 * eventually terminates. qemu_aio_context is automatically
Stefan Hajnoczi9612aa42023-03-09 14:08:55 -0500674 * polled by calling AIO_WAIT_WHILE_UNLOCKED on it, but we must poll
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200675 * iohandler_ctx manually.
Kevin Wolfc81219a2021-02-12 18:20:27 +0100676 *
677 * Letting the iothread continue while shutting down the dispatcher
678 * means that new requests may still be coming in. This is okay,
679 * we'll just leave them in the queue without sending a response
680 * and monitor_data_destroy() will free them.
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200681 */
682 qmp_dispatcher_co_shutdown = true;
683 if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
684 aio_co_wake(qmp_dispatcher_co);
685 }
686
Stefan Hajnoczi9612aa42023-03-09 14:08:55 -0500687 AIO_WAIT_WHILE_UNLOCKED(NULL,
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200688 (aio_poll(iohandler_get_aio_context(), false),
689 qatomic_mb_read(&qmp_dispatcher_co_busy)));
690
Kevin Wolfc81219a2021-02-12 18:20:27 +0100691 /*
692 * We need to explicitly stop the I/O thread (but not destroy it),
693 * clean up the monitor resources, then destroy the I/O thread since
694 * we need to unregister from chardev below in
695 * monitor_data_destroy(), and chardev is not thread-safe yet
696 */
697 if (mon_iothread) {
698 iothread_stop(mon_iothread);
699 }
700
Kevin Wolf357bda92020-10-13 14:50:27 +0200701 /* Flush output buffers and destroy monitors */
702 qemu_mutex_lock(&monitor_lock);
703 monitor_destroyed = true;
704 while (!QTAILQ_EMPTY(&mon_list)) {
705 Monitor *mon = QTAILQ_FIRST(&mon_list);
706 QTAILQ_REMOVE(&mon_list, mon, entry);
707 /* Permit QAPI event emission from character frontend release */
708 qemu_mutex_unlock(&monitor_lock);
709 monitor_flush(mon);
710 monitor_data_destroy(mon);
711 qemu_mutex_lock(&monitor_lock);
712 g_free(mon);
713 }
714 qemu_mutex_unlock(&monitor_lock);
715
Kevin Wolf1d95db72019-06-13 17:34:02 +0200716 if (mon_iothread) {
717 iothread_destroy(mon_iothread);
718 mon_iothread = NULL;
719 }
720}
721
722static void monitor_qapi_event_init(void)
723{
724 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
725 qapi_event_throttle_equal);
726}
727
Markus Armbruster9d2b5f22023-01-24 13:19:45 +0100728void monitor_init_globals(void)
Kevin Wolf1d95db72019-06-13 17:34:02 +0200729{
730 monitor_qapi_event_init();
731 qemu_mutex_init(&monitor_lock);
Kevin Wolfe69ee452020-10-05 17:58:48 +0200732 coroutine_mon = g_hash_table_new(NULL, NULL);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200733
734 /*
735 * The dispatcher BH must run in the main loop thread, since we
736 * have commands assuming that context. It would be nice to get
737 * rid of those assumptions.
738 */
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200739 qmp_dispatcher_co = qemu_coroutine_create(monitor_qmp_dispatcher_co, NULL);
740 qatomic_mb_set(&qmp_dispatcher_co_busy, true);
741 aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200742}
743
Kevin Wolfa2f411c2020-02-24 15:30:07 +0100744int monitor_init(MonitorOptions *opts, bool allow_hmp, Error **errp)
Kevin Wolfc3e95552020-01-29 11:22:36 +0100745{
Markus Armbruster50707b32022-11-21 09:50:49 +0100746 ERRP_GUARD();
Kevin Wolfc3e95552020-01-29 11:22:36 +0100747 Chardev *chr;
Kevin Wolfc3e95552020-01-29 11:22:36 +0100748
Kevin Wolff2098722020-02-24 15:30:04 +0100749 chr = qemu_chr_find(opts->chardev);
Kevin Wolfc3e95552020-01-29 11:22:36 +0100750 if (chr == NULL) {
Kevin Wolff2098722020-02-24 15:30:04 +0100751 error_setg(errp, "chardev \"%s\" not found", opts->chardev);
Kevin Wolfc3e95552020-01-29 11:22:36 +0100752 return -1;
753 }
754
Kevin Wolfa2f411c2020-02-24 15:30:07 +0100755 if (!opts->has_mode) {
756 opts->mode = allow_hmp ? MONITOR_MODE_READLINE : MONITOR_MODE_CONTROL;
757 }
758
Kevin Wolff2098722020-02-24 15:30:04 +0100759 switch (opts->mode) {
760 case MONITOR_MODE_CONTROL:
Markus Armbruster50707b32022-11-21 09:50:49 +0100761 monitor_init_qmp(chr, opts->pretty, errp);
Kevin Wolff2098722020-02-24 15:30:04 +0100762 break;
763 case MONITOR_MODE_READLINE:
Kevin Wolfa2f411c2020-02-24 15:30:07 +0100764 if (!allow_hmp) {
765 error_setg(errp, "Only QMP is supported");
766 return -1;
767 }
Kevin Wolff2098722020-02-24 15:30:04 +0100768 if (opts->pretty) {
Daniel P. Berrangé283d8452021-02-19 17:56:13 +0000769 error_setg(errp, "'pretty' is not compatible with HMP monitors");
770 return -1;
Kevin Wolff2098722020-02-24 15:30:04 +0100771 }
Markus Armbruster50707b32022-11-21 09:50:49 +0100772 monitor_init_hmp(chr, true, errp);
Kevin Wolff2098722020-02-24 15:30:04 +0100773 break;
774 default:
775 g_assert_not_reached();
776 }
777
Markus Armbruster50707b32022-11-21 09:50:49 +0100778 return *errp ? -1 : 0;
Kevin Wolff2098722020-02-24 15:30:04 +0100779}
780
781int monitor_init_opts(QemuOpts *opts, Error **errp)
782{
783 Visitor *v;
784 MonitorOptions *options;
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200785 int ret;
Kevin Wolff2098722020-02-24 15:30:04 +0100786
787 v = opts_visitor_new(opts);
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200788 visit_type_MonitorOptions(v, NULL, &options, errp);
Kevin Wolff2098722020-02-24 15:30:04 +0100789 visit_free(v);
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200790 if (!options) {
Kevin Wolff2098722020-02-24 15:30:04 +0100791 return -1;
Kevin Wolfc3e95552020-01-29 11:22:36 +0100792 }
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200793
794 ret = monitor_init(options, true, errp);
795 qapi_free_MonitorOptions(options);
796 return ret;
Kevin Wolfc3e95552020-01-29 11:22:36 +0100797}
798
Kevin Wolf1d95db72019-06-13 17:34:02 +0200799QemuOptsList qemu_mon_opts = {
800 .name = "mon",
801 .implied_opt_name = "chardev",
802 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
803 .desc = {
804 {
805 .name = "mode",
806 .type = QEMU_OPT_STRING,
807 },{
808 .name = "chardev",
809 .type = QEMU_OPT_STRING,
810 },{
811 .name = "pretty",
812 .type = QEMU_OPT_BOOL,
813 },
814 { /* end of list */ }
815 },
816};