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