2
0

monitor.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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. #include "qemu/osdep.h"
  25. #include "monitor-internal.h"
  26. #include "qapi/error.h"
  27. #include "qapi/opts-visitor.h"
  28. #include "qapi/qapi-emit-events.h"
  29. #include "qapi/qapi-visit-control.h"
  30. #include "qapi/qmp/qdict.h"
  31. #include "qapi/qmp/qstring.h"
  32. #include "qemu/error-report.h"
  33. #include "qemu/option.h"
  34. #include "sysemu/qtest.h"
  35. #include "sysemu/sysemu.h"
  36. #include "trace.h"
  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. typedef struct {
  49. int64_t rate; /* Minimum time (in ns) between two events */
  50. } MonitorQAPIEventConf;
  51. /* Shared monitor I/O thread */
  52. IOThread *mon_iothread;
  53. /* Coroutine to dispatch the requests received from I/O thread */
  54. Coroutine *qmp_dispatcher_co;
  55. /* Set to true when the dispatcher coroutine should terminate */
  56. bool qmp_dispatcher_co_shutdown;
  57. /*
  58. * qmp_dispatcher_co_busy is used for synchronisation between the
  59. * monitor thread and the main thread to ensure that the dispatcher
  60. * coroutine never gets scheduled a second time when it's already
  61. * scheduled (scheduling the same coroutine twice is forbidden).
  62. *
  63. * It is true if the coroutine is active and processing requests.
  64. * Additional requests may then be pushed onto mon->qmp_requests,
  65. * and @qmp_dispatcher_co_shutdown may be set without further ado.
  66. * @qmp_dispatcher_co_busy must not be woken up in this case.
  67. *
  68. * If false, you also have to set @qmp_dispatcher_co_busy to true and
  69. * wake up @qmp_dispatcher_co after pushing the new requests.
  70. *
  71. * The coroutine will automatically change this variable back to false
  72. * before it yields. Nobody else may set the variable to false.
  73. *
  74. * Access must be atomic for thread safety.
  75. */
  76. bool qmp_dispatcher_co_busy;
  77. /*
  78. * Protects mon_list, monitor_qapi_event_state, coroutine_mon,
  79. * monitor_destroyed.
  80. */
  81. QemuMutex monitor_lock;
  82. static GHashTable *monitor_qapi_event_state;
  83. static GHashTable *coroutine_mon; /* Maps Coroutine* to Monitor* */
  84. MonitorList mon_list;
  85. int mon_refcount;
  86. static bool monitor_destroyed;
  87. Monitor *monitor_cur(void)
  88. {
  89. Monitor *mon;
  90. qemu_mutex_lock(&monitor_lock);
  91. mon = g_hash_table_lookup(coroutine_mon, qemu_coroutine_self());
  92. qemu_mutex_unlock(&monitor_lock);
  93. return mon;
  94. }
  95. /**
  96. * Sets a new current monitor and returns the old one.
  97. *
  98. * If a non-NULL monitor is set for a coroutine, another call
  99. * resetting it to NULL is required before the coroutine terminates,
  100. * otherwise a stale entry would remain in the hash table.
  101. */
  102. Monitor *monitor_set_cur(Coroutine *co, Monitor *mon)
  103. {
  104. Monitor *old_monitor = monitor_cur();
  105. qemu_mutex_lock(&monitor_lock);
  106. if (mon) {
  107. g_hash_table_replace(coroutine_mon, co, mon);
  108. } else {
  109. g_hash_table_remove(coroutine_mon, co);
  110. }
  111. qemu_mutex_unlock(&monitor_lock);
  112. return old_monitor;
  113. }
  114. /**
  115. * Is the current monitor, if any, a QMP monitor?
  116. */
  117. bool monitor_cur_is_qmp(void)
  118. {
  119. Monitor *cur_mon = monitor_cur();
  120. return cur_mon && monitor_is_qmp(cur_mon);
  121. }
  122. /**
  123. * Is @mon is using readline?
  124. * Note: not all HMP monitors use readline, e.g., gdbserver has a
  125. * non-interactive HMP monitor, so readline is not used there.
  126. */
  127. static inline bool monitor_uses_readline(const MonitorHMP *mon)
  128. {
  129. return mon->use_readline;
  130. }
  131. static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
  132. {
  133. if (monitor_is_qmp(mon)) {
  134. return false;
  135. }
  136. return !monitor_uses_readline(container_of(mon, MonitorHMP, common));
  137. }
  138. static void monitor_flush_locked(Monitor *mon);
  139. static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
  140. void *opaque)
  141. {
  142. Monitor *mon = opaque;
  143. qemu_mutex_lock(&mon->mon_lock);
  144. mon->out_watch = 0;
  145. monitor_flush_locked(mon);
  146. qemu_mutex_unlock(&mon->mon_lock);
  147. return FALSE;
  148. }
  149. /* Caller must hold mon->mon_lock */
  150. static void monitor_flush_locked(Monitor *mon)
  151. {
  152. int rc;
  153. size_t len;
  154. const char *buf;
  155. if (mon->skip_flush) {
  156. return;
  157. }
  158. buf = qstring_get_str(mon->outbuf);
  159. len = qstring_get_length(mon->outbuf);
  160. if (len && !mon->mux_out) {
  161. rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
  162. if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
  163. /* all flushed or error */
  164. qobject_unref(mon->outbuf);
  165. mon->outbuf = qstring_new();
  166. return;
  167. }
  168. if (rc > 0) {
  169. /* partial write */
  170. QString *tmp = qstring_from_str(buf + rc);
  171. qobject_unref(mon->outbuf);
  172. mon->outbuf = tmp;
  173. }
  174. if (mon->out_watch == 0) {
  175. mon->out_watch =
  176. qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
  177. monitor_unblocked, mon);
  178. }
  179. }
  180. }
  181. void monitor_flush(Monitor *mon)
  182. {
  183. qemu_mutex_lock(&mon->mon_lock);
  184. monitor_flush_locked(mon);
  185. qemu_mutex_unlock(&mon->mon_lock);
  186. }
  187. /* flush at every end of line */
  188. int monitor_puts(Monitor *mon, const char *str)
  189. {
  190. int i;
  191. char c;
  192. qemu_mutex_lock(&mon->mon_lock);
  193. for (i = 0; str[i]; i++) {
  194. c = str[i];
  195. if (c == '\n') {
  196. qstring_append_chr(mon->outbuf, '\r');
  197. }
  198. qstring_append_chr(mon->outbuf, c);
  199. if (c == '\n') {
  200. monitor_flush_locked(mon);
  201. }
  202. }
  203. qemu_mutex_unlock(&mon->mon_lock);
  204. return i;
  205. }
  206. int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
  207. {
  208. char *buf;
  209. int n;
  210. if (!mon) {
  211. return -1;
  212. }
  213. if (monitor_is_qmp(mon)) {
  214. return -1;
  215. }
  216. buf = g_strdup_vprintf(fmt, ap);
  217. n = monitor_puts(mon, buf);
  218. g_free(buf);
  219. return n;
  220. }
  221. int monitor_printf(Monitor *mon, const char *fmt, ...)
  222. {
  223. int ret;
  224. va_list ap;
  225. va_start(ap, fmt);
  226. ret = monitor_vprintf(mon, fmt, ap);
  227. va_end(ap);
  228. return ret;
  229. }
  230. /*
  231. * Print to current monitor if we have one, else to stderr.
  232. */
  233. int error_vprintf(const char *fmt, va_list ap)
  234. {
  235. Monitor *cur_mon = monitor_cur();
  236. if (cur_mon && !monitor_cur_is_qmp()) {
  237. return monitor_vprintf(cur_mon, fmt, ap);
  238. }
  239. return vfprintf(stderr, fmt, ap);
  240. }
  241. int error_vprintf_unless_qmp(const char *fmt, va_list ap)
  242. {
  243. Monitor *cur_mon = monitor_cur();
  244. if (!cur_mon) {
  245. return vfprintf(stderr, fmt, ap);
  246. }
  247. if (!monitor_cur_is_qmp()) {
  248. return monitor_vprintf(cur_mon, fmt, ap);
  249. }
  250. return -1;
  251. }
  252. static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
  253. /* Limit guest-triggerable events to 1 per second */
  254. [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
  255. [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
  256. [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
  257. [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
  258. [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
  259. [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
  260. [QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE] = { 1000 * SCALE_MS },
  261. };
  262. /*
  263. * Return the clock to use for recording an event's time.
  264. * It's QEMU_CLOCK_REALTIME, except for qtests it's
  265. * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
  266. * Beware: result is invalid before configure_accelerator().
  267. */
  268. static inline QEMUClockType monitor_get_event_clock(void)
  269. {
  270. return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
  271. }
  272. /*
  273. * Broadcast an event to all monitors.
  274. * @qdict is the event object. Its member "event" must match @event.
  275. * Caller must hold monitor_lock.
  276. */
  277. static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
  278. {
  279. Monitor *mon;
  280. MonitorQMP *qmp_mon;
  281. trace_monitor_protocol_event_emit(event, qdict);
  282. QTAILQ_FOREACH(mon, &mon_list, entry) {
  283. if (!monitor_is_qmp(mon)) {
  284. continue;
  285. }
  286. qmp_mon = container_of(mon, MonitorQMP, common);
  287. if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
  288. qmp_send_response(qmp_mon, qdict);
  289. }
  290. }
  291. }
  292. static void monitor_qapi_event_handler(void *opaque);
  293. /*
  294. * Queue a new event for emission to Monitor instances,
  295. * applying any rate limiting if required.
  296. */
  297. static void
  298. monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
  299. {
  300. MonitorQAPIEventConf *evconf;
  301. MonitorQAPIEventState *evstate;
  302. assert(event < QAPI_EVENT__MAX);
  303. evconf = &monitor_qapi_event_conf[event];
  304. trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
  305. qemu_mutex_lock(&monitor_lock);
  306. if (!evconf->rate) {
  307. /* Unthrottled event */
  308. monitor_qapi_event_emit(event, qdict);
  309. } else {
  310. QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
  311. MonitorQAPIEventState key = { .event = event, .data = data };
  312. evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
  313. assert(!evstate || timer_pending(evstate->timer));
  314. if (evstate) {
  315. /*
  316. * Timer is pending for (at least) evconf->rate ns after
  317. * last send. Store event for sending when timer fires,
  318. * replacing a prior stored event if any.
  319. */
  320. qobject_unref(evstate->qdict);
  321. evstate->qdict = qobject_ref(qdict);
  322. } else {
  323. /*
  324. * Last send was (at least) evconf->rate ns ago.
  325. * Send immediately, and arm the timer to call
  326. * monitor_qapi_event_handler() in evconf->rate ns. Any
  327. * events arriving before then will be delayed until then.
  328. */
  329. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  330. monitor_qapi_event_emit(event, qdict);
  331. evstate = g_new(MonitorQAPIEventState, 1);
  332. evstate->event = event;
  333. evstate->data = qobject_ref(data);
  334. evstate->qdict = NULL;
  335. evstate->timer = timer_new_ns(monitor_get_event_clock(),
  336. monitor_qapi_event_handler,
  337. evstate);
  338. g_hash_table_add(monitor_qapi_event_state, evstate);
  339. timer_mod_ns(evstate->timer, now + evconf->rate);
  340. }
  341. }
  342. qemu_mutex_unlock(&monitor_lock);
  343. }
  344. void qapi_event_emit(QAPIEvent event, QDict *qdict)
  345. {
  346. /*
  347. * monitor_qapi_event_queue_no_reenter() is not reentrant: it
  348. * would deadlock on monitor_lock. Work around by queueing
  349. * events in thread-local storage.
  350. * TODO: remove this, make it re-enter safe.
  351. */
  352. typedef struct MonitorQapiEvent {
  353. QAPIEvent event;
  354. QDict *qdict;
  355. QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
  356. } MonitorQapiEvent;
  357. static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
  358. static __thread bool reentered;
  359. MonitorQapiEvent *ev;
  360. if (!reentered) {
  361. QSIMPLEQ_INIT(&event_queue);
  362. }
  363. ev = g_new(MonitorQapiEvent, 1);
  364. ev->qdict = qobject_ref(qdict);
  365. ev->event = event;
  366. QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
  367. if (reentered) {
  368. return;
  369. }
  370. reentered = true;
  371. while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
  372. QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
  373. monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
  374. qobject_unref(ev->qdict);
  375. g_free(ev);
  376. }
  377. reentered = false;
  378. }
  379. /*
  380. * This function runs evconf->rate ns after sending a throttled
  381. * event.
  382. * If another event has since been stored, send it.
  383. */
  384. static void monitor_qapi_event_handler(void *opaque)
  385. {
  386. MonitorQAPIEventState *evstate = opaque;
  387. MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
  388. trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
  389. qemu_mutex_lock(&monitor_lock);
  390. if (evstate->qdict) {
  391. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  392. monitor_qapi_event_emit(evstate->event, evstate->qdict);
  393. qobject_unref(evstate->qdict);
  394. evstate->qdict = NULL;
  395. timer_mod_ns(evstate->timer, now + evconf->rate);
  396. } else {
  397. g_hash_table_remove(monitor_qapi_event_state, evstate);
  398. qobject_unref(evstate->data);
  399. timer_free(evstate->timer);
  400. g_free(evstate);
  401. }
  402. qemu_mutex_unlock(&monitor_lock);
  403. }
  404. static unsigned int qapi_event_throttle_hash(const void *key)
  405. {
  406. const MonitorQAPIEventState *evstate = key;
  407. unsigned int hash = evstate->event * 255;
  408. if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
  409. hash += g_str_hash(qdict_get_str(evstate->data, "id"));
  410. }
  411. if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  412. hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
  413. }
  414. return hash;
  415. }
  416. static gboolean qapi_event_throttle_equal(const void *a, const void *b)
  417. {
  418. const MonitorQAPIEventState *eva = a;
  419. const MonitorQAPIEventState *evb = b;
  420. if (eva->event != evb->event) {
  421. return FALSE;
  422. }
  423. if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
  424. return !strcmp(qdict_get_str(eva->data, "id"),
  425. qdict_get_str(evb->data, "id"));
  426. }
  427. if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  428. return !strcmp(qdict_get_str(eva->data, "node-name"),
  429. qdict_get_str(evb->data, "node-name"));
  430. }
  431. return TRUE;
  432. }
  433. int monitor_suspend(Monitor *mon)
  434. {
  435. if (monitor_is_hmp_non_interactive(mon)) {
  436. return -ENOTTY;
  437. }
  438. qatomic_inc(&mon->suspend_cnt);
  439. if (mon->use_io_thread) {
  440. /*
  441. * Kick I/O thread to make sure this takes effect. It'll be
  442. * evaluated again in prepare() of the watch object.
  443. */
  444. aio_notify(iothread_get_aio_context(mon_iothread));
  445. }
  446. trace_monitor_suspend(mon, 1);
  447. return 0;
  448. }
  449. static void monitor_accept_input(void *opaque)
  450. {
  451. Monitor *mon = opaque;
  452. qemu_chr_fe_accept_input(&mon->chr);
  453. }
  454. void monitor_resume(Monitor *mon)
  455. {
  456. if (monitor_is_hmp_non_interactive(mon)) {
  457. return;
  458. }
  459. if (qatomic_dec_fetch(&mon->suspend_cnt) == 0) {
  460. AioContext *ctx;
  461. if (mon->use_io_thread) {
  462. ctx = iothread_get_aio_context(mon_iothread);
  463. } else {
  464. ctx = qemu_get_aio_context();
  465. }
  466. if (!monitor_is_qmp(mon)) {
  467. MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
  468. assert(hmp_mon->rs);
  469. readline_show_prompt(hmp_mon->rs);
  470. }
  471. aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
  472. }
  473. trace_monitor_suspend(mon, -1);
  474. }
  475. int monitor_can_read(void *opaque)
  476. {
  477. Monitor *mon = opaque;
  478. return !qatomic_mb_read(&mon->suspend_cnt);
  479. }
  480. void monitor_list_append(Monitor *mon)
  481. {
  482. qemu_mutex_lock(&monitor_lock);
  483. /*
  484. * This prevents inserting new monitors during monitor_cleanup().
  485. * A cleaner solution would involve the main thread telling other
  486. * threads to terminate, waiting for their termination.
  487. */
  488. if (!monitor_destroyed) {
  489. QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
  490. mon = NULL;
  491. }
  492. qemu_mutex_unlock(&monitor_lock);
  493. if (mon) {
  494. monitor_data_destroy(mon);
  495. g_free(mon);
  496. }
  497. }
  498. static void monitor_iothread_init(void)
  499. {
  500. mon_iothread = iothread_create("mon_iothread", &error_abort);
  501. }
  502. void monitor_data_init(Monitor *mon, bool is_qmp, bool skip_flush,
  503. bool use_io_thread)
  504. {
  505. if (use_io_thread && !mon_iothread) {
  506. monitor_iothread_init();
  507. }
  508. qemu_mutex_init(&mon->mon_lock);
  509. mon->is_qmp = is_qmp;
  510. mon->outbuf = qstring_new();
  511. mon->skip_flush = skip_flush;
  512. mon->use_io_thread = use_io_thread;
  513. }
  514. void monitor_data_destroy(Monitor *mon)
  515. {
  516. g_free(mon->mon_cpu_path);
  517. qemu_chr_fe_deinit(&mon->chr, false);
  518. if (monitor_is_qmp(mon)) {
  519. monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
  520. } else {
  521. readline_free(container_of(mon, MonitorHMP, common)->rs);
  522. }
  523. qobject_unref(mon->outbuf);
  524. qemu_mutex_destroy(&mon->mon_lock);
  525. }
  526. void monitor_cleanup(void)
  527. {
  528. /*
  529. * We need to explicitly stop the I/O thread (but not destroy it),
  530. * clean up the monitor resources, then destroy the I/O thread since
  531. * we need to unregister from chardev below in
  532. * monitor_data_destroy(), and chardev is not thread-safe yet
  533. */
  534. if (mon_iothread) {
  535. iothread_stop(mon_iothread);
  536. }
  537. /*
  538. * The dispatcher needs to stop before destroying the monitor and
  539. * the I/O thread.
  540. *
  541. * We need to poll both qemu_aio_context and iohandler_ctx to make
  542. * sure that the dispatcher coroutine keeps making progress and
  543. * eventually terminates. qemu_aio_context is automatically
  544. * polled by calling AIO_WAIT_WHILE on it, but we must poll
  545. * iohandler_ctx manually.
  546. */
  547. qmp_dispatcher_co_shutdown = true;
  548. if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
  549. aio_co_wake(qmp_dispatcher_co);
  550. }
  551. AIO_WAIT_WHILE(qemu_get_aio_context(),
  552. (aio_poll(iohandler_get_aio_context(), false),
  553. qatomic_mb_read(&qmp_dispatcher_co_busy)));
  554. /* Flush output buffers and destroy monitors */
  555. qemu_mutex_lock(&monitor_lock);
  556. monitor_destroyed = true;
  557. while (!QTAILQ_EMPTY(&mon_list)) {
  558. Monitor *mon = QTAILQ_FIRST(&mon_list);
  559. QTAILQ_REMOVE(&mon_list, mon, entry);
  560. /* Permit QAPI event emission from character frontend release */
  561. qemu_mutex_unlock(&monitor_lock);
  562. monitor_flush(mon);
  563. monitor_data_destroy(mon);
  564. qemu_mutex_lock(&monitor_lock);
  565. g_free(mon);
  566. }
  567. qemu_mutex_unlock(&monitor_lock);
  568. if (mon_iothread) {
  569. iothread_destroy(mon_iothread);
  570. mon_iothread = NULL;
  571. }
  572. }
  573. static void monitor_qapi_event_init(void)
  574. {
  575. monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
  576. qapi_event_throttle_equal);
  577. }
  578. void monitor_init_globals_core(void)
  579. {
  580. monitor_qapi_event_init();
  581. qemu_mutex_init(&monitor_lock);
  582. coroutine_mon = g_hash_table_new(NULL, NULL);
  583. /*
  584. * The dispatcher BH must run in the main loop thread, since we
  585. * have commands assuming that context. It would be nice to get
  586. * rid of those assumptions.
  587. */
  588. qmp_dispatcher_co = qemu_coroutine_create(monitor_qmp_dispatcher_co, NULL);
  589. qatomic_mb_set(&qmp_dispatcher_co_busy, true);
  590. aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
  591. }
  592. int monitor_init(MonitorOptions *opts, bool allow_hmp, Error **errp)
  593. {
  594. Chardev *chr;
  595. Error *local_err = NULL;
  596. chr = qemu_chr_find(opts->chardev);
  597. if (chr == NULL) {
  598. error_setg(errp, "chardev \"%s\" not found", opts->chardev);
  599. return -1;
  600. }
  601. if (!opts->has_mode) {
  602. opts->mode = allow_hmp ? MONITOR_MODE_READLINE : MONITOR_MODE_CONTROL;
  603. }
  604. switch (opts->mode) {
  605. case MONITOR_MODE_CONTROL:
  606. monitor_init_qmp(chr, opts->pretty, &local_err);
  607. break;
  608. case MONITOR_MODE_READLINE:
  609. if (!allow_hmp) {
  610. error_setg(errp, "Only QMP is supported");
  611. return -1;
  612. }
  613. if (opts->pretty) {
  614. warn_report("'pretty' is deprecated for HMP monitors, it has no "
  615. "effect and will be removed in future versions");
  616. }
  617. monitor_init_hmp(chr, true, &local_err);
  618. break;
  619. default:
  620. g_assert_not_reached();
  621. }
  622. if (local_err) {
  623. error_propagate(errp, local_err);
  624. return -1;
  625. }
  626. return 0;
  627. }
  628. int monitor_init_opts(QemuOpts *opts, Error **errp)
  629. {
  630. Visitor *v;
  631. MonitorOptions *options;
  632. int ret;
  633. v = opts_visitor_new(opts);
  634. visit_type_MonitorOptions(v, NULL, &options, errp);
  635. visit_free(v);
  636. if (!options) {
  637. return -1;
  638. }
  639. ret = monitor_init(options, true, errp);
  640. qapi_free_MonitorOptions(options);
  641. return ret;
  642. }
  643. QemuOptsList qemu_mon_opts = {
  644. .name = "mon",
  645. .implied_opt_name = "chardev",
  646. .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
  647. .desc = {
  648. {
  649. .name = "mode",
  650. .type = QEMU_OPT_STRING,
  651. },{
  652. .name = "chardev",
  653. .type = QEMU_OPT_STRING,
  654. },{
  655. .name = "pretty",
  656. .type = QEMU_OPT_BOOL,
  657. },
  658. { /* end of list */ }
  659. },
  660. };