monitor.c 22 KB

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