xref: /openbmc/qemu/monitor/monitor.c (revision bf616ce4)
1 /*
2  * QEMU monitor
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #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"
35 #include "trace.h"
36 
37 /*
38  * To prevent flooding clients, events can be throttled. The
39  * throttling is calculated globally, rather than per-Monitor
40  * instance.
41  */
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;
48 
49 typedef struct {
50     int64_t rate;       /* Minimum time (in ns) between two events */
51 } MonitorQAPIEventConf;
52 
53 /* Shared monitor I/O thread */
54 IOThread *mon_iothread;
55 
56 /* Coroutine to dispatch the requests received from I/O thread */
57 Coroutine *qmp_dispatcher_co;
58 
59 /*
60  * Set to true when the dispatcher coroutine should terminate.  Protected
61  * by monitor_lock.
62  */
63 bool qmp_dispatcher_co_shutdown;
64 
65 /*
66  * Protects mon_list, monitor_qapi_event_state, coroutine_mon,
67  * monitor_destroyed.
68  */
69 QemuMutex monitor_lock;
70 static GHashTable *monitor_qapi_event_state;
71 static GHashTable *coroutine_mon; /* Maps Coroutine* to Monitor* */
72 
73 MonitorList mon_list;
74 int mon_refcount;
75 static bool monitor_destroyed;
76 
77 Monitor *monitor_cur(void)
78 {
79     Monitor *mon;
80 
81     qemu_mutex_lock(&monitor_lock);
82     mon = g_hash_table_lookup(coroutine_mon, qemu_coroutine_self());
83     qemu_mutex_unlock(&monitor_lock);
84 
85     return mon;
86 }
87 
88 /**
89  * Sets a new current monitor and returns the old one.
90  *
91  * If a non-NULL monitor is set for a coroutine, another call
92  * resetting it to NULL is required before the coroutine terminates,
93  * otherwise a stale entry would remain in the hash table.
94  */
95 Monitor *monitor_set_cur(Coroutine *co, Monitor *mon)
96 {
97     Monitor *old_monitor = monitor_cur();
98 
99     qemu_mutex_lock(&monitor_lock);
100     if (mon) {
101         g_hash_table_replace(coroutine_mon, co, mon);
102     } else {
103         g_hash_table_remove(coroutine_mon, co);
104     }
105     qemu_mutex_unlock(&monitor_lock);
106 
107     return old_monitor;
108 }
109 
110 /**
111  * Is the current monitor, if any, a QMP monitor?
112  */
113 bool monitor_cur_is_qmp(void)
114 {
115     Monitor *cur_mon = monitor_cur();
116 
117     return cur_mon && monitor_is_qmp(cur_mon);
118 }
119 
120 /**
121  * Is @mon is using readline?
122  * Note: not all HMP monitors use readline, e.g., gdbserver has a
123  * non-interactive HMP monitor, so readline is not used there.
124  */
125 static inline bool monitor_uses_readline(const MonitorHMP *mon)
126 {
127     return mon->use_readline;
128 }
129 
130 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
131 {
132     if (monitor_is_qmp(mon)) {
133         return false;
134     }
135 
136     return !monitor_uses_readline(container_of(mon, MonitorHMP, common));
137 }
138 
139 static gboolean monitor_unblocked(void *do_not_use, GIOCondition cond,
140                                   void *opaque)
141 {
142     Monitor *mon = opaque;
143 
144     QEMU_LOCK_GUARD(&mon->mon_lock);
145     mon->out_watch = 0;
146     monitor_flush_locked(mon);
147     return G_SOURCE_REMOVE;
148 }
149 
150 /* Caller must hold mon->mon_lock */
151 void monitor_flush_locked(Monitor *mon)
152 {
153     int rc;
154     size_t len;
155     const char *buf;
156 
157     if (mon->skip_flush) {
158         return;
159     }
160 
161     buf = mon->outbuf->str;
162     len = mon->outbuf->len;
163 
164     if (len && !mon->mux_out) {
165         rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
166         if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
167             /* all flushed or error */
168             g_string_truncate(mon->outbuf, 0);
169             return;
170         }
171         if (rc > 0) {
172             /* partial write */
173             g_string_erase(mon->outbuf, 0, rc);
174         }
175         if (mon->out_watch == 0) {
176             mon->out_watch =
177                 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
178                                       monitor_unblocked, mon);
179         }
180     }
181 }
182 
183 void monitor_flush(Monitor *mon)
184 {
185     QEMU_LOCK_GUARD(&mon->mon_lock);
186     monitor_flush_locked(mon);
187 }
188 
189 /* flush at every end of line */
190 int monitor_puts_locked(Monitor *mon, const char *str)
191 {
192     int i;
193     char c;
194 
195     for (i = 0; str[i]; i++) {
196         c = str[i];
197         if (c == '\n') {
198             g_string_append_c(mon->outbuf, '\r');
199         }
200         g_string_append_c(mon->outbuf, c);
201         if (c == '\n') {
202             monitor_flush_locked(mon);
203         }
204     }
205 
206     return i;
207 }
208 
209 int monitor_puts(Monitor *mon, const char *str)
210 {
211     QEMU_LOCK_GUARD(&mon->mon_lock);
212     return monitor_puts_locked(mon, str);
213 }
214 
215 int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
216 {
217     char *buf;
218     int n;
219 
220     if (!mon) {
221         return -1;
222     }
223 
224     if (monitor_is_qmp(mon)) {
225         return -1;
226     }
227 
228     buf = g_strdup_vprintf(fmt, ap);
229     n = monitor_puts(mon, buf);
230     g_free(buf);
231     return n;
232 }
233 
234 int monitor_printf(Monitor *mon, const char *fmt, ...)
235 {
236     int ret;
237 
238     va_list ap;
239     va_start(ap, fmt);
240     ret = monitor_vprintf(mon, fmt, ap);
241     va_end(ap);
242     return ret;
243 }
244 
245 void monitor_printc(Monitor *mon, int c)
246 {
247     monitor_printf(mon, "'");
248     switch(c) {
249     case '\'':
250         monitor_printf(mon, "\\'");
251         break;
252     case '\\':
253         monitor_printf(mon, "\\\\");
254         break;
255     case '\n':
256         monitor_printf(mon, "\\n");
257         break;
258     case '\r':
259         monitor_printf(mon, "\\r");
260         break;
261     default:
262         if (c >= 32 && c <= 126) {
263             monitor_printf(mon, "%c", c);
264         } else {
265             monitor_printf(mon, "\\x%02x", c);
266         }
267         break;
268     }
269     monitor_printf(mon, "'");
270 }
271 
272 /*
273  * Print to current monitor if we have one, else to stderr.
274  */
275 int error_vprintf(const char *fmt, va_list ap)
276 {
277     Monitor *cur_mon = monitor_cur();
278 
279     if (cur_mon && !monitor_cur_is_qmp()) {
280         return monitor_vprintf(cur_mon, fmt, ap);
281     }
282     return vfprintf(stderr, fmt, ap);
283 }
284 
285 int error_vprintf_unless_qmp(const char *fmt, va_list ap)
286 {
287     Monitor *cur_mon = monitor_cur();
288 
289     if (!cur_mon) {
290         return vfprintf(stderr, fmt, ap);
291     }
292     if (!monitor_cur_is_qmp()) {
293         return monitor_vprintf(cur_mon, fmt, ap);
294     }
295     return -1;
296 }
297 
298 int error_printf_unless_qmp(const char *fmt, ...)
299 {
300     va_list ap;
301     int ret;
302 
303     va_start(ap, fmt);
304     ret = error_vprintf_unless_qmp(fmt, ap);
305     va_end(ap);
306     return ret;
307 }
308 
309 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
310     /* Limit guest-triggerable events to 1 per second */
311     [QAPI_EVENT_RTC_CHANGE]        = { 1000 * SCALE_MS },
312     [QAPI_EVENT_WATCHDOG]          = { 1000 * SCALE_MS },
313     [QAPI_EVENT_BALLOON_CHANGE]    = { 1000 * SCALE_MS },
314     [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
315     [QAPI_EVENT_QUORUM_FAILURE]    = { 1000 * SCALE_MS },
316     [QAPI_EVENT_VSERPORT_CHANGE]   = { 1000 * SCALE_MS },
317     [QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE] = { 1000 * SCALE_MS },
318     [QAPI_EVENT_HV_BALLOON_STATUS_REPORT] = { 1000 * SCALE_MS },
319 };
320 
321 /*
322  * Return the clock to use for recording an event's time.
323  * It's QEMU_CLOCK_REALTIME, except for qtests it's
324  * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
325  * Beware: result is invalid before configure_accelerator().
326  */
327 static inline QEMUClockType monitor_get_event_clock(void)
328 {
329     return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
330 }
331 
332 /*
333  * Broadcast an event to all monitors.
334  * @qdict is the event object.  Its member "event" must match @event.
335  * Caller must hold monitor_lock.
336  */
337 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
338 {
339     Monitor *mon;
340     MonitorQMP *qmp_mon;
341 
342     trace_monitor_protocol_event_emit(event, qdict);
343     QTAILQ_FOREACH(mon, &mon_list, entry) {
344         if (!monitor_is_qmp(mon)) {
345             continue;
346         }
347 
348         qmp_mon = container_of(mon, MonitorQMP, common);
349         if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
350             qmp_send_response(qmp_mon, qdict);
351         }
352     }
353 }
354 
355 static void monitor_qapi_event_handler(void *opaque);
356 
357 /*
358  * Queue a new event for emission to Monitor instances,
359  * applying any rate limiting if required.
360  */
361 static void
362 monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
363 {
364     MonitorQAPIEventConf *evconf;
365     MonitorQAPIEventState *evstate;
366 
367     assert(event < QAPI_EVENT__MAX);
368     evconf = &monitor_qapi_event_conf[event];
369     trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
370 
371     QEMU_LOCK_GUARD(&monitor_lock);
372 
373     if (!evconf->rate) {
374         /* Unthrottled event */
375         monitor_qapi_event_emit(event, qdict);
376     } else {
377         QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
378         MonitorQAPIEventState key = { .event = event, .data = data };
379 
380         evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
381         assert(!evstate || timer_pending(evstate->timer));
382 
383         if (evstate) {
384             /*
385              * Timer is pending for (at least) evconf->rate ns after
386              * last send.  Store event for sending when timer fires,
387              * replacing a prior stored event if any.
388              */
389             qobject_unref(evstate->qdict);
390             evstate->qdict = qobject_ref(qdict);
391         } else {
392             /*
393              * Last send was (at least) evconf->rate ns ago.
394              * Send immediately, and arm the timer to call
395              * monitor_qapi_event_handler() in evconf->rate ns.  Any
396              * events arriving before then will be delayed until then.
397              */
398             int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
399 
400             monitor_qapi_event_emit(event, qdict);
401 
402             evstate = g_new(MonitorQAPIEventState, 1);
403             evstate->event = event;
404             evstate->data = qobject_ref(data);
405             evstate->qdict = NULL;
406             evstate->timer = timer_new_ns(monitor_get_event_clock(),
407                                           monitor_qapi_event_handler,
408                                           evstate);
409             g_hash_table_add(monitor_qapi_event_state, evstate);
410             timer_mod_ns(evstate->timer, now + evconf->rate);
411         }
412     }
413 }
414 
415 void qapi_event_emit(QAPIEvent event, QDict *qdict)
416 {
417     /*
418      * monitor_qapi_event_queue_no_reenter() is not reentrant: it
419      * would deadlock on monitor_lock.  Work around by queueing
420      * events in thread-local storage.
421      * TODO: remove this, make it re-enter safe.
422      */
423     typedef struct MonitorQapiEvent {
424         QAPIEvent event;
425         QDict *qdict;
426         QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
427     } MonitorQapiEvent;
428     static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
429     static __thread bool reentered;
430     MonitorQapiEvent *ev;
431 
432     if (!reentered) {
433         QSIMPLEQ_INIT(&event_queue);
434     }
435 
436     ev = g_new(MonitorQapiEvent, 1);
437     ev->qdict = qobject_ref(qdict);
438     ev->event = event;
439     QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
440     if (reentered) {
441         return;
442     }
443 
444     reentered = true;
445 
446     while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
447         QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
448         monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
449         qobject_unref(ev->qdict);
450         g_free(ev);
451     }
452 
453     reentered = false;
454 }
455 
456 /*
457  * This function runs evconf->rate ns after sending a throttled
458  * event.
459  * If another event has since been stored, send it.
460  */
461 static void monitor_qapi_event_handler(void *opaque)
462 {
463     MonitorQAPIEventState *evstate = opaque;
464     MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
465 
466     trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
467     QEMU_LOCK_GUARD(&monitor_lock);
468 
469     if (evstate->qdict) {
470         int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
471 
472         monitor_qapi_event_emit(evstate->event, evstate->qdict);
473         qobject_unref(evstate->qdict);
474         evstate->qdict = NULL;
475         timer_mod_ns(evstate->timer, now + evconf->rate);
476     } else {
477         g_hash_table_remove(monitor_qapi_event_state, evstate);
478         qobject_unref(evstate->data);
479         timer_free(evstate->timer);
480         g_free(evstate);
481     }
482 }
483 
484 static unsigned int qapi_event_throttle_hash(const void *key)
485 {
486     const MonitorQAPIEventState *evstate = key;
487     unsigned int hash = evstate->event * 255;
488 
489     if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
490         hash += g_str_hash(qdict_get_str(evstate->data, "id"));
491     }
492 
493     if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
494         hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
495     }
496 
497     if (evstate->event == QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE) {
498         hash += g_str_hash(qdict_get_str(evstate->data, "qom-path"));
499     }
500 
501     return hash;
502 }
503 
504 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
505 {
506     const MonitorQAPIEventState *eva = a;
507     const MonitorQAPIEventState *evb = b;
508 
509     if (eva->event != evb->event) {
510         return FALSE;
511     }
512 
513     if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
514         return !strcmp(qdict_get_str(eva->data, "id"),
515                        qdict_get_str(evb->data, "id"));
516     }
517 
518     if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
519         return !strcmp(qdict_get_str(eva->data, "node-name"),
520                        qdict_get_str(evb->data, "node-name"));
521     }
522 
523     if (eva->event == QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE) {
524         return !strcmp(qdict_get_str(eva->data, "qom-path"),
525                        qdict_get_str(evb->data, "qom-path"));
526     }
527 
528     return TRUE;
529 }
530 
531 int monitor_suspend(Monitor *mon)
532 {
533     if (monitor_is_hmp_non_interactive(mon)) {
534         return -ENOTTY;
535     }
536 
537     qatomic_inc(&mon->suspend_cnt);
538 
539     if (mon->use_io_thread) {
540         /*
541          * Kick I/O thread to make sure this takes effect.  It'll be
542          * evaluated again in prepare() of the watch object.
543          */
544         aio_notify(iothread_get_aio_context(mon_iothread));
545     }
546 
547     trace_monitor_suspend(mon, 1);
548     return 0;
549 }
550 
551 static void monitor_accept_input(void *opaque)
552 {
553     Monitor *mon = opaque;
554 
555     qemu_mutex_lock(&mon->mon_lock);
556     if (!monitor_is_qmp(mon) && mon->reset_seen) {
557         MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
558         assert(hmp_mon->rs);
559         readline_restart(hmp_mon->rs);
560         qemu_mutex_unlock(&mon->mon_lock);
561         readline_show_prompt(hmp_mon->rs);
562     } else {
563         qemu_mutex_unlock(&mon->mon_lock);
564     }
565 
566     qemu_chr_fe_accept_input(&mon->chr);
567 }
568 
569 void monitor_resume(Monitor *mon)
570 {
571     if (monitor_is_hmp_non_interactive(mon)) {
572         return;
573     }
574 
575     if (qatomic_dec_fetch(&mon->suspend_cnt) == 0) {
576         AioContext *ctx;
577 
578         if (mon->use_io_thread) {
579             ctx = iothread_get_aio_context(mon_iothread);
580         } else {
581             ctx = qemu_get_aio_context();
582         }
583 
584         aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
585     }
586 
587     trace_monitor_suspend(mon, -1);
588 }
589 
590 int monitor_can_read(void *opaque)
591 {
592     Monitor *mon = opaque;
593 
594     return !qatomic_read(&mon->suspend_cnt);
595 }
596 
597 void monitor_list_append(Monitor *mon)
598 {
599     qemu_mutex_lock(&monitor_lock);
600     /*
601      * This prevents inserting new monitors during monitor_cleanup().
602      * A cleaner solution would involve the main thread telling other
603      * threads to terminate, waiting for their termination.
604      */
605     if (!monitor_destroyed) {
606         QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
607         mon = NULL;
608     }
609     qemu_mutex_unlock(&monitor_lock);
610 
611     if (mon) {
612         monitor_data_destroy(mon);
613         g_free(mon);
614     }
615 }
616 
617 static void monitor_iothread_init(void)
618 {
619     mon_iothread = iothread_create("mon_iothread", &error_abort);
620 }
621 
622 void monitor_data_init(Monitor *mon, bool is_qmp, bool skip_flush,
623                        bool use_io_thread)
624 {
625     if (use_io_thread && !mon_iothread) {
626         monitor_iothread_init();
627     }
628     qemu_mutex_init(&mon->mon_lock);
629     mon->is_qmp = is_qmp;
630     mon->outbuf = g_string_new(NULL);
631     mon->skip_flush = skip_flush;
632     mon->use_io_thread = use_io_thread;
633 }
634 
635 void monitor_data_destroy(Monitor *mon)
636 {
637     g_free(mon->mon_cpu_path);
638     qemu_chr_fe_deinit(&mon->chr, false);
639     if (monitor_is_qmp(mon)) {
640         monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
641     } else {
642         readline_free(container_of(mon, MonitorHMP, common)->rs);
643     }
644     g_string_free(mon->outbuf, true);
645     qemu_mutex_destroy(&mon->mon_lock);
646 }
647 
648 void monitor_cleanup(void)
649 {
650     /*
651      * The dispatcher needs to stop before destroying the monitor and
652      * the I/O thread.
653      *
654      * We need to poll both qemu_aio_context and iohandler_ctx to make
655      * sure that the dispatcher coroutine keeps making progress and
656      * eventually terminates.  qemu_aio_context is automatically
657      * polled by calling AIO_WAIT_WHILE_UNLOCKED on it, but we must poll
658      * iohandler_ctx manually.
659      *
660      * Letting the iothread continue while shutting down the dispatcher
661      * means that new requests may still be coming in. This is okay,
662      * we'll just leave them in the queue without sending a response
663      * and monitor_data_destroy() will free them.
664      */
665     WITH_QEMU_LOCK_GUARD(&monitor_lock) {
666         qmp_dispatcher_co_shutdown = true;
667     }
668     qmp_dispatcher_co_wake();
669 
670     AIO_WAIT_WHILE_UNLOCKED(NULL,
671                    (aio_poll(iohandler_get_aio_context(), false),
672                     qatomic_read(&qmp_dispatcher_co)));
673 
674     /*
675      * We need to explicitly stop the I/O thread (but not destroy it),
676      * clean up the monitor resources, then destroy the I/O thread since
677      * we need to unregister from chardev below in
678      * monitor_data_destroy(), and chardev is not thread-safe yet
679      */
680     if (mon_iothread) {
681         iothread_stop(mon_iothread);
682     }
683 
684     /* Flush output buffers and destroy monitors */
685     qemu_mutex_lock(&monitor_lock);
686     monitor_destroyed = true;
687     while (!QTAILQ_EMPTY(&mon_list)) {
688         Monitor *mon = QTAILQ_FIRST(&mon_list);
689         QTAILQ_REMOVE(&mon_list, mon, entry);
690         /* Permit QAPI event emission from character frontend release */
691         qemu_mutex_unlock(&monitor_lock);
692         monitor_flush(mon);
693         monitor_data_destroy(mon);
694         qemu_mutex_lock(&monitor_lock);
695         g_free(mon);
696     }
697     qemu_mutex_unlock(&monitor_lock);
698 
699     if (mon_iothread) {
700         iothread_destroy(mon_iothread);
701         mon_iothread = NULL;
702     }
703 }
704 
705 static void monitor_qapi_event_init(void)
706 {
707     monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
708                                                 qapi_event_throttle_equal);
709 }
710 
711 void monitor_init_globals(void)
712 {
713     monitor_qapi_event_init();
714     qemu_mutex_init(&monitor_lock);
715     coroutine_mon = g_hash_table_new(NULL, NULL);
716 
717     /*
718      * The dispatcher BH must run in the main loop thread, since we
719      * have commands assuming that context.  It would be nice to get
720      * rid of those assumptions.
721      */
722     qmp_dispatcher_co = qemu_coroutine_create(monitor_qmp_dispatcher_co, NULL);
723     aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
724 }
725 
726 int monitor_init(MonitorOptions *opts, bool allow_hmp, Error **errp)
727 {
728     ERRP_GUARD();
729     Chardev *chr;
730 
731     chr = qemu_chr_find(opts->chardev);
732     if (chr == NULL) {
733         error_setg(errp, "chardev \"%s\" not found", opts->chardev);
734         return -1;
735     }
736 
737     if (!opts->has_mode) {
738         opts->mode = allow_hmp ? MONITOR_MODE_READLINE : MONITOR_MODE_CONTROL;
739     }
740 
741     switch (opts->mode) {
742     case MONITOR_MODE_CONTROL:
743         monitor_init_qmp(chr, opts->pretty, errp);
744         break;
745     case MONITOR_MODE_READLINE:
746         if (!allow_hmp) {
747             error_setg(errp, "Only QMP is supported");
748             return -1;
749         }
750         if (opts->pretty) {
751             error_setg(errp, "'pretty' is not compatible with HMP monitors");
752             return -1;
753         }
754         monitor_init_hmp(chr, true, errp);
755         break;
756     default:
757         g_assert_not_reached();
758     }
759 
760     return *errp ? -1 : 0;
761 }
762 
763 int monitor_init_opts(QemuOpts *opts, Error **errp)
764 {
765     Visitor *v;
766     MonitorOptions *options;
767     int ret;
768 
769     v = opts_visitor_new(opts);
770     visit_type_MonitorOptions(v, NULL, &options, errp);
771     visit_free(v);
772     if (!options) {
773         return -1;
774     }
775 
776     ret = monitor_init(options, true, errp);
777     qapi_free_MonitorOptions(options);
778     return ret;
779 }
780 
781 QemuOptsList qemu_mon_opts = {
782     .name = "mon",
783     .implied_opt_name = "chardev",
784     .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
785     .desc = {
786         {
787             .name = "mode",
788             .type = QEMU_OPT_STRING,
789         },{
790             .name = "chardev",
791             .type = QEMU_OPT_STRING,
792         },{
793             .name = "pretty",
794             .type = QEMU_OPT_BOOL,
795         },
796         { /* end of list */ }
797     },
798 };
799