blob: 640496e56263b03af6687902698c8ad8f62bea4f [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"
Markus Armbrusterd5938f22019-08-12 07:23:56 +020035#include "sysemu/sysemu.h"
Kevin Wolf1d95db72019-06-13 17:34:02 +020036#include "trace.h"
37
38/*
39 * To prevent flooding clients, events can be throttled. The
40 * throttling is calculated globally, rather than per-Monitor
41 * instance.
42 */
43typedef struct MonitorQAPIEventState {
44 QAPIEvent event; /* Throttling state for this event type and... */
45 QDict *data; /* ... data, see qapi_event_throttle_equal() */
46 QEMUTimer *timer; /* Timer for handling delayed events */
47 QDict *qdict; /* Delayed event (if any) */
48} MonitorQAPIEventState;
49
50typedef struct {
51 int64_t rate; /* Minimum time (in ns) between two events */
52} MonitorQAPIEventConf;
53
54/* Shared monitor I/O thread */
55IOThread *mon_iothread;
56
Kevin Wolf9ce44e22020-10-05 17:58:50 +020057/* Coroutine to dispatch the requests received from I/O thread */
58Coroutine *qmp_dispatcher_co;
59
60/* Set to true when the dispatcher coroutine should terminate */
61bool qmp_dispatcher_co_shutdown;
62
63/*
64 * qmp_dispatcher_co_busy is used for synchronisation between the
65 * monitor thread and the main thread to ensure that the dispatcher
66 * coroutine never gets scheduled a second time when it's already
67 * scheduled (scheduling the same coroutine twice is forbidden).
68 *
69 * It is true if the coroutine is active and processing requests.
70 * Additional requests may then be pushed onto mon->qmp_requests,
71 * and @qmp_dispatcher_co_shutdown may be set without further ado.
72 * @qmp_dispatcher_co_busy must not be woken up in this case.
73 *
74 * If false, you also have to set @qmp_dispatcher_co_busy to true and
75 * wake up @qmp_dispatcher_co after pushing the new requests.
76 *
77 * The coroutine will automatically change this variable back to false
78 * before it yields. Nobody else may set the variable to false.
79 *
80 * Access must be atomic for thread safety.
81 */
82bool qmp_dispatcher_co_busy;
Kevin Wolf1d95db72019-06-13 17:34:02 +020083
Kevin Wolfe69ee452020-10-05 17:58:48 +020084/*
85 * Protects mon_list, monitor_qapi_event_state, coroutine_mon,
86 * monitor_destroyed.
87 */
Kevin Wolf1d95db72019-06-13 17:34:02 +020088QemuMutex monitor_lock;
89static GHashTable *monitor_qapi_event_state;
Kevin Wolfe69ee452020-10-05 17:58:48 +020090static GHashTable *coroutine_mon; /* Maps Coroutine* to Monitor* */
Kevin Wolf1d95db72019-06-13 17:34:02 +020091
92MonitorList mon_list;
93int mon_refcount;
94static bool monitor_destroyed;
95
Kevin Wolf947e4742020-10-05 17:58:44 +020096Monitor *monitor_cur(void)
97{
Kevin Wolfe69ee452020-10-05 17:58:48 +020098 Monitor *mon;
99
100 qemu_mutex_lock(&monitor_lock);
101 mon = g_hash_table_lookup(coroutine_mon, qemu_coroutine_self());
102 qemu_mutex_unlock(&monitor_lock);
103
104 return mon;
Kevin Wolf947e4742020-10-05 17:58:44 +0200105}
106
107/**
108 * Sets a new current monitor and returns the old one.
Kevin Wolfe69ee452020-10-05 17:58:48 +0200109 *
110 * If a non-NULL monitor is set for a coroutine, another call
111 * resetting it to NULL is required before the coroutine terminates,
112 * otherwise a stale entry would remain in the hash table.
Kevin Wolf947e4742020-10-05 17:58:44 +0200113 */
Kevin Wolfe69ee452020-10-05 17:58:48 +0200114Monitor *monitor_set_cur(Coroutine *co, Monitor *mon)
Kevin Wolf947e4742020-10-05 17:58:44 +0200115{
Kevin Wolfe69ee452020-10-05 17:58:48 +0200116 Monitor *old_monitor = monitor_cur();
Kevin Wolf947e4742020-10-05 17:58:44 +0200117
Kevin Wolfe69ee452020-10-05 17:58:48 +0200118 qemu_mutex_lock(&monitor_lock);
119 if (mon) {
120 g_hash_table_replace(coroutine_mon, co, mon);
121 } else {
122 g_hash_table_remove(coroutine_mon, co);
123 }
124 qemu_mutex_unlock(&monitor_lock);
125
Kevin Wolf947e4742020-10-05 17:58:44 +0200126 return old_monitor;
127}
Kevin Wolf1d95db72019-06-13 17:34:02 +0200128
129/**
130 * Is the current monitor, if any, a QMP monitor?
131 */
132bool monitor_cur_is_qmp(void)
133{
Kevin Wolf947e4742020-10-05 17:58:44 +0200134 Monitor *cur_mon = monitor_cur();
135
Kevin Wolf1d95db72019-06-13 17:34:02 +0200136 return cur_mon && monitor_is_qmp(cur_mon);
137}
138
139/**
140 * Is @mon is using readline?
141 * Note: not all HMP monitors use readline, e.g., gdbserver has a
142 * non-interactive HMP monitor, so readline is not used there.
143 */
Kevin Wolf92082412019-06-13 17:34:03 +0200144static inline bool monitor_uses_readline(const MonitorHMP *mon)
Kevin Wolf1d95db72019-06-13 17:34:02 +0200145{
Kevin Wolf92082412019-06-13 17:34:03 +0200146 return mon->use_readline;
Kevin Wolf1d95db72019-06-13 17:34:02 +0200147}
148
149static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
150{
Kevin Wolf92082412019-06-13 17:34:03 +0200151 if (monitor_is_qmp(mon)) {
152 return false;
153 }
154
155 return !monitor_uses_readline(container_of(mon, MonitorHMP, common));
Kevin Wolf1d95db72019-06-13 17:34:02 +0200156}
157
158static void monitor_flush_locked(Monitor *mon);
159
160static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
161 void *opaque)
162{
163 Monitor *mon = opaque;
164
165 qemu_mutex_lock(&mon->mon_lock);
166 mon->out_watch = 0;
167 monitor_flush_locked(mon);
168 qemu_mutex_unlock(&mon->mon_lock);
169 return FALSE;
170}
171
172/* Caller must hold mon->mon_lock */
173static void monitor_flush_locked(Monitor *mon)
174{
175 int rc;
176 size_t len;
177 const char *buf;
178
179 if (mon->skip_flush) {
180 return;
181 }
182
Markus Armbruster20076f42020-12-11 18:11:34 +0100183 buf = mon->outbuf->str;
184 len = mon->outbuf->len;
Kevin Wolf1d95db72019-06-13 17:34:02 +0200185
186 if (len && !mon->mux_out) {
187 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
188 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
189 /* all flushed or error */
Markus Armbruster20076f42020-12-11 18:11:34 +0100190 g_string_truncate(mon->outbuf, 0);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200191 return;
192 }
193 if (rc > 0) {
194 /* partial write */
Markus Armbruster20076f42020-12-11 18:11:34 +0100195 g_string_erase(mon->outbuf, 0, rc);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200196 }
197 if (mon->out_watch == 0) {
198 mon->out_watch =
199 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
200 monitor_unblocked, mon);
201 }
202 }
203}
204
205void monitor_flush(Monitor *mon)
206{
207 qemu_mutex_lock(&mon->mon_lock);
208 monitor_flush_locked(mon);
209 qemu_mutex_unlock(&mon->mon_lock);
210}
211
212/* flush at every end of line */
213int monitor_puts(Monitor *mon, const char *str)
214{
215 int i;
216 char c;
217
218 qemu_mutex_lock(&mon->mon_lock);
219 for (i = 0; str[i]; i++) {
220 c = str[i];
221 if (c == '\n') {
Markus Armbruster20076f42020-12-11 18:11:34 +0100222 g_string_append_c(mon->outbuf, '\r');
Kevin Wolf1d95db72019-06-13 17:34:02 +0200223 }
Markus Armbruster20076f42020-12-11 18:11:34 +0100224 g_string_append_c(mon->outbuf, c);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200225 if (c == '\n') {
226 monitor_flush_locked(mon);
227 }
228 }
229 qemu_mutex_unlock(&mon->mon_lock);
230
231 return i;
232}
233
234int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
235{
236 char *buf;
237 int n;
238
239 if (!mon) {
240 return -1;
241 }
242
243 if (monitor_is_qmp(mon)) {
244 return -1;
245 }
246
247 buf = g_strdup_vprintf(fmt, ap);
248 n = monitor_puts(mon, buf);
249 g_free(buf);
250 return n;
251}
252
253int monitor_printf(Monitor *mon, const char *fmt, ...)
254{
255 int ret;
256
257 va_list ap;
258 va_start(ap, fmt);
259 ret = monitor_vprintf(mon, fmt, ap);
260 va_end(ap);
261 return ret;
262}
263
264/*
265 * Print to current monitor if we have one, else to stderr.
266 */
267int error_vprintf(const char *fmt, va_list ap)
268{
Kevin Wolf947e4742020-10-05 17:58:44 +0200269 Monitor *cur_mon = monitor_cur();
270
Kevin Wolf1d95db72019-06-13 17:34:02 +0200271 if (cur_mon && !monitor_cur_is_qmp()) {
272 return monitor_vprintf(cur_mon, fmt, ap);
273 }
274 return vfprintf(stderr, fmt, ap);
275}
276
277int error_vprintf_unless_qmp(const char *fmt, va_list ap)
278{
Kevin Wolf947e4742020-10-05 17:58:44 +0200279 Monitor *cur_mon = monitor_cur();
280
Kevin Wolf1d95db72019-06-13 17:34:02 +0200281 if (!cur_mon) {
282 return vfprintf(stderr, fmt, ap);
283 }
284 if (!monitor_cur_is_qmp()) {
285 return monitor_vprintf(cur_mon, fmt, ap);
286 }
287 return -1;
288}
289
290
291static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
292 /* Limit guest-triggerable events to 1 per second */
293 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
294 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
295 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
296 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
297 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
298 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
David Hildenbrand722a3c72020-06-26 09:22:44 +0200299 [QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE] = { 1000 * SCALE_MS },
Kevin Wolf1d95db72019-06-13 17:34:02 +0200300};
301
302/*
303 * Return the clock to use for recording an event's time.
304 * It's QEMU_CLOCK_REALTIME, except for qtests it's
305 * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
306 * Beware: result is invalid before configure_accelerator().
307 */
308static inline QEMUClockType monitor_get_event_clock(void)
309{
310 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
311}
312
313/*
314 * Broadcast an event to all monitors.
315 * @qdict is the event object. Its member "event" must match @event.
316 * Caller must hold monitor_lock.
317 */
318static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
319{
320 Monitor *mon;
321 MonitorQMP *qmp_mon;
322
323 trace_monitor_protocol_event_emit(event, qdict);
324 QTAILQ_FOREACH(mon, &mon_list, entry) {
325 if (!monitor_is_qmp(mon)) {
326 continue;
327 }
328
329 qmp_mon = container_of(mon, MonitorQMP, common);
330 if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
331 qmp_send_response(qmp_mon, qdict);
332 }
333 }
334}
335
336static void monitor_qapi_event_handler(void *opaque);
337
338/*
339 * Queue a new event for emission to Monitor instances,
340 * applying any rate limiting if required.
341 */
342static void
343monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
344{
345 MonitorQAPIEventConf *evconf;
346 MonitorQAPIEventState *evstate;
347
348 assert(event < QAPI_EVENT__MAX);
349 evconf = &monitor_qapi_event_conf[event];
350 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
351
Mahmoud Mandoura8e2ab52021-03-11 05:15:34 +0200352 QEMU_LOCK_GUARD(&monitor_lock);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200353
354 if (!evconf->rate) {
355 /* Unthrottled event */
356 monitor_qapi_event_emit(event, qdict);
357 } else {
358 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
359 MonitorQAPIEventState key = { .event = event, .data = data };
360
361 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
362 assert(!evstate || timer_pending(evstate->timer));
363
364 if (evstate) {
365 /*
366 * Timer is pending for (at least) evconf->rate ns after
367 * last send. Store event for sending when timer fires,
368 * replacing a prior stored event if any.
369 */
370 qobject_unref(evstate->qdict);
371 evstate->qdict = qobject_ref(qdict);
372 } else {
373 /*
374 * Last send was (at least) evconf->rate ns ago.
375 * Send immediately, and arm the timer to call
376 * monitor_qapi_event_handler() in evconf->rate ns. Any
377 * events arriving before then will be delayed until then.
378 */
379 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
380
381 monitor_qapi_event_emit(event, qdict);
382
383 evstate = g_new(MonitorQAPIEventState, 1);
384 evstate->event = event;
385 evstate->data = qobject_ref(data);
386 evstate->qdict = NULL;
387 evstate->timer = timer_new_ns(monitor_get_event_clock(),
388 monitor_qapi_event_handler,
389 evstate);
390 g_hash_table_add(monitor_qapi_event_state, evstate);
391 timer_mod_ns(evstate->timer, now + evconf->rate);
392 }
393 }
Kevin Wolf1d95db72019-06-13 17:34:02 +0200394}
395
396void qapi_event_emit(QAPIEvent event, QDict *qdict)
397{
398 /*
399 * monitor_qapi_event_queue_no_reenter() is not reentrant: it
400 * would deadlock on monitor_lock. Work around by queueing
401 * events in thread-local storage.
402 * TODO: remove this, make it re-enter safe.
403 */
404 typedef struct MonitorQapiEvent {
405 QAPIEvent event;
406 QDict *qdict;
407 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
408 } MonitorQapiEvent;
409 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
410 static __thread bool reentered;
411 MonitorQapiEvent *ev;
412
413 if (!reentered) {
414 QSIMPLEQ_INIT(&event_queue);
415 }
416
417 ev = g_new(MonitorQapiEvent, 1);
418 ev->qdict = qobject_ref(qdict);
419 ev->event = event;
420 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
421 if (reentered) {
422 return;
423 }
424
425 reentered = true;
426
427 while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
428 QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
429 monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
430 qobject_unref(ev->qdict);
431 g_free(ev);
432 }
433
434 reentered = false;
435}
436
437/*
438 * This function runs evconf->rate ns after sending a throttled
439 * event.
440 * If another event has since been stored, send it.
441 */
442static void monitor_qapi_event_handler(void *opaque)
443{
444 MonitorQAPIEventState *evstate = opaque;
445 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
446
447 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
Mahmoud Mandoura8e2ab52021-03-11 05:15:34 +0200448 QEMU_LOCK_GUARD(&monitor_lock);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200449
450 if (evstate->qdict) {
451 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
452
453 monitor_qapi_event_emit(evstate->event, evstate->qdict);
454 qobject_unref(evstate->qdict);
455 evstate->qdict = NULL;
456 timer_mod_ns(evstate->timer, now + evconf->rate);
457 } else {
458 g_hash_table_remove(monitor_qapi_event_state, evstate);
459 qobject_unref(evstate->data);
460 timer_free(evstate->timer);
461 g_free(evstate);
462 }
Kevin Wolf1d95db72019-06-13 17:34:02 +0200463}
464
465static unsigned int qapi_event_throttle_hash(const void *key)
466{
467 const MonitorQAPIEventState *evstate = key;
468 unsigned int hash = evstate->event * 255;
469
470 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
471 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
472 }
473
474 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
475 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
476 }
477
478 return hash;
479}
480
481static gboolean qapi_event_throttle_equal(const void *a, const void *b)
482{
483 const MonitorQAPIEventState *eva = a;
484 const MonitorQAPIEventState *evb = b;
485
486 if (eva->event != evb->event) {
487 return FALSE;
488 }
489
490 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
491 return !strcmp(qdict_get_str(eva->data, "id"),
492 qdict_get_str(evb->data, "id"));
493 }
494
495 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
496 return !strcmp(qdict_get_str(eva->data, "node-name"),
497 qdict_get_str(evb->data, "node-name"));
498 }
499
500 return TRUE;
501}
502
503int monitor_suspend(Monitor *mon)
504{
505 if (monitor_is_hmp_non_interactive(mon)) {
506 return -ENOTTY;
507 }
508
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100509 qatomic_inc(&mon->suspend_cnt);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200510
511 if (mon->use_io_thread) {
512 /*
513 * Kick I/O thread to make sure this takes effect. It'll be
514 * evaluated again in prepare() of the watch object.
515 */
516 aio_notify(iothread_get_aio_context(mon_iothread));
517 }
518
519 trace_monitor_suspend(mon, 1);
520 return 0;
521}
522
523static void monitor_accept_input(void *opaque)
524{
525 Monitor *mon = opaque;
526
527 qemu_chr_fe_accept_input(&mon->chr);
528}
529
530void monitor_resume(Monitor *mon)
531{
532 if (monitor_is_hmp_non_interactive(mon)) {
533 return;
534 }
535
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100536 if (qatomic_dec_fetch(&mon->suspend_cnt) == 0) {
Kevin Wolf1d95db72019-06-13 17:34:02 +0200537 AioContext *ctx;
538
539 if (mon->use_io_thread) {
540 ctx = iothread_get_aio_context(mon_iothread);
541 } else {
542 ctx = qemu_get_aio_context();
543 }
544
545 if (!monitor_is_qmp(mon)) {
546 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
547 assert(hmp_mon->rs);
548 readline_show_prompt(hmp_mon->rs);
549 }
550
551 aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
552 }
553
554 trace_monitor_suspend(mon, -1);
555}
556
557int monitor_can_read(void *opaque)
558{
559 Monitor *mon = opaque;
560
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100561 return !qatomic_mb_read(&mon->suspend_cnt);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200562}
563
564void monitor_list_append(Monitor *mon)
565{
566 qemu_mutex_lock(&monitor_lock);
567 /*
568 * This prevents inserting new monitors during monitor_cleanup().
569 * A cleaner solution would involve the main thread telling other
570 * threads to terminate, waiting for their termination.
571 */
572 if (!monitor_destroyed) {
573 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
574 mon = NULL;
575 }
576 qemu_mutex_unlock(&monitor_lock);
577
578 if (mon) {
579 monitor_data_destroy(mon);
580 g_free(mon);
581 }
582}
583
584static void monitor_iothread_init(void)
585{
586 mon_iothread = iothread_create("mon_iothread", &error_abort);
587}
588
Kevin Wolf92082412019-06-13 17:34:03 +0200589void monitor_data_init(Monitor *mon, bool is_qmp, bool skip_flush,
Kevin Wolf1d95db72019-06-13 17:34:02 +0200590 bool use_io_thread)
591{
592 if (use_io_thread && !mon_iothread) {
593 monitor_iothread_init();
594 }
595 qemu_mutex_init(&mon->mon_lock);
Kevin Wolf92082412019-06-13 17:34:03 +0200596 mon->is_qmp = is_qmp;
Markus Armbruster20076f42020-12-11 18:11:34 +0100597 mon->outbuf = g_string_new(NULL);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200598 mon->skip_flush = skip_flush;
599 mon->use_io_thread = use_io_thread;
Kevin Wolf1d95db72019-06-13 17:34:02 +0200600}
601
602void monitor_data_destroy(Monitor *mon)
603{
604 g_free(mon->mon_cpu_path);
605 qemu_chr_fe_deinit(&mon->chr, false);
606 if (monitor_is_qmp(mon)) {
607 monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
608 } else {
609 readline_free(container_of(mon, MonitorHMP, common)->rs);
610 }
Markus Armbruster20076f42020-12-11 18:11:34 +0100611 g_string_free(mon->outbuf, true);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200612 qemu_mutex_destroy(&mon->mon_lock);
613}
614
Kevin Wolf1d95db72019-06-13 17:34:02 +0200615void monitor_cleanup(void)
616{
617 /*
Kevin Wolf357bda92020-10-13 14:50:27 +0200618 * The dispatcher needs to stop before destroying the monitor and
619 * the I/O thread.
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200620 *
621 * We need to poll both qemu_aio_context and iohandler_ctx to make
622 * sure that the dispatcher coroutine keeps making progress and
623 * eventually terminates. qemu_aio_context is automatically
624 * polled by calling AIO_WAIT_WHILE on it, but we must poll
625 * iohandler_ctx manually.
Kevin Wolfc81219a2021-02-12 18:20:27 +0100626 *
627 * Letting the iothread continue while shutting down the dispatcher
628 * means that new requests may still be coming in. This is okay,
629 * we'll just leave them in the queue without sending a response
630 * and monitor_data_destroy() will free them.
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200631 */
632 qmp_dispatcher_co_shutdown = true;
633 if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
634 aio_co_wake(qmp_dispatcher_co);
635 }
636
637 AIO_WAIT_WHILE(qemu_get_aio_context(),
638 (aio_poll(iohandler_get_aio_context(), false),
639 qatomic_mb_read(&qmp_dispatcher_co_busy)));
640
Kevin Wolfc81219a2021-02-12 18:20:27 +0100641 /*
642 * We need to explicitly stop the I/O thread (but not destroy it),
643 * clean up the monitor resources, then destroy the I/O thread since
644 * we need to unregister from chardev below in
645 * monitor_data_destroy(), and chardev is not thread-safe yet
646 */
647 if (mon_iothread) {
648 iothread_stop(mon_iothread);
649 }
650
Kevin Wolf357bda92020-10-13 14:50:27 +0200651 /* Flush output buffers and destroy monitors */
652 qemu_mutex_lock(&monitor_lock);
653 monitor_destroyed = true;
654 while (!QTAILQ_EMPTY(&mon_list)) {
655 Monitor *mon = QTAILQ_FIRST(&mon_list);
656 QTAILQ_REMOVE(&mon_list, mon, entry);
657 /* Permit QAPI event emission from character frontend release */
658 qemu_mutex_unlock(&monitor_lock);
659 monitor_flush(mon);
660 monitor_data_destroy(mon);
661 qemu_mutex_lock(&monitor_lock);
662 g_free(mon);
663 }
664 qemu_mutex_unlock(&monitor_lock);
665
Kevin Wolf1d95db72019-06-13 17:34:02 +0200666 if (mon_iothread) {
667 iothread_destroy(mon_iothread);
668 mon_iothread = NULL;
669 }
670}
671
672static void monitor_qapi_event_init(void)
673{
674 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
675 qapi_event_throttle_equal);
676}
677
678void monitor_init_globals_core(void)
679{
680 monitor_qapi_event_init();
681 qemu_mutex_init(&monitor_lock);
Kevin Wolfe69ee452020-10-05 17:58:48 +0200682 coroutine_mon = g_hash_table_new(NULL, NULL);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200683
684 /*
685 * The dispatcher BH must run in the main loop thread, since we
686 * have commands assuming that context. It would be nice to get
687 * rid of those assumptions.
688 */
Kevin Wolf9ce44e22020-10-05 17:58:50 +0200689 qmp_dispatcher_co = qemu_coroutine_create(monitor_qmp_dispatcher_co, NULL);
690 qatomic_mb_set(&qmp_dispatcher_co_busy, true);
691 aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
Kevin Wolf1d95db72019-06-13 17:34:02 +0200692}
693
Kevin Wolfa2f411c2020-02-24 15:30:07 +0100694int monitor_init(MonitorOptions *opts, bool allow_hmp, Error **errp)
Kevin Wolfc3e95552020-01-29 11:22:36 +0100695{
696 Chardev *chr;
Kevin Wolff27a9bb2020-02-24 15:30:05 +0100697 Error *local_err = NULL;
Kevin Wolfc3e95552020-01-29 11:22:36 +0100698
Kevin Wolff2098722020-02-24 15:30:04 +0100699 chr = qemu_chr_find(opts->chardev);
Kevin Wolfc3e95552020-01-29 11:22:36 +0100700 if (chr == NULL) {
Kevin Wolff2098722020-02-24 15:30:04 +0100701 error_setg(errp, "chardev \"%s\" not found", opts->chardev);
Kevin Wolfc3e95552020-01-29 11:22:36 +0100702 return -1;
703 }
704
Kevin Wolfa2f411c2020-02-24 15:30:07 +0100705 if (!opts->has_mode) {
706 opts->mode = allow_hmp ? MONITOR_MODE_READLINE : MONITOR_MODE_CONTROL;
707 }
708
Kevin Wolff2098722020-02-24 15:30:04 +0100709 switch (opts->mode) {
710 case MONITOR_MODE_CONTROL:
Kevin Wolff27a9bb2020-02-24 15:30:05 +0100711 monitor_init_qmp(chr, opts->pretty, &local_err);
Kevin Wolff2098722020-02-24 15:30:04 +0100712 break;
713 case MONITOR_MODE_READLINE:
Kevin Wolfa2f411c2020-02-24 15:30:07 +0100714 if (!allow_hmp) {
715 error_setg(errp, "Only QMP is supported");
716 return -1;
717 }
Kevin Wolff2098722020-02-24 15:30:04 +0100718 if (opts->pretty) {
719 warn_report("'pretty' is deprecated for HMP monitors, it has no "
720 "effect and will be removed in future versions");
721 }
Kevin Wolf8e9119a2020-02-24 15:30:06 +0100722 monitor_init_hmp(chr, true, &local_err);
Kevin Wolff2098722020-02-24 15:30:04 +0100723 break;
724 default:
725 g_assert_not_reached();
726 }
727
Kevin Wolff27a9bb2020-02-24 15:30:05 +0100728 if (local_err) {
729 error_propagate(errp, local_err);
730 return -1;
731 }
Kevin Wolff2098722020-02-24 15:30:04 +0100732 return 0;
733}
734
735int monitor_init_opts(QemuOpts *opts, Error **errp)
736{
737 Visitor *v;
738 MonitorOptions *options;
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200739 int ret;
Kevin Wolff2098722020-02-24 15:30:04 +0100740
741 v = opts_visitor_new(opts);
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200742 visit_type_MonitorOptions(v, NULL, &options, errp);
Kevin Wolff2098722020-02-24 15:30:04 +0100743 visit_free(v);
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200744 if (!options) {
Kevin Wolff2098722020-02-24 15:30:04 +0100745 return -1;
Kevin Wolfc3e95552020-01-29 11:22:36 +0100746 }
Markus Armbrusterb11a0932020-07-07 18:06:07 +0200747
748 ret = monitor_init(options, true, errp);
749 qapi_free_MonitorOptions(options);
750 return ret;
Kevin Wolfc3e95552020-01-29 11:22:36 +0100751}
752
Kevin Wolf1d95db72019-06-13 17:34:02 +0200753QemuOptsList qemu_mon_opts = {
754 .name = "mon",
755 .implied_opt_name = "chardev",
756 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
757 .desc = {
758 {
759 .name = "mode",
760 .type = QEMU_OPT_STRING,
761 },{
762 .name = "chardev",
763 .type = QEMU_OPT_STRING,
764 },{
765 .name = "pretty",
766 .type = QEMU_OPT_BOOL,
767 },
768 { /* end of list */ }
769 },
770};