monitor.c 22 KB

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