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
25 #include "qemu/osdep.h"
26 #include "monitor-internal.h"
27 #include "qapi/error.h"
28 #include "qapi/opts-visitor.h"
29 #include "qapi/qapi-emit-events.h"
30 #include "qapi/qapi-visit-control.h"
31 #include "qapi/qmp/qdict.h"
32 #include "qemu/error-report.h"
33 #include "qemu/option.h"
34 #include "sysemu/qtest.h"
38 * To prevent flooding clients, events can be throttled. The
39 * throttling is calculated globally, rather than per-Monitor
42 typedef 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
;
50 int64_t rate
; /* Minimum time (in ns) between two events */
51 } MonitorQAPIEventConf
;
53 /* Shared monitor I/O thread */
54 IOThread
*mon_iothread
;
56 /* Coroutine to dispatch the requests received from I/O thread */
57 Coroutine
*qmp_dispatcher_co
;
59 /* Set to true when the dispatcher coroutine should terminate */
60 bool qmp_dispatcher_co_shutdown
;
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).
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.
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.
76 * The coroutine will automatically change this variable back to false
77 * before it yields. Nobody else may set the variable to false.
79 * Access must be atomic for thread safety.
81 bool qmp_dispatcher_co_busy
;
84 * Protects mon_list, monitor_qapi_event_state, coroutine_mon,
87 QemuMutex monitor_lock
;
88 static GHashTable
*monitor_qapi_event_state
;
89 static GHashTable
*coroutine_mon
; /* Maps Coroutine* to Monitor* */
93 static bool monitor_destroyed
;
95 Monitor
*monitor_cur(void)
99 qemu_mutex_lock(&monitor_lock
);
100 mon
= g_hash_table_lookup(coroutine_mon
, qemu_coroutine_self());
101 qemu_mutex_unlock(&monitor_lock
);
107 * Sets a new current monitor and returns the old one.
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.
113 Monitor
*monitor_set_cur(Coroutine
*co
, Monitor
*mon
)
115 Monitor
*old_monitor
= monitor_cur();
117 qemu_mutex_lock(&monitor_lock
);
119 g_hash_table_replace(coroutine_mon
, co
, mon
);
121 g_hash_table_remove(coroutine_mon
, co
);
123 qemu_mutex_unlock(&monitor_lock
);
129 * Is the current monitor, if any, a QMP monitor?
131 bool monitor_cur_is_qmp(void)
133 Monitor
*cur_mon
= monitor_cur();
135 return cur_mon
&& monitor_is_qmp(cur_mon
);
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.
143 static inline bool monitor_uses_readline(const MonitorHMP
*mon
)
145 return mon
->use_readline
;
148 static inline bool monitor_is_hmp_non_interactive(const Monitor
*mon
)
150 if (monitor_is_qmp(mon
)) {
154 return !monitor_uses_readline(container_of(mon
, MonitorHMP
, common
));
157 static void monitor_flush_locked(Monitor
*mon
);
159 static gboolean
monitor_unblocked(void *do_not_use
, GIOCondition cond
,
162 Monitor
*mon
= opaque
;
164 qemu_mutex_lock(&mon
->mon_lock
);
166 monitor_flush_locked(mon
);
167 qemu_mutex_unlock(&mon
->mon_lock
);
171 /* Caller must hold mon->mon_lock */
172 static void monitor_flush_locked(Monitor
*mon
)
178 if (mon
->skip_flush
) {
182 buf
= mon
->outbuf
->str
;
183 len
= mon
->outbuf
->len
;
185 if (len
&& !mon
->mux_out
) {
186 rc
= qemu_chr_fe_write(&mon
->chr
, (const uint8_t *) buf
, len
);
187 if ((rc
< 0 && errno
!= EAGAIN
) || (rc
== len
)) {
188 /* all flushed or error */
189 g_string_truncate(mon
->outbuf
, 0);
194 g_string_erase(mon
->outbuf
, 0, rc
);
196 if (mon
->out_watch
== 0) {
198 qemu_chr_fe_add_watch(&mon
->chr
, G_IO_OUT
| G_IO_HUP
,
199 monitor_unblocked
, mon
);
204 void monitor_flush(Monitor
*mon
)
206 qemu_mutex_lock(&mon
->mon_lock
);
207 monitor_flush_locked(mon
);
208 qemu_mutex_unlock(&mon
->mon_lock
);
211 /* flush at every end of line */
212 int monitor_puts(Monitor
*mon
, const char *str
)
217 qemu_mutex_lock(&mon
->mon_lock
);
218 for (i
= 0; str
[i
]; i
++) {
221 g_string_append_c(mon
->outbuf
, '\r');
223 g_string_append_c(mon
->outbuf
, c
);
225 monitor_flush_locked(mon
);
228 qemu_mutex_unlock(&mon
->mon_lock
);
233 int monitor_vprintf(Monitor
*mon
, const char *fmt
, va_list ap
)
242 if (monitor_is_qmp(mon
)) {
246 buf
= g_strdup_vprintf(fmt
, ap
);
247 n
= monitor_puts(mon
, buf
);
252 int monitor_printf(Monitor
*mon
, const char *fmt
, ...)
258 ret
= monitor_vprintf(mon
, fmt
, ap
);
263 void monitor_printc(Monitor
*mon
, int c
)
265 monitor_printf(mon
, "'");
268 monitor_printf(mon
, "\\'");
271 monitor_printf(mon
, "\\\\");
274 monitor_printf(mon
, "\\n");
277 monitor_printf(mon
, "\\r");
280 if (c
>= 32 && c
<= 126) {
281 monitor_printf(mon
, "%c", c
);
283 monitor_printf(mon
, "\\x%02x", c
);
287 monitor_printf(mon
, "'");
291 * Print to current monitor if we have one, else to stderr.
293 int error_vprintf(const char *fmt
, va_list ap
)
295 Monitor
*cur_mon
= monitor_cur();
297 if (cur_mon
&& !monitor_cur_is_qmp()) {
298 return monitor_vprintf(cur_mon
, fmt
, ap
);
300 return vfprintf(stderr
, fmt
, ap
);
303 int error_vprintf_unless_qmp(const char *fmt
, va_list ap
)
305 Monitor
*cur_mon
= monitor_cur();
308 return vfprintf(stderr
, fmt
, ap
);
310 if (!monitor_cur_is_qmp()) {
311 return monitor_vprintf(cur_mon
, fmt
, ap
);
316 int error_printf_unless_qmp(const char *fmt
, ...)
322 ret
= error_vprintf_unless_qmp(fmt
, ap
);
327 static 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
},
335 [QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE
] = { 1000 * SCALE_MS
},
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().
344 static inline QEMUClockType
monitor_get_event_clock(void)
346 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL
: QEMU_CLOCK_REALTIME
;
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.
354 static void monitor_qapi_event_emit(QAPIEvent event
, QDict
*qdict
)
359 trace_monitor_protocol_event_emit(event
, qdict
);
360 QTAILQ_FOREACH(mon
, &mon_list
, entry
) {
361 if (!monitor_is_qmp(mon
)) {
365 qmp_mon
= container_of(mon
, MonitorQMP
, common
);
366 if (qmp_mon
->commands
!= &qmp_cap_negotiation_commands
) {
367 qmp_send_response(qmp_mon
, qdict
);
372 static void monitor_qapi_event_handler(void *opaque
);
375 * Queue a new event for emission to Monitor instances,
376 * applying any rate limiting if required.
379 monitor_qapi_event_queue_no_reenter(QAPIEvent event
, QDict
*qdict
)
381 MonitorQAPIEventConf
*evconf
;
382 MonitorQAPIEventState
*evstate
;
384 assert(event
< QAPI_EVENT__MAX
);
385 evconf
= &monitor_qapi_event_conf
[event
];
386 trace_monitor_protocol_event_queue(event
, qdict
, evconf
->rate
);
388 QEMU_LOCK_GUARD(&monitor_lock
);
391 /* Unthrottled event */
392 monitor_qapi_event_emit(event
, qdict
);
394 QDict
*data
= qobject_to(QDict
, qdict_get(qdict
, "data"));
395 MonitorQAPIEventState key
= { .event
= event
, .data
= data
};
397 evstate
= g_hash_table_lookup(monitor_qapi_event_state
, &key
);
398 assert(!evstate
|| timer_pending(evstate
->timer
));
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.
406 qobject_unref(evstate
->qdict
);
407 evstate
->qdict
= qobject_ref(qdict
);
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.
415 int64_t now
= qemu_clock_get_ns(monitor_get_event_clock());
417 monitor_qapi_event_emit(event
, qdict
);
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
,
426 g_hash_table_add(monitor_qapi_event_state
, evstate
);
427 timer_mod_ns(evstate
->timer
, now
+ evconf
->rate
);
432 void qapi_event_emit(QAPIEvent event
, QDict
*qdict
)
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.
440 typedef struct MonitorQapiEvent
{
443 QSIMPLEQ_ENTRY(MonitorQapiEvent
) entry
;
445 static __thread
QSIMPLEQ_HEAD(, MonitorQapiEvent
) event_queue
;
446 static __thread
bool reentered
;
447 MonitorQapiEvent
*ev
;
450 QSIMPLEQ_INIT(&event_queue
);
453 ev
= g_new(MonitorQapiEvent
, 1);
454 ev
->qdict
= qobject_ref(qdict
);
456 QSIMPLEQ_INSERT_TAIL(&event_queue
, ev
, entry
);
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
);
474 * This function runs evconf->rate ns after sending a throttled
476 * If another event has since been stored, send it.
478 static void monitor_qapi_event_handler(void *opaque
)
480 MonitorQAPIEventState
*evstate
= opaque
;
481 MonitorQAPIEventConf
*evconf
= &monitor_qapi_event_conf
[evstate
->event
];
483 trace_monitor_protocol_event_handler(evstate
->event
, evstate
->qdict
);
484 QEMU_LOCK_GUARD(&monitor_lock
);
486 if (evstate
->qdict
) {
487 int64_t now
= qemu_clock_get_ns(monitor_get_event_clock());
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
);
494 g_hash_table_remove(monitor_qapi_event_state
, evstate
);
495 qobject_unref(evstate
->data
);
496 timer_free(evstate
->timer
);
501 static unsigned int qapi_event_throttle_hash(const void *key
)
503 const MonitorQAPIEventState
*evstate
= key
;
504 unsigned int hash
= evstate
->event
* 255;
506 if (evstate
->event
== QAPI_EVENT_VSERPORT_CHANGE
) {
507 hash
+= g_str_hash(qdict_get_str(evstate
->data
, "id"));
510 if (evstate
->event
== QAPI_EVENT_QUORUM_REPORT_BAD
) {
511 hash
+= g_str_hash(qdict_get_str(evstate
->data
, "node-name"));
514 if (evstate
->event
== QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE
) {
515 hash
+= g_str_hash(qdict_get_str(evstate
->data
, "qom-path"));
521 static gboolean
qapi_event_throttle_equal(const void *a
, const void *b
)
523 const MonitorQAPIEventState
*eva
= a
;
524 const MonitorQAPIEventState
*evb
= b
;
526 if (eva
->event
!= evb
->event
) {
530 if (eva
->event
== QAPI_EVENT_VSERPORT_CHANGE
) {
531 return !strcmp(qdict_get_str(eva
->data
, "id"),
532 qdict_get_str(evb
->data
, "id"));
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"));
540 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"));
548 int monitor_suspend(Monitor
*mon
)
550 if (monitor_is_hmp_non_interactive(mon
)) {
554 qatomic_inc(&mon
->suspend_cnt
);
556 if (mon
->use_io_thread
) {
558 * Kick I/O thread to make sure this takes effect. It'll be
559 * evaluated again in prepare() of the watch object.
561 aio_notify(iothread_get_aio_context(mon_iothread
));
564 trace_monitor_suspend(mon
, 1);
568 static void monitor_accept_input(void *opaque
)
570 Monitor
*mon
= opaque
;
572 qemu_chr_fe_accept_input(&mon
->chr
);
575 void monitor_resume(Monitor
*mon
)
577 if (monitor_is_hmp_non_interactive(mon
)) {
581 if (qatomic_dec_fetch(&mon
->suspend_cnt
) == 0) {
584 if (mon
->use_io_thread
) {
585 ctx
= iothread_get_aio_context(mon_iothread
);
587 ctx
= qemu_get_aio_context();
590 if (!monitor_is_qmp(mon
)) {
591 MonitorHMP
*hmp_mon
= container_of(mon
, MonitorHMP
, common
);
593 readline_show_prompt(hmp_mon
->rs
);
596 aio_bh_schedule_oneshot(ctx
, monitor_accept_input
, mon
);
599 trace_monitor_suspend(mon
, -1);
602 int monitor_can_read(void *opaque
)
604 Monitor
*mon
= opaque
;
606 return !qatomic_mb_read(&mon
->suspend_cnt
);
609 void monitor_list_append(Monitor
*mon
)
611 qemu_mutex_lock(&monitor_lock
);
613 * This prevents inserting new monitors during monitor_cleanup().
614 * A cleaner solution would involve the main thread telling other
615 * threads to terminate, waiting for their termination.
617 if (!monitor_destroyed
) {
618 QTAILQ_INSERT_HEAD(&mon_list
, mon
, entry
);
621 qemu_mutex_unlock(&monitor_lock
);
624 monitor_data_destroy(mon
);
629 static void monitor_iothread_init(void)
631 mon_iothread
= iothread_create("mon_iothread", &error_abort
);
634 void monitor_data_init(Monitor
*mon
, bool is_qmp
, bool skip_flush
,
637 if (use_io_thread
&& !mon_iothread
) {
638 monitor_iothread_init();
640 qemu_mutex_init(&mon
->mon_lock
);
641 mon
->is_qmp
= is_qmp
;
642 mon
->outbuf
= g_string_new(NULL
);
643 mon
->skip_flush
= skip_flush
;
644 mon
->use_io_thread
= use_io_thread
;
647 void monitor_data_destroy(Monitor
*mon
)
649 g_free(mon
->mon_cpu_path
);
650 qemu_chr_fe_deinit(&mon
->chr
, false);
651 if (monitor_is_qmp(mon
)) {
652 monitor_data_destroy_qmp(container_of(mon
, MonitorQMP
, common
));
654 readline_free(container_of(mon
, MonitorHMP
, common
)->rs
);
656 g_string_free(mon
->outbuf
, true);
657 qemu_mutex_destroy(&mon
->mon_lock
);
660 void monitor_cleanup(void)
663 * The dispatcher needs to stop before destroying the monitor and
666 * We need to poll both qemu_aio_context and iohandler_ctx to make
667 * sure that the dispatcher coroutine keeps making progress and
668 * eventually terminates. qemu_aio_context is automatically
669 * polled by calling AIO_WAIT_WHILE on it, but we must poll
670 * iohandler_ctx manually.
672 * Letting the iothread continue while shutting down the dispatcher
673 * means that new requests may still be coming in. This is okay,
674 * we'll just leave them in the queue without sending a response
675 * and monitor_data_destroy() will free them.
677 qmp_dispatcher_co_shutdown
= true;
678 if (!qatomic_xchg(&qmp_dispatcher_co_busy
, true)) {
679 aio_co_wake(qmp_dispatcher_co
);
682 AIO_WAIT_WHILE(qemu_get_aio_context(),
683 (aio_poll(iohandler_get_aio_context(), false),
684 qatomic_mb_read(&qmp_dispatcher_co_busy
)));
687 * We need to explicitly stop the I/O thread (but not destroy it),
688 * clean up the monitor resources, then destroy the I/O thread since
689 * we need to unregister from chardev below in
690 * monitor_data_destroy(), and chardev is not thread-safe yet
693 iothread_stop(mon_iothread
);
696 /* Flush output buffers and destroy monitors */
697 qemu_mutex_lock(&monitor_lock
);
698 monitor_destroyed
= true;
699 while (!QTAILQ_EMPTY(&mon_list
)) {
700 Monitor
*mon
= QTAILQ_FIRST(&mon_list
);
701 QTAILQ_REMOVE(&mon_list
, mon
, entry
);
702 /* Permit QAPI event emission from character frontend release */
703 qemu_mutex_unlock(&monitor_lock
);
705 monitor_data_destroy(mon
);
706 qemu_mutex_lock(&monitor_lock
);
709 qemu_mutex_unlock(&monitor_lock
);
712 iothread_destroy(mon_iothread
);
717 static void monitor_qapi_event_init(void)
719 monitor_qapi_event_state
= g_hash_table_new(qapi_event_throttle_hash
,
720 qapi_event_throttle_equal
);
723 void monitor_init_globals(void)
725 monitor_qapi_event_init();
726 qemu_mutex_init(&monitor_lock
);
727 coroutine_mon
= g_hash_table_new(NULL
, NULL
);
730 * The dispatcher BH must run in the main loop thread, since we
731 * have commands assuming that context. It would be nice to get
732 * rid of those assumptions.
734 qmp_dispatcher_co
= qemu_coroutine_create(monitor_qmp_dispatcher_co
, NULL
);
735 qatomic_mb_set(&qmp_dispatcher_co_busy
, true);
736 aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co
);
739 int monitor_init(MonitorOptions
*opts
, bool allow_hmp
, Error
**errp
)
744 chr
= qemu_chr_find(opts
->chardev
);
746 error_setg(errp
, "chardev \"%s\" not found", opts
->chardev
);
750 if (!opts
->has_mode
) {
751 opts
->mode
= allow_hmp
? MONITOR_MODE_READLINE
: MONITOR_MODE_CONTROL
;
754 switch (opts
->mode
) {
755 case MONITOR_MODE_CONTROL
:
756 monitor_init_qmp(chr
, opts
->pretty
, errp
);
758 case MONITOR_MODE_READLINE
:
760 error_setg(errp
, "Only QMP is supported");
764 error_setg(errp
, "'pretty' is not compatible with HMP monitors");
767 monitor_init_hmp(chr
, true, errp
);
770 g_assert_not_reached();
773 return *errp
? -1 : 0;
776 int monitor_init_opts(QemuOpts
*opts
, Error
**errp
)
779 MonitorOptions
*options
;
782 v
= opts_visitor_new(opts
);
783 visit_type_MonitorOptions(v
, NULL
, &options
, errp
);
789 ret
= monitor_init(options
, true, errp
);
790 qapi_free_MonitorOptions(options
);
794 QemuOptsList qemu_mon_opts
= {
796 .implied_opt_name
= "chardev",
797 .head
= QTAILQ_HEAD_INITIALIZER(qemu_mon_opts
.head
),
801 .type
= QEMU_OPT_STRING
,
804 .type
= QEMU_OPT_STRING
,
807 .type
= QEMU_OPT_BOOL
,
809 { /* end of list */ }