monitor.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. void monitor_printc(Monitor *mon, int c)
  226. {
  227. monitor_printf(mon, "'");
  228. switch(c) {
  229. case '\'':
  230. monitor_printf(mon, "\\'");
  231. break;
  232. case '\\':
  233. monitor_printf(mon, "\\\\");
  234. break;
  235. case '\n':
  236. monitor_printf(mon, "\\n");
  237. break;
  238. case '\r':
  239. monitor_printf(mon, "\\r");
  240. break;
  241. default:
  242. if (c >= 32 && c <= 126) {
  243. monitor_printf(mon, "%c", c);
  244. } else {
  245. monitor_printf(mon, "\\x%02x", c);
  246. }
  247. break;
  248. }
  249. monitor_printf(mon, "'");
  250. }
  251. /*
  252. * Print to current monitor if we have one, else to stderr.
  253. */
  254. int error_vprintf(const char *fmt, va_list ap)
  255. {
  256. Monitor *cur_mon = monitor_cur();
  257. if (cur_mon && !monitor_cur_is_qmp()) {
  258. return monitor_vprintf(cur_mon, fmt, ap);
  259. }
  260. return vfprintf(stderr, fmt, ap);
  261. }
  262. int error_vprintf_unless_qmp(const char *fmt, va_list ap)
  263. {
  264. Monitor *cur_mon = monitor_cur();
  265. if (!cur_mon) {
  266. return vfprintf(stderr, fmt, ap);
  267. }
  268. if (!monitor_cur_is_qmp()) {
  269. return monitor_vprintf(cur_mon, fmt, ap);
  270. }
  271. return -1;
  272. }
  273. int error_printf_unless_qmp(const char *fmt, ...)
  274. {
  275. va_list ap;
  276. int ret;
  277. va_start(ap, fmt);
  278. ret = error_vprintf_unless_qmp(fmt, ap);
  279. va_end(ap);
  280. return ret;
  281. }
  282. static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
  283. /* Limit guest-triggerable events to 1 per second */
  284. [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
  285. [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
  286. [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
  287. [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
  288. [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
  289. [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
  290. [QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE] = { 1000 * SCALE_MS },
  291. };
  292. /*
  293. * Return the clock to use for recording an event's time.
  294. * It's QEMU_CLOCK_REALTIME, except for qtests it's
  295. * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
  296. * Beware: result is invalid before configure_accelerator().
  297. */
  298. static inline QEMUClockType monitor_get_event_clock(void)
  299. {
  300. return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
  301. }
  302. /*
  303. * Broadcast an event to all monitors.
  304. * @qdict is the event object. Its member "event" must match @event.
  305. * Caller must hold monitor_lock.
  306. */
  307. static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
  308. {
  309. Monitor *mon;
  310. MonitorQMP *qmp_mon;
  311. trace_monitor_protocol_event_emit(event, qdict);
  312. QTAILQ_FOREACH(mon, &mon_list, entry) {
  313. if (!monitor_is_qmp(mon)) {
  314. continue;
  315. }
  316. qmp_mon = container_of(mon, MonitorQMP, common);
  317. if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
  318. qmp_send_response(qmp_mon, qdict);
  319. }
  320. }
  321. }
  322. static void monitor_qapi_event_handler(void *opaque);
  323. /*
  324. * Queue a new event for emission to Monitor instances,
  325. * applying any rate limiting if required.
  326. */
  327. static void
  328. monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
  329. {
  330. MonitorQAPIEventConf *evconf;
  331. MonitorQAPIEventState *evstate;
  332. assert(event < QAPI_EVENT__MAX);
  333. evconf = &monitor_qapi_event_conf[event];
  334. trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
  335. QEMU_LOCK_GUARD(&monitor_lock);
  336. if (!evconf->rate) {
  337. /* Unthrottled event */
  338. monitor_qapi_event_emit(event, qdict);
  339. } else {
  340. QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
  341. MonitorQAPIEventState key = { .event = event, .data = data };
  342. evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
  343. assert(!evstate || timer_pending(evstate->timer));
  344. if (evstate) {
  345. /*
  346. * Timer is pending for (at least) evconf->rate ns after
  347. * last send. Store event for sending when timer fires,
  348. * replacing a prior stored event if any.
  349. */
  350. qobject_unref(evstate->qdict);
  351. evstate->qdict = qobject_ref(qdict);
  352. } else {
  353. /*
  354. * Last send was (at least) evconf->rate ns ago.
  355. * Send immediately, and arm the timer to call
  356. * monitor_qapi_event_handler() in evconf->rate ns. Any
  357. * events arriving before then will be delayed until then.
  358. */
  359. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  360. monitor_qapi_event_emit(event, qdict);
  361. evstate = g_new(MonitorQAPIEventState, 1);
  362. evstate->event = event;
  363. evstate->data = qobject_ref(data);
  364. evstate->qdict = NULL;
  365. evstate->timer = timer_new_ns(monitor_get_event_clock(),
  366. monitor_qapi_event_handler,
  367. evstate);
  368. g_hash_table_add(monitor_qapi_event_state, evstate);
  369. timer_mod_ns(evstate->timer, now + evconf->rate);
  370. }
  371. }
  372. }
  373. void qapi_event_emit(QAPIEvent event, QDict *qdict)
  374. {
  375. /*
  376. * monitor_qapi_event_queue_no_reenter() is not reentrant: it
  377. * would deadlock on monitor_lock. Work around by queueing
  378. * events in thread-local storage.
  379. * TODO: remove this, make it re-enter safe.
  380. */
  381. typedef struct MonitorQapiEvent {
  382. QAPIEvent event;
  383. QDict *qdict;
  384. QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
  385. } MonitorQapiEvent;
  386. static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
  387. static __thread bool reentered;
  388. MonitorQapiEvent *ev;
  389. if (!reentered) {
  390. QSIMPLEQ_INIT(&event_queue);
  391. }
  392. ev = g_new(MonitorQapiEvent, 1);
  393. ev->qdict = qobject_ref(qdict);
  394. ev->event = event;
  395. QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
  396. if (reentered) {
  397. return;
  398. }
  399. reentered = true;
  400. while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
  401. QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
  402. monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
  403. qobject_unref(ev->qdict);
  404. g_free(ev);
  405. }
  406. reentered = false;
  407. }
  408. /*
  409. * This function runs evconf->rate ns after sending a throttled
  410. * event.
  411. * If another event has since been stored, send it.
  412. */
  413. static void monitor_qapi_event_handler(void *opaque)
  414. {
  415. MonitorQAPIEventState *evstate = opaque;
  416. MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
  417. trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
  418. QEMU_LOCK_GUARD(&monitor_lock);
  419. if (evstate->qdict) {
  420. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  421. monitor_qapi_event_emit(evstate->event, evstate->qdict);
  422. qobject_unref(evstate->qdict);
  423. evstate->qdict = NULL;
  424. timer_mod_ns(evstate->timer, now + evconf->rate);
  425. } else {
  426. g_hash_table_remove(monitor_qapi_event_state, evstate);
  427. qobject_unref(evstate->data);
  428. timer_free(evstate->timer);
  429. g_free(evstate);
  430. }
  431. }
  432. static unsigned int qapi_event_throttle_hash(const void *key)
  433. {
  434. const MonitorQAPIEventState *evstate = key;
  435. unsigned int hash = evstate->event * 255;
  436. if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
  437. hash += g_str_hash(qdict_get_str(evstate->data, "id"));
  438. }
  439. if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  440. hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
  441. }
  442. if (evstate->event == QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE) {
  443. hash += g_str_hash(qdict_get_str(evstate->data, "qom-path"));
  444. }
  445. return hash;
  446. }
  447. static gboolean qapi_event_throttle_equal(const void *a, const void *b)
  448. {
  449. const MonitorQAPIEventState *eva = a;
  450. const MonitorQAPIEventState *evb = b;
  451. if (eva->event != evb->event) {
  452. return FALSE;
  453. }
  454. if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
  455. return !strcmp(qdict_get_str(eva->data, "id"),
  456. qdict_get_str(evb->data, "id"));
  457. }
  458. if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  459. return !strcmp(qdict_get_str(eva->data, "node-name"),
  460. qdict_get_str(evb->data, "node-name"));
  461. }
  462. if (eva->event == QAPI_EVENT_MEMORY_DEVICE_SIZE_CHANGE) {
  463. return !strcmp(qdict_get_str(eva->data, "qom-path"),
  464. qdict_get_str(evb->data, "qom-path"));
  465. }
  466. return TRUE;
  467. }
  468. int monitor_suspend(Monitor *mon)
  469. {
  470. if (monitor_is_hmp_non_interactive(mon)) {
  471. return -ENOTTY;
  472. }
  473. qatomic_inc(&mon->suspend_cnt);
  474. if (mon->use_io_thread) {
  475. /*
  476. * Kick I/O thread to make sure this takes effect. It'll be
  477. * evaluated again in prepare() of the watch object.
  478. */
  479. aio_notify(iothread_get_aio_context(mon_iothread));
  480. }
  481. trace_monitor_suspend(mon, 1);
  482. return 0;
  483. }
  484. static void monitor_accept_input(void *opaque)
  485. {
  486. Monitor *mon = opaque;
  487. qemu_chr_fe_accept_input(&mon->chr);
  488. }
  489. void monitor_resume(Monitor *mon)
  490. {
  491. if (monitor_is_hmp_non_interactive(mon)) {
  492. return;
  493. }
  494. if (qatomic_dec_fetch(&mon->suspend_cnt) == 0) {
  495. AioContext *ctx;
  496. if (mon->use_io_thread) {
  497. ctx = iothread_get_aio_context(mon_iothread);
  498. } else {
  499. ctx = qemu_get_aio_context();
  500. }
  501. if (!monitor_is_qmp(mon)) {
  502. MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
  503. assert(hmp_mon->rs);
  504. readline_show_prompt(hmp_mon->rs);
  505. }
  506. aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
  507. }
  508. trace_monitor_suspend(mon, -1);
  509. }
  510. int monitor_can_read(void *opaque)
  511. {
  512. Monitor *mon = opaque;
  513. return !qatomic_mb_read(&mon->suspend_cnt);
  514. }
  515. void monitor_list_append(Monitor *mon)
  516. {
  517. qemu_mutex_lock(&monitor_lock);
  518. /*
  519. * This prevents inserting new monitors during monitor_cleanup().
  520. * A cleaner solution would involve the main thread telling other
  521. * threads to terminate, waiting for their termination.
  522. */
  523. if (!monitor_destroyed) {
  524. QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
  525. mon = NULL;
  526. }
  527. qemu_mutex_unlock(&monitor_lock);
  528. if (mon) {
  529. monitor_data_destroy(mon);
  530. g_free(mon);
  531. }
  532. }
  533. static void monitor_iothread_init(void)
  534. {
  535. mon_iothread = iothread_create("mon_iothread", &error_abort);
  536. }
  537. void monitor_data_init(Monitor *mon, bool is_qmp, bool skip_flush,
  538. bool use_io_thread)
  539. {
  540. if (use_io_thread && !mon_iothread) {
  541. monitor_iothread_init();
  542. }
  543. qemu_mutex_init(&mon->mon_lock);
  544. mon->is_qmp = is_qmp;
  545. mon->outbuf = g_string_new(NULL);
  546. mon->skip_flush = skip_flush;
  547. mon->use_io_thread = use_io_thread;
  548. }
  549. void monitor_data_destroy(Monitor *mon)
  550. {
  551. g_free(mon->mon_cpu_path);
  552. qemu_chr_fe_deinit(&mon->chr, false);
  553. if (monitor_is_qmp(mon)) {
  554. monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
  555. } else {
  556. readline_free(container_of(mon, MonitorHMP, common)->rs);
  557. }
  558. g_string_free(mon->outbuf, true);
  559. qemu_mutex_destroy(&mon->mon_lock);
  560. }
  561. void monitor_cleanup(void)
  562. {
  563. /*
  564. * The dispatcher needs to stop before destroying the monitor and
  565. * the I/O thread.
  566. *
  567. * We need to poll both qemu_aio_context and iohandler_ctx to make
  568. * sure that the dispatcher coroutine keeps making progress and
  569. * eventually terminates. qemu_aio_context is automatically
  570. * polled by calling AIO_WAIT_WHILE on it, but we must poll
  571. * iohandler_ctx manually.
  572. *
  573. * Letting the iothread continue while shutting down the dispatcher
  574. * means that new requests may still be coming in. This is okay,
  575. * we'll just leave them in the queue without sending a response
  576. * and monitor_data_destroy() will free them.
  577. */
  578. qmp_dispatcher_co_shutdown = true;
  579. if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
  580. aio_co_wake(qmp_dispatcher_co);
  581. }
  582. AIO_WAIT_WHILE(qemu_get_aio_context(),
  583. (aio_poll(iohandler_get_aio_context(), false),
  584. qatomic_mb_read(&qmp_dispatcher_co_busy)));
  585. /*
  586. * We need to explicitly stop the I/O thread (but not destroy it),
  587. * clean up the monitor resources, then destroy the I/O thread since
  588. * we need to unregister from chardev below in
  589. * monitor_data_destroy(), and chardev is not thread-safe yet
  590. */
  591. if (mon_iothread) {
  592. iothread_stop(mon_iothread);
  593. }
  594. /* Flush output buffers and destroy monitors */
  595. qemu_mutex_lock(&monitor_lock);
  596. monitor_destroyed = true;
  597. while (!QTAILQ_EMPTY(&mon_list)) {
  598. Monitor *mon = QTAILQ_FIRST(&mon_list);
  599. QTAILQ_REMOVE(&mon_list, mon, entry);
  600. /* Permit QAPI event emission from character frontend release */
  601. qemu_mutex_unlock(&monitor_lock);
  602. monitor_flush(mon);
  603. monitor_data_destroy(mon);
  604. qemu_mutex_lock(&monitor_lock);
  605. g_free(mon);
  606. }
  607. qemu_mutex_unlock(&monitor_lock);
  608. if (mon_iothread) {
  609. iothread_destroy(mon_iothread);
  610. mon_iothread = NULL;
  611. }
  612. }
  613. static void monitor_qapi_event_init(void)
  614. {
  615. monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
  616. qapi_event_throttle_equal);
  617. }
  618. void monitor_init_globals(void)
  619. {
  620. monitor_qapi_event_init();
  621. qemu_mutex_init(&monitor_lock);
  622. coroutine_mon = g_hash_table_new(NULL, NULL);
  623. /*
  624. * The dispatcher BH must run in the main loop thread, since we
  625. * have commands assuming that context. It would be nice to get
  626. * rid of those assumptions.
  627. */
  628. qmp_dispatcher_co = qemu_coroutine_create(monitor_qmp_dispatcher_co, NULL);
  629. qatomic_mb_set(&qmp_dispatcher_co_busy, true);
  630. aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
  631. }
  632. int monitor_init(MonitorOptions *opts, bool allow_hmp, Error **errp)
  633. {
  634. ERRP_GUARD();
  635. Chardev *chr;
  636. chr = qemu_chr_find(opts->chardev);
  637. if (chr == NULL) {
  638. error_setg(errp, "chardev \"%s\" not found", opts->chardev);
  639. return -1;
  640. }
  641. if (!opts->has_mode) {
  642. opts->mode = allow_hmp ? MONITOR_MODE_READLINE : MONITOR_MODE_CONTROL;
  643. }
  644. switch (opts->mode) {
  645. case MONITOR_MODE_CONTROL:
  646. monitor_init_qmp(chr, opts->pretty, errp);
  647. break;
  648. case MONITOR_MODE_READLINE:
  649. if (!allow_hmp) {
  650. error_setg(errp, "Only QMP is supported");
  651. return -1;
  652. }
  653. if (opts->pretty) {
  654. error_setg(errp, "'pretty' is not compatible with HMP monitors");
  655. return -1;
  656. }
  657. monitor_init_hmp(chr, true, errp);
  658. break;
  659. default:
  660. g_assert_not_reached();
  661. }
  662. return *errp ? -1 : 0;
  663. }
  664. int monitor_init_opts(QemuOpts *opts, Error **errp)
  665. {
  666. Visitor *v;
  667. MonitorOptions *options;
  668. int ret;
  669. v = opts_visitor_new(opts);
  670. visit_type_MonitorOptions(v, NULL, &options, errp);
  671. visit_free(v);
  672. if (!options) {
  673. return -1;
  674. }
  675. ret = monitor_init(options, true, errp);
  676. qapi_free_MonitorOptions(options);
  677. return ret;
  678. }
  679. QemuOptsList qemu_mon_opts = {
  680. .name = "mon",
  681. .implied_opt_name = "chardev",
  682. .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
  683. .desc = {
  684. {
  685. .name = "mode",
  686. .type = QEMU_OPT_STRING,
  687. },{
  688. .name = "chardev",
  689. .type = QEMU_OPT_STRING,
  690. },{
  691. .name = "pretty",
  692. .type = QEMU_OPT_BOOL,
  693. },
  694. { /* end of list */ }
  695. },
  696. };