From 854f63d44065567c2991b5050f7d4011ca985c4e Mon Sep 17 00:00:00 2001 From: Yury Kotov Date: Thu, 23 May 2019 12:44:33 +0300 Subject: monitor: Fix return type of monitor_fdset_dup_fd_find monitor_fdset_dup_fd_find_remove() and monitor_fdset_dup_fd_find() return mon_fdset->id which is int64_t. Downcasting from int64_t to int leads to a bug with removing fd from fdset with id >= 2^32. So, fix return types for these function. Signed-off-by: Yury Kotov Reviewed-by: Markus Armbruster Message-Id: <20190523094433.30297-1-yury-kotov@yandex-team.ru> Signed-off-by: Markus Armbruster --- include/monitor/monitor.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'include') diff --git a/include/monitor/monitor.h b/include/monitor/monitor.h index 06cfcd8f36..1e1d6d2269 100644 --- a/include/monitor/monitor.h +++ b/include/monitor/monitor.h @@ -44,6 +44,6 @@ AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id, int monitor_fdset_get_fd(int64_t fdset_id, int flags); int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd); void monitor_fdset_dup_fd_remove(int dup_fd); -int monitor_fdset_dup_fd_find(int dup_fd); +int64_t monitor_fdset_dup_fd_find(int dup_fd); #endif /* MONITOR_H */ -- cgit v1.2.3-55-g7522 From 5f9dba1600de5e6312ea2d86cff61a5f03c8207e Mon Sep 17 00:00:00 2001 From: Kevin Wolf Date: Thu, 13 Jun 2019 17:33:54 +0200 Subject: monitor: Create MonitorHMP with readline state The ReadLineState in Monitor is only used for HMP monitors. Create MonitorHMP and move it there. Can't use container_of() in hmp_change(). Cast instead, and mark FIXME. Will be cleaned up shortly. Signed-off-by: Kevin Wolf Reviewed-by: Dr. David Alan Gilbert Message-Id: <20190613153405.24769-5-kwolf@redhat.com> Reviewed-by: Markus Armbruster [Superfluous variable in monitor_data_destroy() eliminated, whitespace tweaked in hmp_change(), commit message improved] Signed-off-by: Markus Armbruster --- hmp.c | 4 +- include/monitor/monitor.h | 5 +- monitor.c | 126 ++++++++++++++++++++++++++-------------------- 3 files changed, 77 insertions(+), 58 deletions(-) (limited to 'include') diff --git a/hmp.c b/hmp.c index be5e345c6f..e6ea7cb9c2 100644 --- a/hmp.c +++ b/hmp.c @@ -1943,6 +1943,8 @@ static void hmp_change_read_arg(void *opaque, const char *password, void hmp_change(Monitor *mon, const QDict *qdict) { + /* FIXME Make MonitorHMP public and use container_of */ + MonitorHMP *hmp_mon = (MonitorHMP *)mon; const char *device = qdict_get_str(qdict, "device"); const char *target = qdict_get_str(qdict, "target"); const char *arg = qdict_get_try_str(qdict, "arg"); @@ -1960,7 +1962,7 @@ void hmp_change(Monitor *mon, const QDict *qdict) if (strcmp(target, "passwd") == 0 || strcmp(target, "password") == 0) { if (!arg) { - monitor_read_password(mon, hmp_change_read_arg, NULL); + monitor_read_password(hmp_mon, hmp_change_read_arg, NULL); return; } } diff --git a/include/monitor/monitor.h b/include/monitor/monitor.h index 1e1d6d2269..f9d30e1d78 100644 --- a/include/monitor/monitor.h +++ b/include/monitor/monitor.h @@ -6,6 +6,7 @@ #include "qemu/readline.h" extern __thread Monitor *cur_mon; +typedef struct MonitorHMP MonitorHMP; /* flags for monitor_init */ /* 0x01 unused */ @@ -34,8 +35,8 @@ void monitor_flush(Monitor *mon); int monitor_set_cpu(int cpu_index); int monitor_get_cpu_index(void); -void monitor_read_command(Monitor *mon, int show_prompt); -int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func, +void monitor_read_command(MonitorHMP *mon, int show_prompt); +int monitor_read_password(MonitorHMP *mon, ReadLineFunc *readline_func, void *opaque); AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id, diff --git a/monitor.c b/monitor.c index 15f94fc41f..7c57308e2a 100644 --- a/monitor.c +++ b/monitor.c @@ -192,14 +192,6 @@ struct Monitor { bool skip_flush; bool use_io_thread; - /* - * State used only in the thread "owning" the monitor. - * If @use_io_thread, this is @mon_iothread. - * Else, it's the main thread. - * These members can be safely accessed without locks. - */ - ReadLineState *rs; - gchar *mon_cpu_path; mon_cmd_t *cmd_table; QTAILQ_ENTRY(Monitor) entry; @@ -220,6 +212,18 @@ struct Monitor { int mux_out; }; +struct MonitorHMP { + Monitor common; + /* + * State used only in the thread "owning" the monitor. + * If @use_io_thread, this is @mon_iothread. (This does not actually happen + * in the current state of the code.) + * Else, it's the main thread. + * These members can be safely accessed without locks. + */ + ReadLineState *rs; +}; + typedef struct { Monitor common; JSONMessageParser parser; @@ -326,7 +330,7 @@ bool monitor_cur_is_qmp(void) return cur_mon && monitor_is_qmp(cur_mon); } -void monitor_read_command(Monitor *mon, int show_prompt) +void monitor_read_command(MonitorHMP *mon, int show_prompt) { if (!mon->rs) return; @@ -336,7 +340,7 @@ void monitor_read_command(Monitor *mon, int show_prompt) readline_show_prompt(mon->rs); } -int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func, +int monitor_read_password(MonitorHMP *mon, ReadLineFunc *readline_func, void *opaque) { if (mon->rs) { @@ -344,7 +348,8 @@ int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func, /* prompt is printed on return from the command handler */ return 0; } else { - monitor_printf(mon, "terminal does not support password prompting\n"); + monitor_printf(&mon->common, + "terminal does not support password prompting\n"); return -ENOTTY; } } @@ -705,7 +710,7 @@ static void monitor_qapi_event_init(void) qapi_event_throttle_equal); } -static void handle_hmp_command(Monitor *mon, const char *cmdline); +static void handle_hmp_command(MonitorHMP *mon, const char *cmdline); static void monitor_iothread_init(void); @@ -738,8 +743,9 @@ static void monitor_data_destroy(Monitor *mon) qemu_chr_fe_deinit(&mon->chr, false); if (monitor_is_qmp(mon)) { monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common)); + } else { + readline_free(container_of(mon, MonitorHMP, common)->rs); } - readline_free(mon->rs); qobject_unref(mon->outbuf); qemu_mutex_destroy(&mon->mon_lock); } @@ -749,12 +755,12 @@ char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index, { char *output = NULL; Monitor *old_mon; - Monitor hmp = {}; + MonitorHMP hmp = {}; - monitor_data_init(&hmp, 0, true, false); + monitor_data_init(&hmp.common, 0, true, false); old_mon = cur_mon; - cur_mon = &hmp; + cur_mon = &hmp.common; if (has_cpu_index) { int ret = monitor_set_cpu(cpu_index); @@ -769,16 +775,16 @@ char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index, handle_hmp_command(&hmp, command_line); cur_mon = old_mon; - qemu_mutex_lock(&hmp.mon_lock); - if (qstring_get_length(hmp.outbuf) > 0) { - output = g_strdup(qstring_get_str(hmp.outbuf)); + qemu_mutex_lock(&hmp.common.mon_lock); + if (qstring_get_length(hmp.common.outbuf) > 0) { + output = g_strdup(qstring_get_str(hmp.common.outbuf)); } else { output = g_strdup(""); } - qemu_mutex_unlock(&hmp.mon_lock); + qemu_mutex_unlock(&hmp.common.mon_lock); out: - monitor_data_destroy(&hmp); + monitor_data_destroy(&hmp.common); return output; } @@ -1348,16 +1354,19 @@ static void hmp_info_sync_profile(Monitor *mon, const QDict *qdict) static void hmp_info_history(Monitor *mon, const QDict *qdict) { + MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common); int i; const char *str; - if (!mon->rs) + if (!hmp_mon->rs) { return; + } i = 0; for(;;) { - str = readline_get_history(mon->rs, i); - if (!str) + str = readline_get_history(hmp_mon->rs, i); + if (!str) { break; + } monitor_printf(mon, "%d: '%s'\n", i, str); i++; } @@ -3055,11 +3064,12 @@ static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table, * Do not assume the return value points into @table! It doesn't when * the command is found in a sub-command table. */ -static const mon_cmd_t *monitor_parse_command(Monitor *mon, +static const mon_cmd_t *monitor_parse_command(MonitorHMP *hmp_mon, const char *cmdp_start, const char **cmdp, mon_cmd_t *table) { + Monitor *mon = &hmp_mon->common; const char *p; const mon_cmd_t *cmd; char cmdname[256]; @@ -3090,7 +3100,7 @@ static const mon_cmd_t *monitor_parse_command(Monitor *mon, *cmdp = p; /* search sub command */ if (cmd->sub_table != NULL && *p != '\0') { - return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table); + return monitor_parse_command(hmp_mon, cmdp_start, cmdp, cmd->sub_table); } return cmd; @@ -3467,7 +3477,7 @@ fail: return NULL; } -static void handle_hmp_command(Monitor *mon, const char *cmdline) +static void handle_hmp_command(MonitorHMP *mon, const char *cmdline) { QDict *qdict; const mon_cmd_t *cmd; @@ -3475,26 +3485,26 @@ static void handle_hmp_command(Monitor *mon, const char *cmdline) trace_handle_hmp_command(mon, cmdline); - cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table); + cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->common.cmd_table); if (!cmd) { return; } - qdict = monitor_parse_arguments(mon, &cmdline, cmd); + qdict = monitor_parse_arguments(&mon->common, &cmdline, cmd); if (!qdict) { while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) { cmdline--; } - monitor_printf(mon, "Try \"help %.*s\" for more information\n", + monitor_printf(&mon->common, "Try \"help %.*s\" for more information\n", (int)(cmdline - cmd_start), cmd_start); return; } - cmd->cmd(mon, qdict); + cmd->cmd(&mon->common, qdict); qobject_unref(qdict); } -static void cmd_completion(Monitor *mon, const char *name, const char *list) +static void cmd_completion(MonitorHMP *mon, const char *name, const char *list) { const char *p, *pstart; char cmd[128]; @@ -3518,7 +3528,7 @@ static void cmd_completion(Monitor *mon, const char *name, const char *list) } } -static void file_completion(Monitor *mon, const char *input) +static void file_completion(MonitorHMP *mon, const char *input) { DIR *ffs; struct dirent *d; @@ -4007,7 +4017,7 @@ void loadvm_completion(ReadLineState *rs, int nb_args, const char *str) } } -static void monitor_find_completion_by_table(Monitor *mon, +static void monitor_find_completion_by_table(MonitorHMP *mon, const mon_cmd_t *cmd_table, char **args, int nb_args) @@ -4102,7 +4112,7 @@ static void monitor_find_completion_by_table(Monitor *mon, static void monitor_find_completion(void *opaque, const char *cmdline) { - Monitor *mon = opaque; + MonitorHMP *mon = opaque; char *args[MAX_ARGS]; int nb_args, len; @@ -4122,7 +4132,7 @@ static void monitor_find_completion(void *opaque, } /* 2. auto complete according to args */ - monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args); + monitor_find_completion_by_table(mon, mon->common.cmd_table, args, nb_args); cleanup: free_cmdline_args(args, nb_args); @@ -4333,19 +4343,21 @@ static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size) static void monitor_read(void *opaque, const uint8_t *buf, int size) { + MonitorHMP *mon; Monitor *old_mon = cur_mon; int i; cur_mon = opaque; + mon = container_of(cur_mon, MonitorHMP, common); - if (cur_mon->rs) { + if (mon->rs) { for (i = 0; i < size; i++) - readline_handle_byte(cur_mon->rs, buf[i]); + readline_handle_byte(mon->rs, buf[i]); } else { if (size == 0 || buf[size - 1] != 0) monitor_printf(cur_mon, "corrupted command\n"); else - handle_hmp_command(cur_mon, (char *)buf); + handle_hmp_command(mon, (char *)buf); } cur_mon = old_mon; @@ -4354,11 +4366,11 @@ static void monitor_read(void *opaque, const uint8_t *buf, int size) static void monitor_command_cb(void *opaque, const char *cmdline, void *readline_opaque) { - Monitor *mon = opaque; + MonitorHMP *mon = opaque; - monitor_suspend(mon); + monitor_suspend(&mon->common); handle_hmp_command(mon, cmdline); - monitor_resume(mon); + monitor_resume(&mon->common); } int monitor_suspend(Monitor *mon) @@ -4404,8 +4416,9 @@ void monitor_resume(Monitor *mon) } if (!monitor_is_qmp(mon)) { - assert(mon->rs); - readline_show_prompt(mon->rs); + MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common); + assert(hmp_mon->rs); + readline_show_prompt(hmp_mon->rs); } aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon); @@ -4467,6 +4480,7 @@ static void monitor_qmp_event(void *opaque, int event) static void monitor_event(void *opaque, int event) { Monitor *mon = opaque; + MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common); switch (event) { case CHR_EVENT_MUX_IN: @@ -4474,7 +4488,7 @@ static void monitor_event(void *opaque, int event) mon->mux_out = 0; qemu_mutex_unlock(&mon->mon_lock); if (mon->reset_seen) { - readline_restart(mon->rs); + readline_restart(hmp_mon->rs); monitor_resume(mon); monitor_flush(mon); } else { @@ -4501,8 +4515,8 @@ static void monitor_event(void *opaque, int event) monitor_printf(mon, "QEMU %s monitor - type 'help' for more " "information\n", QEMU_VERSION); if (!mon->mux_out) { - readline_restart(mon->rs); - readline_show_prompt(mon->rs); + readline_restart(hmp_mon->rs); + readline_show_prompt(hmp_mon->rs); } mon->reset_seen = 1; mon_refcount++; @@ -4563,15 +4577,17 @@ void monitor_init_globals(void) static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque, const char *fmt, ...) { + MonitorHMP *mon = opaque; va_list ap; va_start(ap, fmt); - monitor_vprintf(opaque, fmt, ap); + monitor_vprintf(&mon->common, fmt, ap); va_end(ap); } static void monitor_readline_flush(void *opaque) { - monitor_flush(opaque); + MonitorHMP *mon = opaque; + monitor_flush(&mon->common); } /* @@ -4672,11 +4688,11 @@ static void monitor_init_qmp(Chardev *chr, int flags) static void monitor_init_hmp(Chardev *chr, int flags) { - Monitor *mon = g_new0(Monitor, 1); + MonitorHMP *mon = g_new0(MonitorHMP, 1); bool use_readline = flags & MONITOR_USE_READLINE; - monitor_data_init(mon, flags, false, false); - qemu_chr_fe_init(&mon->chr, chr, &error_abort); + monitor_data_init(&mon->common, flags, false, false); + qemu_chr_fe_init(&mon->common.chr, chr, &error_abort); if (use_readline) { mon->rs = readline_init(monitor_readline_printf, @@ -4686,9 +4702,9 @@ static void monitor_init_hmp(Chardev *chr, int flags) monitor_read_command(mon, 0); } - qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read, - monitor_event, NULL, mon, NULL, true); - monitor_list_append(mon); + qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read, monitor_read, + monitor_event, NULL, &mon->common, NULL, true); + monitor_list_append(&mon->common); } void monitor_init(Chardev *chr, int flags) -- cgit v1.2.3-55-g7522 From 1d95db745b78439e9eec0782eca9cc0d679d6224 Mon Sep 17 00:00:00 2001 From: Kevin Wolf Date: Thu, 13 Jun 2019 17:34:02 +0200 Subject: monitor: Split out monitor/monitor.c Move the monitor core infrastructure from monitor/misc.c to monitor/monitor.c. This is code that can be shared for all targets, so compile it only once. What remains in monitor/misc.c after this patch is mostly monitor command implementations (which could move to hmp-cmds.c or qmp-cmds.c later) and code that requires a system emulator or is even target-dependent (including HMP command completion code). The amount of function and particularly extern variables in monitor_int.h is probably a bit larger than it needs to be, but this way no non-trivial code modifications are needed. The interfaces between all monitor parts can be cleaned up later. Signed-off-by: Kevin Wolf Message-Id: <20190613153405.24769-13-kwolf@redhat.com> Reviewed-by: Markus Armbruster [Superfluous #include dropped] Signed-off-by: Markus Armbruster --- MAINTAINERS | 2 + include/monitor/monitor.h | 1 + monitor/Makefile.objs | 2 +- monitor/misc.c | 598 +----------------------------------------- monitor/monitor-internal.h | 1 + monitor/monitor.c | 633 +++++++++++++++++++++++++++++++++++++++++++++ monitor/trace-events | 2 +- 7 files changed, 640 insertions(+), 599 deletions(-) create mode 100644 monitor/monitor.c (limited to 'include') diff --git a/MAINTAINERS b/MAINTAINERS index 15f21c35e0..d32c5c2313 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1920,6 +1920,7 @@ M: Dr. David Alan Gilbert S: Maintained F: monitor/monitor-internal.h F: monitor/misc.c +F: monitor/monitor.c F: monitor/hmp* F: hmp.h F: hmp-commands*.hx @@ -2044,6 +2045,7 @@ S: Supported F: monitor/monitor-internal.h F: monitor/qmp* F: monitor/misc.c +F: monitor/monitor.c F: docs/devel/*qmp-* F: docs/interop/*qmp-* F: scripts/qmp/ diff --git a/include/monitor/monitor.h b/include/monitor/monitor.h index f9d30e1d78..44ac43df34 100644 --- a/include/monitor/monitor.h +++ b/include/monitor/monitor.h @@ -19,6 +19,7 @@ typedef struct MonitorHMP MonitorHMP; bool monitor_cur_is_qmp(void); void monitor_init_globals(void); +void monitor_init_globals_core(void); void monitor_init(Chardev *chr, int flags); void monitor_cleanup(void); diff --git a/monitor/Makefile.objs b/monitor/Makefile.objs index bea8838acc..e91a8581cd 100644 --- a/monitor/Makefile.objs +++ b/monitor/Makefile.objs @@ -1,3 +1,3 @@ obj-y += misc.o -common-obj-y += qmp.o hmp.o +common-obj-y += monitor.o qmp.o hmp.o common-obj-y += qmp-cmds.o hmp-cmds.o diff --git a/monitor/misc.c b/monitor/misc.c index e4d656f002..6e3d580ae7 100644 --- a/monitor/misc.c +++ b/monitor/misc.c @@ -54,7 +54,6 @@ #include "qapi/qmp/qerror.h" #include "qapi/qmp/qstring.h" #include "qom/object_interfaces.h" -#include "trace.h" #include "trace/control.h" #include "monitor/hmp-target.h" #ifdef CONFIG_TRACE_SIMPLE @@ -71,7 +70,6 @@ #include "qapi/error.h" #include "qapi/qmp-event.h" #include "qapi/qapi-introspect.h" -#include "sysemu/qtest.h" #include "sysemu/cpus.h" #include "qemu/cutils.h" #include "tcg/tcg.h" @@ -107,427 +105,15 @@ struct MonFdset { QLIST_ENTRY(MonFdset) next; }; -/* - * To prevent flooding clients, events can be throttled. The - * throttling is calculated globally, rather than per-Monitor - * instance. - */ -typedef struct MonitorQAPIEventState { - QAPIEvent event; /* Throttling state for this event type and... */ - QDict *data; /* ... data, see qapi_event_throttle_equal() */ - QEMUTimer *timer; /* Timer for handling delayed events */ - QDict *qdict; /* Delayed event (if any) */ -} MonitorQAPIEventState; - -typedef struct { - int64_t rate; /* Minimum time (in ns) between two events */ -} MonitorQAPIEventConf; - -/* Shared monitor I/O thread */ -IOThread *mon_iothread; - -/* Bottom half to dispatch the requests received from I/O thread */ -QEMUBH *qmp_dispatcher_bh; - /* QMP checker flags */ #define QMP_ACCEPT_UNKNOWNS 1 -/* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */ -QemuMutex monitor_lock; -static GHashTable *monitor_qapi_event_state; -MonitorList mon_list; -static bool monitor_destroyed; - /* Protects mon_fdsets */ static QemuMutex mon_fdsets_lock; static QLIST_HEAD(, MonFdset) mon_fdsets; -int mon_refcount; - static HMPCommand hmp_info_cmds[]; -__thread Monitor *cur_mon; - -/** - * Is @mon is using readline? - * Note: not all HMP monitors use readline, e.g., gdbserver has a - * non-interactive HMP monitor, so readline is not used there. - */ -static inline bool monitor_uses_readline(const Monitor *mon) -{ - return mon->flags & MONITOR_USE_READLINE; -} - -static inline bool monitor_is_hmp_non_interactive(const Monitor *mon) -{ - return !monitor_is_qmp(mon) && !monitor_uses_readline(mon); -} - -/* - * Return the clock to use for recording an event's time. - * It's QEMU_CLOCK_REALTIME, except for qtests it's - * QEMU_CLOCK_VIRTUAL, to support testing rate limits. - * Beware: result is invalid before configure_accelerator(). - */ -static inline QEMUClockType monitor_get_event_clock(void) -{ - return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME; -} - -/** - * Is the current monitor, if any, a QMP monitor? - */ -bool monitor_cur_is_qmp(void) -{ - return cur_mon && monitor_is_qmp(cur_mon); -} - -static void monitor_flush_locked(Monitor *mon); - -static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond, - void *opaque) -{ - Monitor *mon = opaque; - - qemu_mutex_lock(&mon->mon_lock); - mon->out_watch = 0; - monitor_flush_locked(mon); - qemu_mutex_unlock(&mon->mon_lock); - return FALSE; -} - -/* Caller must hold mon->mon_lock */ -static void monitor_flush_locked(Monitor *mon) -{ - int rc; - size_t len; - const char *buf; - - if (mon->skip_flush) { - return; - } - - buf = qstring_get_str(mon->outbuf); - len = qstring_get_length(mon->outbuf); - - if (len && !mon->mux_out) { - rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len); - if ((rc < 0 && errno != EAGAIN) || (rc == len)) { - /* all flushed or error */ - qobject_unref(mon->outbuf); - mon->outbuf = qstring_new(); - return; - } - if (rc > 0) { - /* partial write */ - QString *tmp = qstring_from_str(buf + rc); - qobject_unref(mon->outbuf); - mon->outbuf = tmp; - } - if (mon->out_watch == 0) { - mon->out_watch = - qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP, - monitor_unblocked, mon); - } - } -} - -void monitor_flush(Monitor *mon) -{ - qemu_mutex_lock(&mon->mon_lock); - monitor_flush_locked(mon); - qemu_mutex_unlock(&mon->mon_lock); -} - -/* flush at every end of line */ -int monitor_puts(Monitor *mon, const char *str) -{ - int i; - char c; - - qemu_mutex_lock(&mon->mon_lock); - for (i = 0; str[i]; i++) { - c = str[i]; - if (c == '\n') { - qstring_append_chr(mon->outbuf, '\r'); - } - qstring_append_chr(mon->outbuf, c); - if (c == '\n') { - monitor_flush_locked(mon); - } - } - qemu_mutex_unlock(&mon->mon_lock); - - return i; -} - -int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap) -{ - char *buf; - int n; - - if (!mon) - return -1; - - if (monitor_is_qmp(mon)) { - return -1; - } - - buf = g_strdup_vprintf(fmt, ap); - n = monitor_puts(mon, buf); - g_free(buf); - return n; -} - -int monitor_printf(Monitor *mon, const char *fmt, ...) -{ - int ret; - - va_list ap; - va_start(ap, fmt); - ret = monitor_vprintf(mon, fmt, ap); - va_end(ap); - return ret; -} - -static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = { - /* Limit guest-triggerable events to 1 per second */ - [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS }, - [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS }, - [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS }, - [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS }, - [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS }, - [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS }, -}; - -/* - * Broadcast an event to all monitors. - * @qdict is the event object. Its member "event" must match @event. - * Caller must hold monitor_lock. - */ -static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict) -{ - Monitor *mon; - MonitorQMP *qmp_mon; - - trace_monitor_protocol_event_emit(event, qdict); - QTAILQ_FOREACH(mon, &mon_list, entry) { - if (!monitor_is_qmp(mon)) { - continue; - } - - qmp_mon = container_of(mon, MonitorQMP, common); - if (qmp_mon->commands != &qmp_cap_negotiation_commands) { - qmp_send_response(qmp_mon, qdict); - } - } -} - -static void monitor_qapi_event_handler(void *opaque); - -/* - * Queue a new event for emission to Monitor instances, - * applying any rate limiting if required. - */ -static void -monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict) -{ - MonitorQAPIEventConf *evconf; - MonitorQAPIEventState *evstate; - - assert(event < QAPI_EVENT__MAX); - evconf = &monitor_qapi_event_conf[event]; - trace_monitor_protocol_event_queue(event, qdict, evconf->rate); - - qemu_mutex_lock(&monitor_lock); - - if (!evconf->rate) { - /* Unthrottled event */ - monitor_qapi_event_emit(event, qdict); - } else { - QDict *data = qobject_to(QDict, qdict_get(qdict, "data")); - MonitorQAPIEventState key = { .event = event, .data = data }; - - evstate = g_hash_table_lookup(monitor_qapi_event_state, &key); - assert(!evstate || timer_pending(evstate->timer)); - - if (evstate) { - /* - * Timer is pending for (at least) evconf->rate ns after - * last send. Store event for sending when timer fires, - * replacing a prior stored event if any. - */ - qobject_unref(evstate->qdict); - evstate->qdict = qobject_ref(qdict); - } else { - /* - * Last send was (at least) evconf->rate ns ago. - * Send immediately, and arm the timer to call - * monitor_qapi_event_handler() in evconf->rate ns. Any - * events arriving before then will be delayed until then. - */ - int64_t now = qemu_clock_get_ns(monitor_get_event_clock()); - - monitor_qapi_event_emit(event, qdict); - - evstate = g_new(MonitorQAPIEventState, 1); - evstate->event = event; - evstate->data = qobject_ref(data); - evstate->qdict = NULL; - evstate->timer = timer_new_ns(monitor_get_event_clock(), - monitor_qapi_event_handler, - evstate); - g_hash_table_add(monitor_qapi_event_state, evstate); - timer_mod_ns(evstate->timer, now + evconf->rate); - } - } - - qemu_mutex_unlock(&monitor_lock); -} - -void qapi_event_emit(QAPIEvent event, QDict *qdict) -{ - /* - * monitor_qapi_event_queue_no_reenter() is not reentrant: it - * would deadlock on monitor_lock. Work around by queueing - * events in thread-local storage. - * TODO: remove this, make it re-enter safe. - */ - typedef struct MonitorQapiEvent { - QAPIEvent event; - QDict *qdict; - QSIMPLEQ_ENTRY(MonitorQapiEvent) entry; - } MonitorQapiEvent; - static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue; - static __thread bool reentered; - MonitorQapiEvent *ev; - - if (!reentered) { - QSIMPLEQ_INIT(&event_queue); - } - - ev = g_new(MonitorQapiEvent, 1); - ev->qdict = qobject_ref(qdict); - ev->event = event; - QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry); - if (reentered) { - return; - } - - reentered = true; - - while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) { - QSIMPLEQ_REMOVE_HEAD(&event_queue, entry); - monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict); - qobject_unref(ev->qdict); - g_free(ev); - } - - reentered = false; -} - -/* - * This function runs evconf->rate ns after sending a throttled - * event. - * If another event has since been stored, send it. - */ -static void monitor_qapi_event_handler(void *opaque) -{ - MonitorQAPIEventState *evstate = opaque; - MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event]; - - trace_monitor_protocol_event_handler(evstate->event, evstate->qdict); - qemu_mutex_lock(&monitor_lock); - - if (evstate->qdict) { - int64_t now = qemu_clock_get_ns(monitor_get_event_clock()); - - monitor_qapi_event_emit(evstate->event, evstate->qdict); - qobject_unref(evstate->qdict); - evstate->qdict = NULL; - timer_mod_ns(evstate->timer, now + evconf->rate); - } else { - g_hash_table_remove(monitor_qapi_event_state, evstate); - qobject_unref(evstate->data); - timer_free(evstate->timer); - g_free(evstate); - } - - qemu_mutex_unlock(&monitor_lock); -} - -static unsigned int qapi_event_throttle_hash(const void *key) -{ - const MonitorQAPIEventState *evstate = key; - unsigned int hash = evstate->event * 255; - - if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) { - hash += g_str_hash(qdict_get_str(evstate->data, "id")); - } - - if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) { - hash += g_str_hash(qdict_get_str(evstate->data, "node-name")); - } - - return hash; -} - -static gboolean qapi_event_throttle_equal(const void *a, const void *b) -{ - const MonitorQAPIEventState *eva = a; - const MonitorQAPIEventState *evb = b; - - if (eva->event != evb->event) { - return FALSE; - } - - if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) { - return !strcmp(qdict_get_str(eva->data, "id"), - qdict_get_str(evb->data, "id")); - } - - if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) { - return !strcmp(qdict_get_str(eva->data, "node-name"), - qdict_get_str(evb->data, "node-name")); - } - - return TRUE; -} - -static void monitor_qapi_event_init(void) -{ - monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash, - qapi_event_throttle_equal); -} - -static void monitor_iothread_init(void); - -void monitor_data_init(Monitor *mon, int flags, bool skip_flush, - bool use_io_thread) -{ - if (use_io_thread && !mon_iothread) { - monitor_iothread_init(); - } - qemu_mutex_init(&mon->mon_lock); - mon->outbuf = qstring_new(); - mon->skip_flush = skip_flush; - mon->use_io_thread = use_io_thread; - mon->flags = flags; -} - -static void monitor_data_destroy(Monitor *mon) -{ - g_free(mon->mon_cpu_path); - qemu_chr_fe_deinit(&mon->chr, false); - if (monitor_is_qmp(mon)) { - monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common)); - } else { - readline_free(container_of(mon, MonitorHMP, common)->rs); - } - qobject_unref(mon->outbuf); - qemu_mutex_destroy(&mon->mon_lock); -} - char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index, int64_t cpu_index, Error **errp) { @@ -2728,67 +2314,6 @@ void loadvm_completion(ReadLineState *rs, int nb_args, const char *str) } } -int monitor_can_read(void *opaque) -{ - Monitor *mon = opaque; - - return !atomic_mb_read(&mon->suspend_cnt); -} - -int monitor_suspend(Monitor *mon) -{ - if (monitor_is_hmp_non_interactive(mon)) { - return -ENOTTY; - } - - atomic_inc(&mon->suspend_cnt); - - if (mon->use_io_thread) { - /* - * Kick I/O thread to make sure this takes effect. It'll be - * evaluated again in prepare() of the watch object. - */ - aio_notify(iothread_get_aio_context(mon_iothread)); - } - - trace_monitor_suspend(mon, 1); - return 0; -} - -static void monitor_accept_input(void *opaque) -{ - Monitor *mon = opaque; - - qemu_chr_fe_accept_input(&mon->chr); -} - -void monitor_resume(Monitor *mon) -{ - if (monitor_is_hmp_non_interactive(mon)) { - return; - } - - if (atomic_dec_fetch(&mon->suspend_cnt) == 0) { - AioContext *ctx; - - if (mon->use_io_thread) { - ctx = iothread_get_aio_context(mon_iothread); - } else { - ctx = qemu_get_aio_context(); - } - - if (!monitor_is_qmp(mon)) { - MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common); - assert(hmp_mon->rs); - readline_show_prompt(hmp_mon->rs); - } - - aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon); - } - - trace_monitor_suspend(mon, -1); -} - static int compare_mon_cmd(const void *a, const void *b) { @@ -2806,135 +2331,14 @@ static void sortcmdlist(void) compare_mon_cmd); } -static void monitor_iothread_init(void) -{ - mon_iothread = iothread_create("mon_iothread", &error_abort); -} - void monitor_init_globals(void) { + monitor_init_globals_core(); monitor_init_qmp_commands(); - monitor_qapi_event_init(); sortcmdlist(); - qemu_mutex_init(&monitor_lock); qemu_mutex_init(&mon_fdsets_lock); - - /* - * The dispatcher BH must run in the main loop thread, since we - * have commands assuming that context. It would be nice to get - * rid of those assumptions. - */ - qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(), - monitor_qmp_bh_dispatcher, - NULL); -} - -/* - * Print to current monitor if we have one, else to stderr. - */ -int error_vprintf(const char *fmt, va_list ap) -{ - if (cur_mon && !monitor_cur_is_qmp()) { - return monitor_vprintf(cur_mon, fmt, ap); - } - return vfprintf(stderr, fmt, ap); -} - -int error_vprintf_unless_qmp(const char *fmt, va_list ap) -{ - if (!cur_mon) { - return vfprintf(stderr, fmt, ap); - } - if (!monitor_cur_is_qmp()) { - return monitor_vprintf(cur_mon, fmt, ap); - } - return -1; -} - -void monitor_list_append(Monitor *mon) -{ - qemu_mutex_lock(&monitor_lock); - /* - * This prevents inserting new monitors during monitor_cleanup(). - * A cleaner solution would involve the main thread telling other - * threads to terminate, waiting for their termination. - */ - if (!monitor_destroyed) { - QTAILQ_INSERT_HEAD(&mon_list, mon, entry); - mon = NULL; - } - qemu_mutex_unlock(&monitor_lock); - - if (mon) { - monitor_data_destroy(mon); - g_free(mon); - } -} - -void monitor_init(Chardev *chr, int flags) -{ - if (flags & MONITOR_USE_CONTROL) { - monitor_init_qmp(chr, flags); - } else { - monitor_init_hmp(chr, flags); - } } -void monitor_cleanup(void) -{ - /* - * We need to explicitly stop the I/O thread (but not destroy it), - * clean up the monitor resources, then destroy the I/O thread since - * we need to unregister from chardev below in - * monitor_data_destroy(), and chardev is not thread-safe yet - */ - if (mon_iothread) { - iothread_stop(mon_iothread); - } - - /* Flush output buffers and destroy monitors */ - qemu_mutex_lock(&monitor_lock); - monitor_destroyed = true; - while (!QTAILQ_EMPTY(&mon_list)) { - Monitor *mon = QTAILQ_FIRST(&mon_list); - QTAILQ_REMOVE(&mon_list, mon, entry); - /* Permit QAPI event emission from character frontend release */ - qemu_mutex_unlock(&monitor_lock); - monitor_flush(mon); - monitor_data_destroy(mon); - qemu_mutex_lock(&monitor_lock); - g_free(mon); - } - qemu_mutex_unlock(&monitor_lock); - - /* QEMUBHs needs to be deleted before destroying the I/O thread */ - qemu_bh_delete(qmp_dispatcher_bh); - qmp_dispatcher_bh = NULL; - if (mon_iothread) { - iothread_destroy(mon_iothread); - mon_iothread = NULL; - } -} - -QemuOptsList qemu_mon_opts = { - .name = "mon", - .implied_opt_name = "chardev", - .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head), - .desc = { - { - .name = "mode", - .type = QEMU_OPT_STRING, - },{ - .name = "chardev", - .type = QEMU_OPT_STRING, - },{ - .name = "pretty", - .type = QEMU_OPT_BOOL, - }, - { /* end of list */ } - }, -}; - HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp) { MachineState *ms = MACHINE(qdev_get_machine()); diff --git a/monitor/monitor-internal.h b/monitor/monitor-internal.h index 10fda7d97c..b4996c14ac 100644 --- a/monitor/monitor-internal.h +++ b/monitor/monitor-internal.h @@ -167,6 +167,7 @@ void monitor_init_hmp(Chardev *chr, int flags); int monitor_puts(Monitor *mon, const char *str); void monitor_data_init(Monitor *mon, int flags, bool skip_flush, bool use_io_thread); +void monitor_data_destroy(Monitor *mon); int monitor_can_read(void *opaque); void monitor_list_append(Monitor *mon); void monitor_fdsets_cleanup(void); diff --git a/monitor/monitor.c b/monitor/monitor.c new file mode 100644 index 0000000000..db3d5ece99 --- /dev/null +++ b/monitor/monitor.c @@ -0,0 +1,633 @@ +/* + * QEMU monitor + * + * Copyright (c) 2003-2004 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "qemu/osdep.h" +#include "monitor-internal.h" +#include "qapi/error.h" +#include "qapi/qapi-emit-events.h" +#include "qapi/qmp/qdict.h" +#include "qapi/qmp/qstring.h" +#include "qemu/error-report.h" +#include "qemu/option.h" +#include "sysemu/qtest.h" +#include "trace.h" + +/* + * To prevent flooding clients, events can be throttled. The + * throttling is calculated globally, rather than per-Monitor + * instance. + */ +typedef struct MonitorQAPIEventState { + QAPIEvent event; /* Throttling state for this event type and... */ + QDict *data; /* ... data, see qapi_event_throttle_equal() */ + QEMUTimer *timer; /* Timer for handling delayed events */ + QDict *qdict; /* Delayed event (if any) */ +} MonitorQAPIEventState; + +typedef struct { + int64_t rate; /* Minimum time (in ns) between two events */ +} MonitorQAPIEventConf; + +/* Shared monitor I/O thread */ +IOThread *mon_iothread; + +/* Bottom half to dispatch the requests received from I/O thread */ +QEMUBH *qmp_dispatcher_bh; + +/* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */ +QemuMutex monitor_lock; +static GHashTable *monitor_qapi_event_state; + +MonitorList mon_list; +int mon_refcount; +static bool monitor_destroyed; + +__thread Monitor *cur_mon; + +/** + * Is the current monitor, if any, a QMP monitor? + */ +bool monitor_cur_is_qmp(void) +{ + return cur_mon && monitor_is_qmp(cur_mon); +} + +/** + * Is @mon is using readline? + * Note: not all HMP monitors use readline, e.g., gdbserver has a + * non-interactive HMP monitor, so readline is not used there. + */ +static inline bool monitor_uses_readline(const Monitor *mon) +{ + return mon->flags & MONITOR_USE_READLINE; +} + +static inline bool monitor_is_hmp_non_interactive(const Monitor *mon) +{ + return !monitor_is_qmp(mon) && !monitor_uses_readline(mon); +} + +static void monitor_flush_locked(Monitor *mon); + +static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond, + void *opaque) +{ + Monitor *mon = opaque; + + qemu_mutex_lock(&mon->mon_lock); + mon->out_watch = 0; + monitor_flush_locked(mon); + qemu_mutex_unlock(&mon->mon_lock); + return FALSE; +} + +/* Caller must hold mon->mon_lock */ +static void monitor_flush_locked(Monitor *mon) +{ + int rc; + size_t len; + const char *buf; + + if (mon->skip_flush) { + return; + } + + buf = qstring_get_str(mon->outbuf); + len = qstring_get_length(mon->outbuf); + + if (len && !mon->mux_out) { + rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len); + if ((rc < 0 && errno != EAGAIN) || (rc == len)) { + /* all flushed or error */ + qobject_unref(mon->outbuf); + mon->outbuf = qstring_new(); + return; + } + if (rc > 0) { + /* partial write */ + QString *tmp = qstring_from_str(buf + rc); + qobject_unref(mon->outbuf); + mon->outbuf = tmp; + } + if (mon->out_watch == 0) { + mon->out_watch = + qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP, + monitor_unblocked, mon); + } + } +} + +void monitor_flush(Monitor *mon) +{ + qemu_mutex_lock(&mon->mon_lock); + monitor_flush_locked(mon); + qemu_mutex_unlock(&mon->mon_lock); +} + +/* flush at every end of line */ +int monitor_puts(Monitor *mon, const char *str) +{ + int i; + char c; + + qemu_mutex_lock(&mon->mon_lock); + for (i = 0; str[i]; i++) { + c = str[i]; + if (c == '\n') { + qstring_append_chr(mon->outbuf, '\r'); + } + qstring_append_chr(mon->outbuf, c); + if (c == '\n') { + monitor_flush_locked(mon); + } + } + qemu_mutex_unlock(&mon->mon_lock); + + return i; +} + +int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap) +{ + char *buf; + int n; + + if (!mon) { + return -1; + } + + if (monitor_is_qmp(mon)) { + return -1; + } + + buf = g_strdup_vprintf(fmt, ap); + n = monitor_puts(mon, buf); + g_free(buf); + return n; +} + +int monitor_printf(Monitor *mon, const char *fmt, ...) +{ + int ret; + + va_list ap; + va_start(ap, fmt); + ret = monitor_vprintf(mon, fmt, ap); + va_end(ap); + return ret; +} + +/* + * Print to current monitor if we have one, else to stderr. + */ +int error_vprintf(const char *fmt, va_list ap) +{ + if (cur_mon && !monitor_cur_is_qmp()) { + return monitor_vprintf(cur_mon, fmt, ap); + } + return vfprintf(stderr, fmt, ap); +} + +int error_vprintf_unless_qmp(const char *fmt, va_list ap) +{ + if (!cur_mon) { + return vfprintf(stderr, fmt, ap); + } + if (!monitor_cur_is_qmp()) { + return monitor_vprintf(cur_mon, fmt, ap); + } + return -1; +} + + +static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = { + /* Limit guest-triggerable events to 1 per second */ + [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS }, + [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS }, + [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS }, + [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS }, + [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS }, + [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS }, +}; + +/* + * Return the clock to use for recording an event's time. + * It's QEMU_CLOCK_REALTIME, except for qtests it's + * QEMU_CLOCK_VIRTUAL, to support testing rate limits. + * Beware: result is invalid before configure_accelerator(). + */ +static inline QEMUClockType monitor_get_event_clock(void) +{ + return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME; +} + +/* + * Broadcast an event to all monitors. + * @qdict is the event object. Its member "event" must match @event. + * Caller must hold monitor_lock. + */ +static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict) +{ + Monitor *mon; + MonitorQMP *qmp_mon; + + trace_monitor_protocol_event_emit(event, qdict); + QTAILQ_FOREACH(mon, &mon_list, entry) { + if (!monitor_is_qmp(mon)) { + continue; + } + + qmp_mon = container_of(mon, MonitorQMP, common); + if (qmp_mon->commands != &qmp_cap_negotiation_commands) { + qmp_send_response(qmp_mon, qdict); + } + } +} + +static void monitor_qapi_event_handler(void *opaque); + +/* + * Queue a new event for emission to Monitor instances, + * applying any rate limiting if required. + */ +static void +monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict) +{ + MonitorQAPIEventConf *evconf; + MonitorQAPIEventState *evstate; + + assert(event < QAPI_EVENT__MAX); + evconf = &monitor_qapi_event_conf[event]; + trace_monitor_protocol_event_queue(event, qdict, evconf->rate); + + qemu_mutex_lock(&monitor_lock); + + if (!evconf->rate) { + /* Unthrottled event */ + monitor_qapi_event_emit(event, qdict); + } else { + QDict *data = qobject_to(QDict, qdict_get(qdict, "data")); + MonitorQAPIEventState key = { .event = event, .data = data }; + + evstate = g_hash_table_lookup(monitor_qapi_event_state, &key); + assert(!evstate || timer_pending(evstate->timer)); + + if (evstate) { + /* + * Timer is pending for (at least) evconf->rate ns after + * last send. Store event for sending when timer fires, + * replacing a prior stored event if any. + */ + qobject_unref(evstate->qdict); + evstate->qdict = qobject_ref(qdict); + } else { + /* + * Last send was (at least) evconf->rate ns ago. + * Send immediately, and arm the timer to call + * monitor_qapi_event_handler() in evconf->rate ns. Any + * events arriving before then will be delayed until then. + */ + int64_t now = qemu_clock_get_ns(monitor_get_event_clock()); + + monitor_qapi_event_emit(event, qdict); + + evstate = g_new(MonitorQAPIEventState, 1); + evstate->event = event; + evstate->data = qobject_ref(data); + evstate->qdict = NULL; + evstate->timer = timer_new_ns(monitor_get_event_clock(), + monitor_qapi_event_handler, + evstate); + g_hash_table_add(monitor_qapi_event_state, evstate); + timer_mod_ns(evstate->timer, now + evconf->rate); + } + } + + qemu_mutex_unlock(&monitor_lock); +} + +void qapi_event_emit(QAPIEvent event, QDict *qdict) +{ + /* + * monitor_qapi_event_queue_no_reenter() is not reentrant: it + * would deadlock on monitor_lock. Work around by queueing + * events in thread-local storage. + * TODO: remove this, make it re-enter safe. + */ + typedef struct MonitorQapiEvent { + QAPIEvent event; + QDict *qdict; + QSIMPLEQ_ENTRY(MonitorQapiEvent) entry; + } MonitorQapiEvent; + static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue; + static __thread bool reentered; + MonitorQapiEvent *ev; + + if (!reentered) { + QSIMPLEQ_INIT(&event_queue); + } + + ev = g_new(MonitorQapiEvent, 1); + ev->qdict = qobject_ref(qdict); + ev->event = event; + QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry); + if (reentered) { + return; + } + + reentered = true; + + while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) { + QSIMPLEQ_REMOVE_HEAD(&event_queue, entry); + monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict); + qobject_unref(ev->qdict); + g_free(ev); + } + + reentered = false; +} + +/* + * This function runs evconf->rate ns after sending a throttled + * event. + * If another event has since been stored, send it. + */ +static void monitor_qapi_event_handler(void *opaque) +{ + MonitorQAPIEventState *evstate = opaque; + MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event]; + + trace_monitor_protocol_event_handler(evstate->event, evstate->qdict); + qemu_mutex_lock(&monitor_lock); + + if (evstate->qdict) { + int64_t now = qemu_clock_get_ns(monitor_get_event_clock()); + + monitor_qapi_event_emit(evstate->event, evstate->qdict); + qobject_unref(evstate->qdict); + evstate->qdict = NULL; + timer_mod_ns(evstate->timer, now + evconf->rate); + } else { + g_hash_table_remove(monitor_qapi_event_state, evstate); + qobject_unref(evstate->data); + timer_free(evstate->timer); + g_free(evstate); + } + + qemu_mutex_unlock(&monitor_lock); +} + +static unsigned int qapi_event_throttle_hash(const void *key) +{ + const MonitorQAPIEventState *evstate = key; + unsigned int hash = evstate->event * 255; + + if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) { + hash += g_str_hash(qdict_get_str(evstate->data, "id")); + } + + if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) { + hash += g_str_hash(qdict_get_str(evstate->data, "node-name")); + } + + return hash; +} + +static gboolean qapi_event_throttle_equal(const void *a, const void *b) +{ + const MonitorQAPIEventState *eva = a; + const MonitorQAPIEventState *evb = b; + + if (eva->event != evb->event) { + return FALSE; + } + + if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) { + return !strcmp(qdict_get_str(eva->data, "id"), + qdict_get_str(evb->data, "id")); + } + + if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) { + return !strcmp(qdict_get_str(eva->data, "node-name"), + qdict_get_str(evb->data, "node-name")); + } + + return TRUE; +} + +int monitor_suspend(Monitor *mon) +{ + if (monitor_is_hmp_non_interactive(mon)) { + return -ENOTTY; + } + + atomic_inc(&mon->suspend_cnt); + + if (mon->use_io_thread) { + /* + * Kick I/O thread to make sure this takes effect. It'll be + * evaluated again in prepare() of the watch object. + */ + aio_notify(iothread_get_aio_context(mon_iothread)); + } + + trace_monitor_suspend(mon, 1); + return 0; +} + +static void monitor_accept_input(void *opaque) +{ + Monitor *mon = opaque; + + qemu_chr_fe_accept_input(&mon->chr); +} + +void monitor_resume(Monitor *mon) +{ + if (monitor_is_hmp_non_interactive(mon)) { + return; + } + + if (atomic_dec_fetch(&mon->suspend_cnt) == 0) { + AioContext *ctx; + + if (mon->use_io_thread) { + ctx = iothread_get_aio_context(mon_iothread); + } else { + ctx = qemu_get_aio_context(); + } + + if (!monitor_is_qmp(mon)) { + MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common); + assert(hmp_mon->rs); + readline_show_prompt(hmp_mon->rs); + } + + aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon); + } + + trace_monitor_suspend(mon, -1); +} + +int monitor_can_read(void *opaque) +{ + Monitor *mon = opaque; + + return !atomic_mb_read(&mon->suspend_cnt); +} + +void monitor_list_append(Monitor *mon) +{ + qemu_mutex_lock(&monitor_lock); + /* + * This prevents inserting new monitors during monitor_cleanup(). + * A cleaner solution would involve the main thread telling other + * threads to terminate, waiting for their termination. + */ + if (!monitor_destroyed) { + QTAILQ_INSERT_HEAD(&mon_list, mon, entry); + mon = NULL; + } + qemu_mutex_unlock(&monitor_lock); + + if (mon) { + monitor_data_destroy(mon); + g_free(mon); + } +} + +static void monitor_iothread_init(void) +{ + mon_iothread = iothread_create("mon_iothread", &error_abort); +} + +void monitor_data_init(Monitor *mon, int flags, bool skip_flush, + bool use_io_thread) +{ + if (use_io_thread && !mon_iothread) { + monitor_iothread_init(); + } + qemu_mutex_init(&mon->mon_lock); + mon->outbuf = qstring_new(); + mon->skip_flush = skip_flush; + mon->use_io_thread = use_io_thread; + mon->flags = flags; +} + +void monitor_data_destroy(Monitor *mon) +{ + g_free(mon->mon_cpu_path); + qemu_chr_fe_deinit(&mon->chr, false); + if (monitor_is_qmp(mon)) { + monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common)); + } else { + readline_free(container_of(mon, MonitorHMP, common)->rs); + } + qobject_unref(mon->outbuf); + qemu_mutex_destroy(&mon->mon_lock); +} + +void monitor_init(Chardev *chr, int flags) +{ + if (flags & MONITOR_USE_CONTROL) { + monitor_init_qmp(chr, flags); + } else { + monitor_init_hmp(chr, flags); + } +} + +void monitor_cleanup(void) +{ + /* + * We need to explicitly stop the I/O thread (but not destroy it), + * clean up the monitor resources, then destroy the I/O thread since + * we need to unregister from chardev below in + * monitor_data_destroy(), and chardev is not thread-safe yet + */ + if (mon_iothread) { + iothread_stop(mon_iothread); + } + + /* Flush output buffers and destroy monitors */ + qemu_mutex_lock(&monitor_lock); + monitor_destroyed = true; + while (!QTAILQ_EMPTY(&mon_list)) { + Monitor *mon = QTAILQ_FIRST(&mon_list); + QTAILQ_REMOVE(&mon_list, mon, entry); + /* Permit QAPI event emission from character frontend release */ + qemu_mutex_unlock(&monitor_lock); + monitor_flush(mon); + monitor_data_destroy(mon); + qemu_mutex_lock(&monitor_lock); + g_free(mon); + } + qemu_mutex_unlock(&monitor_lock); + + /* QEMUBHs needs to be deleted before destroying the I/O thread */ + qemu_bh_delete(qmp_dispatcher_bh); + qmp_dispatcher_bh = NULL; + if (mon_iothread) { + iothread_destroy(mon_iothread); + mon_iothread = NULL; + } +} + +static void monitor_qapi_event_init(void) +{ + monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash, + qapi_event_throttle_equal); +} + +void monitor_init_globals_core(void) +{ + monitor_qapi_event_init(); + qemu_mutex_init(&monitor_lock); + + /* + * The dispatcher BH must run in the main loop thread, since we + * have commands assuming that context. It would be nice to get + * rid of those assumptions. + */ + qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(), + monitor_qmp_bh_dispatcher, + NULL); +} + +QemuOptsList qemu_mon_opts = { + .name = "mon", + .implied_opt_name = "chardev", + .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head), + .desc = { + { + .name = "mode", + .type = QEMU_OPT_STRING, + },{ + .name = "chardev", + .type = QEMU_OPT_STRING, + },{ + .name = "pretty", + .type = QEMU_OPT_BOOL, + }, + { /* end of list */ } + }, +}; diff --git a/monitor/trace-events b/monitor/trace-events index 2285d26121..0365ac4d99 100644 --- a/monitor/trace-events +++ b/monitor/trace-events @@ -3,7 +3,7 @@ # hmp.c handle_hmp_command(void *mon, const char *cmdline) "mon %p cmdline: %s" -# misc.c +# monitor.c monitor_protocol_event_handler(uint32_t event, void *qdict) "event=%d data=%p" monitor_protocol_event_emit(uint32_t event, void *data) "event=%d data=%p" monitor_protocol_event_queue(uint32_t event, void *qdict, uint64_t rate) "event=%d data=%p rate=%" PRId64 -- cgit v1.2.3-55-g7522 From fbfc29e3bf145581e84c12ffc432ab56ce1dea0d Mon Sep 17 00:00:00 2001 From: Kevin Wolf Date: Thu, 13 Jun 2019 17:34:04 +0200 Subject: monitor: Replace monitor_init() with monitor_init_{hmp, qmp}() Most callers know which monitor type they want to have. Instead of calling monitor_init() with flags that can describe both types of monitors, make monitor_init_{hmp,qmp}() public interfaces that take specific bools instead of flags and call these functions directly. Signed-off-by: Kevin Wolf Message-Id: <20190613153405.24769-15-kwolf@redhat.com> Reviewed-by: Markus Armbruster Signed-off-by: Markus Armbruster --- chardev/char.c | 2 +- gdbstub.c | 2 +- include/monitor/monitor.h | 9 ++------- monitor/hmp.c | 4 ++-- monitor/monitor-internal.h | 3 --- monitor/monitor.c | 9 --------- monitor/qmp.c | 7 ++----- stubs/monitor.c | 6 +++++- tests/test-util-sockets.c | 3 ++- vl.c | 18 ++++++++++++------ 10 files changed, 27 insertions(+), 36 deletions(-) (limited to 'include') diff --git a/chardev/char.c b/chardev/char.c index e4887bcc82..7b6b2cb123 100644 --- a/chardev/char.c +++ b/chardev/char.c @@ -731,7 +731,7 @@ Chardev *qemu_chr_new_noreplay(const char *label, const char *filename, if (qemu_opt_get_bool(opts, "mux", 0)) { assert(permit_mux_mon); - monitor_init(chr, MONITOR_USE_READLINE); + monitor_init_hmp(chr, true); } out: diff --git a/gdbstub.c b/gdbstub.c index d614a1f3c0..8618e34311 100644 --- a/gdbstub.c +++ b/gdbstub.c @@ -3344,7 +3344,7 @@ int gdbserver_start(const char *device) /* Initialize a monitor terminal for gdb */ mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB, NULL, NULL, &error_abort); - monitor_init(mon_chr, 0); + monitor_init_hmp(mon_chr, false); } else { qemu_chr_fe_deinit(&s->chr, true); mon_chr = s->mon_chr; diff --git a/include/monitor/monitor.h b/include/monitor/monitor.h index 44ac43df34..a81eeff5f8 100644 --- a/include/monitor/monitor.h +++ b/include/monitor/monitor.h @@ -8,19 +8,14 @@ extern __thread Monitor *cur_mon; typedef struct MonitorHMP MonitorHMP; -/* flags for monitor_init */ -/* 0x01 unused */ -#define MONITOR_USE_READLINE 0x02 -#define MONITOR_USE_CONTROL 0x04 -#define MONITOR_USE_PRETTY 0x08 - #define QMP_REQ_QUEUE_LEN_MAX 8 bool monitor_cur_is_qmp(void); void monitor_init_globals(void); void monitor_init_globals_core(void); -void monitor_init(Chardev *chr, int flags); +void monitor_init_qmp(Chardev *chr, bool pretty); +void monitor_init_hmp(Chardev *chr, bool use_readline); void monitor_cleanup(void); int monitor_suspend(Monitor *mon); diff --git a/monitor/hmp.c b/monitor/hmp.c index 379e366984..5223661e82 100644 --- a/monitor/hmp.c +++ b/monitor/hmp.c @@ -1395,14 +1395,14 @@ static void monitor_readline_flush(void *opaque) monitor_flush(&mon->common); } -void monitor_init_hmp(Chardev *chr, int flags) +void monitor_init_hmp(Chardev *chr, bool use_readline) { MonitorHMP *mon = g_new0(MonitorHMP, 1); monitor_data_init(&mon->common, false, false, false); qemu_chr_fe_init(&mon->common.chr, chr, &error_abort); - mon->use_readline = flags & MONITOR_USE_READLINE; + mon->use_readline = use_readline; if (mon->use_readline) { mon->rs = readline_init(monitor_readline_printf, monitor_readline_flush, diff --git a/monitor/monitor-internal.h b/monitor/monitor-internal.h index 03ea0239ef..7760b22ba3 100644 --- a/monitor/monitor-internal.h +++ b/monitor/monitor-internal.h @@ -163,9 +163,6 @@ extern int mon_refcount; extern HMPCommand hmp_cmds[]; -void monitor_init_qmp(Chardev *chr, int flags); -void monitor_init_hmp(Chardev *chr, int flags); - int monitor_puts(Monitor *mon, const char *str); void monitor_data_init(Monitor *mon, bool is_qmp, bool skip_flush, bool use_io_thread); diff --git a/monitor/monitor.c b/monitor/monitor.c index 3f4808240a..3ef28171c0 100644 --- a/monitor/monitor.c +++ b/monitor/monitor.c @@ -551,15 +551,6 @@ void monitor_data_destroy(Monitor *mon) qemu_mutex_destroy(&mon->mon_lock); } -void monitor_init(Chardev *chr, int flags) -{ - if (flags & MONITOR_USE_CONTROL) { - monitor_init_qmp(chr, flags); - } else { - monitor_init_hmp(chr, flags); - } -} - void monitor_cleanup(void) { /* diff --git a/monitor/qmp.c b/monitor/qmp.c index 940649f688..e1b196217d 100644 --- a/monitor/qmp.c +++ b/monitor/qmp.c @@ -364,18 +364,15 @@ static void monitor_qmp_setup_handlers_bh(void *opaque) monitor_list_append(&mon->common); } -void monitor_init_qmp(Chardev *chr, int flags) +void monitor_init_qmp(Chardev *chr, bool pretty) { MonitorQMP *mon = g_new0(MonitorQMP, 1); - /* Only HMP supports readline */ - assert(!(flags & MONITOR_USE_READLINE)); - /* Note: we run QMP monitor in I/O thread when @chr supports that */ monitor_data_init(&mon->common, true, false, qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT)); - mon->pretty = flags & MONITOR_USE_PRETTY; + mon->pretty = pretty; qemu_mutex_init(&mon->qmp_queue_lock); mon->qmp_requests = g_queue_new(); diff --git a/stubs/monitor.c b/stubs/monitor.c index cdbf5c5f9a..c3e9a2e4dc 100644 --- a/stubs/monitor.c +++ b/stubs/monitor.c @@ -16,7 +16,11 @@ int monitor_get_fd(Monitor *mon, const char *name, Error **errp) return -1; } -void monitor_init(Chardev *chr, int flags) +void monitor_init_qmp(Chardev *chr, bool pretty) +{ +} + +void monitor_init_hmp(Chardev *chr, bool use_readline) { } diff --git a/tests/test-util-sockets.c b/tests/test-util-sockets.c index fd1ced058c..f1ebffee5a 100644 --- a/tests/test-util-sockets.c +++ b/tests/test-util-sockets.c @@ -71,7 +71,8 @@ int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp) */ __thread Monitor *cur_mon; int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap) { abort(); } -void monitor_init(Chardev *chr, int flags) {} +void monitor_init_qmp(Chardev *chr, bool pretty) {} +void monitor_init_hmp(Chardev *chr, bool use_readline) {} static void test_socket_fd_pass_name_good(void) diff --git a/vl.c b/vl.c index 005468cbfb..32daa434eb 100644 --- a/vl.c +++ b/vl.c @@ -2299,25 +2299,27 @@ static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp) static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp) { Chardev *chr; + bool qmp; + bool pretty = false; const char *chardev; const char *mode; - int flags; mode = qemu_opt_get(opts, "mode"); if (mode == NULL) { mode = "readline"; } if (strcmp(mode, "readline") == 0) { - flags = MONITOR_USE_READLINE; + qmp = false; } else if (strcmp(mode, "control") == 0) { - flags = MONITOR_USE_CONTROL; + qmp = true; } else { error_setg(errp, "unknown monitor mode \"%s\"", mode); return -1; } - if (qemu_opt_get_bool(opts, "pretty", 0)) - flags |= MONITOR_USE_PRETTY; + if (qemu_opt_get_bool(opts, "pretty", 0)) { + pretty = true; + } chardev = qemu_opt_get(opts, "chardev"); if (!chardev) { @@ -2330,7 +2332,11 @@ static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp) return -1; } - monitor_init(chr, flags); + if (qmp) { + monitor_init_qmp(chr, pretty); + } else { + monitor_init_hmp(chr, true); + } return 0; } -- cgit v1.2.3-55-g7522 t">+1]; char uport[33]; int sock = -1, rc; /* lookup peer addr */ memset(&ai,0, sizeof(ai)); ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG; ai.ai_family = PF_UNSPEC; ai.ai_socktype = SOCK_DGRAM; addr = qemu_opt_get(opts, "host"); port = qemu_opt_get(opts, "port"); if (addr == NULL || strlen(addr) == 0) { addr = "localhost"; } if (port == NULL || strlen(port) == 0) { fprintf(stderr, "inet_dgram: port not specified\n"); return -1; } if (qemu_opt_get_bool(opts, "ipv4", 0)) ai.ai_family = PF_INET; if (qemu_opt_get_bool(opts, "ipv6", 0)) ai.ai_family = PF_INET6; if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) { fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port, gai_strerror(rc)); return -1; } if (sockets_debug) { fprintf(stderr, "%s: peer (%s:%s)\n", __FUNCTION__, addr, port); inet_print_addrinfo(__FUNCTION__, peer); } /* lookup local addr */ memset(&ai,0, sizeof(ai)); ai.ai_flags = AI_PASSIVE; ai.ai_family = peer->ai_family; ai.ai_socktype = SOCK_DGRAM; addr = qemu_opt_get(opts, "localaddr"); port = qemu_opt_get(opts, "localport"); if (addr == NULL || strlen(addr) == 0) { addr = NULL; } if (!port || strlen(port) == 0) port = "0"; if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) { fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port, gai_strerror(rc)); return -1; } if (sockets_debug) { fprintf(stderr, "%s: local (%s:%s)\n", __FUNCTION__, addr, port); inet_print_addrinfo(__FUNCTION__, local); } /* create socket */ sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol); if (sock < 0) { fprintf(stderr,"%s: socket(%s): %s\n", __FUNCTION__, inet_strfamily(peer->ai_family), strerror(errno)); goto err; } setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on)); /* bind socket */ if (getnameinfo((struct sockaddr*)local->ai_addr,local->ai_addrlen, uaddr,INET6_ADDRSTRLEN,uport,32, NI_NUMERICHOST | NI_NUMERICSERV) != 0) { fprintf(stderr, "%s: getnameinfo: oops\n", __FUNCTION__); goto err; } if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) { fprintf(stderr,"%s: bind(%s,%s,%d): OK\n", __FUNCTION__, inet_strfamily(local->ai_family), uaddr, inet_getport(local)); goto err; } /* connect to peer */ if (getnameinfo((struct sockaddr*)peer->ai_addr, peer->ai_addrlen, uaddr, INET6_ADDRSTRLEN, uport, 32, NI_NUMERICHOST | NI_NUMERICSERV) != 0) { fprintf(stderr, "%s: getnameinfo: oops\n", __FUNCTION__); goto err; } if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) { fprintf(stderr, "%s: connect(%s,%s,%s,%s): %s\n", __FUNCTION__, inet_strfamily(peer->ai_family), peer->ai_canonname, uaddr, uport, strerror(errno)); goto err; } freeaddrinfo(local); freeaddrinfo(peer); return sock; err: if (-1 != sock) closesocket(sock); if (local) freeaddrinfo(local); if (peer) freeaddrinfo(peer); return -1; } /* compatibility wrapper */ static int inet_parse(QemuOpts *opts, const char *str) { const char *optstr, *h; char addr[64]; char port[33]; int pos; /* parse address */ if (str[0] == ':') { /* no host given */ addr[0] = '\0'; if (1 != sscanf(str,":%32[^,]%n",port,&pos)) { fprintf(stderr, "%s: portonly parse error (%s)\n", __FUNCTION__, str); return -1; } } else if (str[0] == '[') { /* IPv6 addr */ if (2 != sscanf(str,"[%64[^]]]:%32[^,]%n",addr,port,&pos)) { fprintf(stderr, "%s: ipv6 parse error (%s)\n", __FUNCTION__, str); return -1; } qemu_opt_set(opts, "ipv6", "on"); } else if (qemu_isdigit(str[0])) { /* IPv4 addr */ if (2 != sscanf(str,"%64[0-9.]:%32[^,]%n",addr,port,&pos)) { fprintf(stderr, "%s: ipv4 parse error (%s)\n", __FUNCTION__, str); return -1; } qemu_opt_set(opts, "ipv4", "on"); } else { /* hostname */ if (2 != sscanf(str,"%64[^:]:%32[^,]%n",addr,port,&pos)) { fprintf(stderr, "%s: hostname parse error (%s)\n", __FUNCTION__, str); return -1; } } qemu_opt_set(opts, "host", addr); qemu_opt_set(opts, "port", port); /* parse options */ optstr = str + pos; h = strstr(optstr, ",to="); if (h) qemu_opt_set(opts, "to", h+4); if (strstr(optstr, ",ipv4")) qemu_opt_set(opts, "ipv4", "on"); if (strstr(optstr, ",ipv6")) qemu_opt_set(opts, "ipv6", "on"); return 0; } int inet_listen(const char *str, char *ostr, int olen, int socktype, int port_offset) { QemuOpts *opts; char *optstr; int sock = -1; opts = qemu_opts_create(&dummy_opts, NULL, 0); if (inet_parse(opts, str) == 0) { sock = inet_listen_opts(opts, port_offset); if (sock != -1 && ostr) { optstr = strchr(str, ','); if (qemu_opt_get_bool(opts, "ipv6", 0)) { snprintf(ostr, olen, "[%s]:%s%s", qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"), optstr ? optstr : ""); } else { snprintf(ostr, olen, "%s:%s%s", qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"), optstr ? optstr : ""); } } } qemu_opts_del(opts); return sock; } int inet_connect(const char *str, int socktype) { QemuOpts *opts; int sock = -1; opts = qemu_opts_create(&dummy_opts, NULL, 0); if (inet_parse(opts, str) == 0) sock = inet_connect_opts(opts); qemu_opts_del(opts); return sock; } #ifndef _WIN32 int unix_listen_opts(QemuOpts *opts) { struct sockaddr_un un; const char *path = qemu_opt_get(opts, "path"); int sock, fd; sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { perror("socket(unix)"); return -1; } memset(&un, 0, sizeof(un)); un.sun_family = AF_UNIX; if (path && strlen(path)) { snprintf(un.sun_path, sizeof(un.sun_path), "%s", path); } else { char *tmpdir = getenv("TMPDIR"); snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX", tmpdir ? tmpdir : "/tmp"); /* * This dummy fd usage silences the mktemp() unsecure warning. * Using mkstemp() doesn't make things more secure here * though. bind() complains about existing files, so we have * to unlink first and thus re-open the race window. The * worst case possible is bind() failing, i.e. a DoS attack. */ fd = mkstemp(un.sun_path); close(fd); qemu_opt_set(opts, "path", un.sun_path); } unlink(un.sun_path); if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) { fprintf(stderr, "bind(unix:%s): %s\n", un.sun_path, strerror(errno)); goto err; } if (listen(sock, 1) < 0) { fprintf(stderr, "listen(unix:%s): %s\n", un.sun_path, strerror(errno)); goto err; } if (sockets_debug) fprintf(stderr, "bind(unix:%s): OK\n", un.sun_path); return sock; err: closesocket(sock); return -1; } int unix_connect_opts(QemuOpts *opts) { struct sockaddr_un un; const char *path = qemu_opt_get(opts, "path"); int sock; if (NULL == path) { fprintf(stderr, "unix connect: no path specified\n"); return -1; } sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { perror("socket(unix)"); return -1; } memset(&un, 0, sizeof(un)); un.sun_family = AF_UNIX; snprintf(un.sun_path, sizeof(un.sun_path), "%s", path); if (connect(sock, (struct sockaddr*) &un, sizeof(un)) < 0) { fprintf(stderr, "connect(unix:%s): %s\n", path, strerror(errno)); return -1; } if (sockets_debug) fprintf(stderr, "connect(unix:%s): OK\n", path); return sock; } /* compatibility wrapper */ int unix_listen(const char *str, char *ostr, int olen) { QemuOpts *opts; char *path, *optstr; int sock, len; opts = qemu_opts_create(&dummy_opts, NULL, 0); optstr = strchr(str, ','); if (optstr) { len = optstr - str; if (len) { path = g_malloc(len+1); snprintf(path, len+1, "%.*s", len, str); qemu_opt_set(opts, "path", path); g_free(path); } } else { qemu_opt_set(opts, "path", str); } sock = unix_listen_opts(opts); if (sock != -1 && ostr) snprintf(ostr, olen, "%s%s", qemu_opt_get(opts, "path"), optstr ? optstr : ""); qemu_opts_del(opts); return sock; } int unix_connect(const char *path) { QemuOpts *opts; int sock; opts = qemu_opts_create(&dummy_opts, NULL, 0); qemu_opt_set(opts, "path", path); sock = unix_connect_opts(opts); qemu_opts_del(opts); return sock; } #else int unix_listen_opts(QemuOpts *opts) { fprintf(stderr, "unix sockets are not available on windows\n"); errno = ENOTSUP; return -1; } int unix_connect_opts(QemuOpts *opts) { fprintf(stderr, "unix sockets are not available on windows\n"); errno = ENOTSUP; return -1; } int unix_listen(const char *path, char *ostr, int olen) { fprintf(stderr, "unix sockets are not available on windows\n"); errno = ENOTSUP; return -1; } int unix_connect(const char *path) { fprintf(stderr, "unix sockets are not available on windows\n"); errno = ENOTSUP; return -1; } #endif #ifdef _WIN32 static void socket_cleanup(void) { WSACleanup(); } #endif int socket_init(void) { #ifdef _WIN32 WSADATA Data; int ret, err; ret = WSAStartup(MAKEWORD(2,2), &Data); if (ret != 0) { err = WSAGetLastError(); fprintf(stderr, "WSAStartup: %d\n", err); return -1; } atexit(socket_cleanup); #endif return 0; }