monitor.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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/qapi-emit-events.h"
  28. #include "qapi/qmp/qdict.h"
  29. #include "qapi/qmp/qstring.h"
  30. #include "qemu/error-report.h"
  31. #include "qemu/option.h"
  32. #include "sysemu/qtest.h"
  33. #include "sysemu/sysemu.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. /* Bottom half to dispatch the requests received from I/O thread */
  52. QEMUBH *qmp_dispatcher_bh;
  53. /* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */
  54. QemuMutex monitor_lock;
  55. static GHashTable *monitor_qapi_event_state;
  56. MonitorList mon_list;
  57. int mon_refcount;
  58. static bool monitor_destroyed;
  59. __thread Monitor *cur_mon;
  60. /**
  61. * Is the current monitor, if any, a QMP monitor?
  62. */
  63. bool monitor_cur_is_qmp(void)
  64. {
  65. return cur_mon && monitor_is_qmp(cur_mon);
  66. }
  67. /**
  68. * Is @mon is using readline?
  69. * Note: not all HMP monitors use readline, e.g., gdbserver has a
  70. * non-interactive HMP monitor, so readline is not used there.
  71. */
  72. static inline bool monitor_uses_readline(const MonitorHMP *mon)
  73. {
  74. return mon->use_readline;
  75. }
  76. static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
  77. {
  78. if (monitor_is_qmp(mon)) {
  79. return false;
  80. }
  81. return !monitor_uses_readline(container_of(mon, MonitorHMP, common));
  82. }
  83. static void monitor_flush_locked(Monitor *mon);
  84. static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
  85. void *opaque)
  86. {
  87. Monitor *mon = opaque;
  88. qemu_mutex_lock(&mon->mon_lock);
  89. mon->out_watch = 0;
  90. monitor_flush_locked(mon);
  91. qemu_mutex_unlock(&mon->mon_lock);
  92. return FALSE;
  93. }
  94. /* Caller must hold mon->mon_lock */
  95. static void monitor_flush_locked(Monitor *mon)
  96. {
  97. int rc;
  98. size_t len;
  99. const char *buf;
  100. if (mon->skip_flush) {
  101. return;
  102. }
  103. buf = qstring_get_str(mon->outbuf);
  104. len = qstring_get_length(mon->outbuf);
  105. if (len && !mon->mux_out) {
  106. rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
  107. if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
  108. /* all flushed or error */
  109. qobject_unref(mon->outbuf);
  110. mon->outbuf = qstring_new();
  111. return;
  112. }
  113. if (rc > 0) {
  114. /* partial write */
  115. QString *tmp = qstring_from_str(buf + rc);
  116. qobject_unref(mon->outbuf);
  117. mon->outbuf = tmp;
  118. }
  119. if (mon->out_watch == 0) {
  120. mon->out_watch =
  121. qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
  122. monitor_unblocked, mon);
  123. }
  124. }
  125. }
  126. void monitor_flush(Monitor *mon)
  127. {
  128. qemu_mutex_lock(&mon->mon_lock);
  129. monitor_flush_locked(mon);
  130. qemu_mutex_unlock(&mon->mon_lock);
  131. }
  132. /* flush at every end of line */
  133. int monitor_puts(Monitor *mon, const char *str)
  134. {
  135. int i;
  136. char c;
  137. qemu_mutex_lock(&mon->mon_lock);
  138. for (i = 0; str[i]; i++) {
  139. c = str[i];
  140. if (c == '\n') {
  141. qstring_append_chr(mon->outbuf, '\r');
  142. }
  143. qstring_append_chr(mon->outbuf, c);
  144. if (c == '\n') {
  145. monitor_flush_locked(mon);
  146. }
  147. }
  148. qemu_mutex_unlock(&mon->mon_lock);
  149. return i;
  150. }
  151. int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
  152. {
  153. char *buf;
  154. int n;
  155. if (!mon) {
  156. return -1;
  157. }
  158. if (monitor_is_qmp(mon)) {
  159. return -1;
  160. }
  161. buf = g_strdup_vprintf(fmt, ap);
  162. n = monitor_puts(mon, buf);
  163. g_free(buf);
  164. return n;
  165. }
  166. int monitor_printf(Monitor *mon, const char *fmt, ...)
  167. {
  168. int ret;
  169. va_list ap;
  170. va_start(ap, fmt);
  171. ret = monitor_vprintf(mon, fmt, ap);
  172. va_end(ap);
  173. return ret;
  174. }
  175. /*
  176. * Print to current monitor if we have one, else to stderr.
  177. */
  178. int error_vprintf(const char *fmt, va_list ap)
  179. {
  180. if (cur_mon && !monitor_cur_is_qmp()) {
  181. return monitor_vprintf(cur_mon, fmt, ap);
  182. }
  183. return vfprintf(stderr, fmt, ap);
  184. }
  185. int error_vprintf_unless_qmp(const char *fmt, va_list ap)
  186. {
  187. if (!cur_mon) {
  188. return vfprintf(stderr, fmt, ap);
  189. }
  190. if (!monitor_cur_is_qmp()) {
  191. return monitor_vprintf(cur_mon, fmt, ap);
  192. }
  193. return -1;
  194. }
  195. static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
  196. /* Limit guest-triggerable events to 1 per second */
  197. [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
  198. [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
  199. [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
  200. [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
  201. [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
  202. [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
  203. };
  204. /*
  205. * Return the clock to use for recording an event's time.
  206. * It's QEMU_CLOCK_REALTIME, except for qtests it's
  207. * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
  208. * Beware: result is invalid before configure_accelerator().
  209. */
  210. static inline QEMUClockType monitor_get_event_clock(void)
  211. {
  212. return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
  213. }
  214. /*
  215. * Broadcast an event to all monitors.
  216. * @qdict is the event object. Its member "event" must match @event.
  217. * Caller must hold monitor_lock.
  218. */
  219. static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
  220. {
  221. Monitor *mon;
  222. MonitorQMP *qmp_mon;
  223. trace_monitor_protocol_event_emit(event, qdict);
  224. QTAILQ_FOREACH(mon, &mon_list, entry) {
  225. if (!monitor_is_qmp(mon)) {
  226. continue;
  227. }
  228. qmp_mon = container_of(mon, MonitorQMP, common);
  229. if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
  230. qmp_send_response(qmp_mon, qdict);
  231. }
  232. }
  233. }
  234. static void monitor_qapi_event_handler(void *opaque);
  235. /*
  236. * Queue a new event for emission to Monitor instances,
  237. * applying any rate limiting if required.
  238. */
  239. static void
  240. monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
  241. {
  242. MonitorQAPIEventConf *evconf;
  243. MonitorQAPIEventState *evstate;
  244. assert(event < QAPI_EVENT__MAX);
  245. evconf = &monitor_qapi_event_conf[event];
  246. trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
  247. qemu_mutex_lock(&monitor_lock);
  248. if (!evconf->rate) {
  249. /* Unthrottled event */
  250. monitor_qapi_event_emit(event, qdict);
  251. } else {
  252. QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
  253. MonitorQAPIEventState key = { .event = event, .data = data };
  254. evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
  255. assert(!evstate || timer_pending(evstate->timer));
  256. if (evstate) {
  257. /*
  258. * Timer is pending for (at least) evconf->rate ns after
  259. * last send. Store event for sending when timer fires,
  260. * replacing a prior stored event if any.
  261. */
  262. qobject_unref(evstate->qdict);
  263. evstate->qdict = qobject_ref(qdict);
  264. } else {
  265. /*
  266. * Last send was (at least) evconf->rate ns ago.
  267. * Send immediately, and arm the timer to call
  268. * monitor_qapi_event_handler() in evconf->rate ns. Any
  269. * events arriving before then will be delayed until then.
  270. */
  271. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  272. monitor_qapi_event_emit(event, qdict);
  273. evstate = g_new(MonitorQAPIEventState, 1);
  274. evstate->event = event;
  275. evstate->data = qobject_ref(data);
  276. evstate->qdict = NULL;
  277. evstate->timer = timer_new_ns(monitor_get_event_clock(),
  278. monitor_qapi_event_handler,
  279. evstate);
  280. g_hash_table_add(monitor_qapi_event_state, evstate);
  281. timer_mod_ns(evstate->timer, now + evconf->rate);
  282. }
  283. }
  284. qemu_mutex_unlock(&monitor_lock);
  285. }
  286. void qapi_event_emit(QAPIEvent event, QDict *qdict)
  287. {
  288. /*
  289. * monitor_qapi_event_queue_no_reenter() is not reentrant: it
  290. * would deadlock on monitor_lock. Work around by queueing
  291. * events in thread-local storage.
  292. * TODO: remove this, make it re-enter safe.
  293. */
  294. typedef struct MonitorQapiEvent {
  295. QAPIEvent event;
  296. QDict *qdict;
  297. QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
  298. } MonitorQapiEvent;
  299. static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
  300. static __thread bool reentered;
  301. MonitorQapiEvent *ev;
  302. if (!reentered) {
  303. QSIMPLEQ_INIT(&event_queue);
  304. }
  305. ev = g_new(MonitorQapiEvent, 1);
  306. ev->qdict = qobject_ref(qdict);
  307. ev->event = event;
  308. QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
  309. if (reentered) {
  310. return;
  311. }
  312. reentered = true;
  313. while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
  314. QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
  315. monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
  316. qobject_unref(ev->qdict);
  317. g_free(ev);
  318. }
  319. reentered = false;
  320. }
  321. /*
  322. * This function runs evconf->rate ns after sending a throttled
  323. * event.
  324. * If another event has since been stored, send it.
  325. */
  326. static void monitor_qapi_event_handler(void *opaque)
  327. {
  328. MonitorQAPIEventState *evstate = opaque;
  329. MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
  330. trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
  331. qemu_mutex_lock(&monitor_lock);
  332. if (evstate->qdict) {
  333. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  334. monitor_qapi_event_emit(evstate->event, evstate->qdict);
  335. qobject_unref(evstate->qdict);
  336. evstate->qdict = NULL;
  337. timer_mod_ns(evstate->timer, now + evconf->rate);
  338. } else {
  339. g_hash_table_remove(monitor_qapi_event_state, evstate);
  340. qobject_unref(evstate->data);
  341. timer_free(evstate->timer);
  342. g_free(evstate);
  343. }
  344. qemu_mutex_unlock(&monitor_lock);
  345. }
  346. static unsigned int qapi_event_throttle_hash(const void *key)
  347. {
  348. const MonitorQAPIEventState *evstate = key;
  349. unsigned int hash = evstate->event * 255;
  350. if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
  351. hash += g_str_hash(qdict_get_str(evstate->data, "id"));
  352. }
  353. if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  354. hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
  355. }
  356. return hash;
  357. }
  358. static gboolean qapi_event_throttle_equal(const void *a, const void *b)
  359. {
  360. const MonitorQAPIEventState *eva = a;
  361. const MonitorQAPIEventState *evb = b;
  362. if (eva->event != evb->event) {
  363. return FALSE;
  364. }
  365. if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
  366. return !strcmp(qdict_get_str(eva->data, "id"),
  367. qdict_get_str(evb->data, "id"));
  368. }
  369. if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  370. return !strcmp(qdict_get_str(eva->data, "node-name"),
  371. qdict_get_str(evb->data, "node-name"));
  372. }
  373. return TRUE;
  374. }
  375. int monitor_suspend(Monitor *mon)
  376. {
  377. if (monitor_is_hmp_non_interactive(mon)) {
  378. return -ENOTTY;
  379. }
  380. atomic_inc(&mon->suspend_cnt);
  381. if (mon->use_io_thread) {
  382. /*
  383. * Kick I/O thread to make sure this takes effect. It'll be
  384. * evaluated again in prepare() of the watch object.
  385. */
  386. aio_notify(iothread_get_aio_context(mon_iothread));
  387. }
  388. trace_monitor_suspend(mon, 1);
  389. return 0;
  390. }
  391. static void monitor_accept_input(void *opaque)
  392. {
  393. Monitor *mon = opaque;
  394. qemu_chr_fe_accept_input(&mon->chr);
  395. }
  396. void monitor_resume(Monitor *mon)
  397. {
  398. if (monitor_is_hmp_non_interactive(mon)) {
  399. return;
  400. }
  401. if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
  402. AioContext *ctx;
  403. if (mon->use_io_thread) {
  404. ctx = iothread_get_aio_context(mon_iothread);
  405. } else {
  406. ctx = qemu_get_aio_context();
  407. }
  408. if (!monitor_is_qmp(mon)) {
  409. MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
  410. assert(hmp_mon->rs);
  411. readline_show_prompt(hmp_mon->rs);
  412. }
  413. aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
  414. }
  415. trace_monitor_suspend(mon, -1);
  416. }
  417. int monitor_can_read(void *opaque)
  418. {
  419. Monitor *mon = opaque;
  420. return !atomic_mb_read(&mon->suspend_cnt);
  421. }
  422. void monitor_list_append(Monitor *mon)
  423. {
  424. qemu_mutex_lock(&monitor_lock);
  425. /*
  426. * This prevents inserting new monitors during monitor_cleanup().
  427. * A cleaner solution would involve the main thread telling other
  428. * threads to terminate, waiting for their termination.
  429. */
  430. if (!monitor_destroyed) {
  431. QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
  432. mon = NULL;
  433. }
  434. qemu_mutex_unlock(&monitor_lock);
  435. if (mon) {
  436. monitor_data_destroy(mon);
  437. g_free(mon);
  438. }
  439. }
  440. static void monitor_iothread_init(void)
  441. {
  442. mon_iothread = iothread_create("mon_iothread", &error_abort);
  443. }
  444. void monitor_data_init(Monitor *mon, bool is_qmp, bool skip_flush,
  445. bool use_io_thread)
  446. {
  447. if (use_io_thread && !mon_iothread) {
  448. monitor_iothread_init();
  449. }
  450. qemu_mutex_init(&mon->mon_lock);
  451. mon->is_qmp = is_qmp;
  452. mon->outbuf = qstring_new();
  453. mon->skip_flush = skip_flush;
  454. mon->use_io_thread = use_io_thread;
  455. }
  456. void monitor_data_destroy(Monitor *mon)
  457. {
  458. g_free(mon->mon_cpu_path);
  459. qemu_chr_fe_deinit(&mon->chr, false);
  460. if (monitor_is_qmp(mon)) {
  461. monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
  462. } else {
  463. readline_free(container_of(mon, MonitorHMP, common)->rs);
  464. }
  465. qobject_unref(mon->outbuf);
  466. qemu_mutex_destroy(&mon->mon_lock);
  467. }
  468. void monitor_cleanup(void)
  469. {
  470. /*
  471. * We need to explicitly stop the I/O thread (but not destroy it),
  472. * clean up the monitor resources, then destroy the I/O thread since
  473. * we need to unregister from chardev below in
  474. * monitor_data_destroy(), and chardev is not thread-safe yet
  475. */
  476. if (mon_iothread) {
  477. iothread_stop(mon_iothread);
  478. }
  479. /* Flush output buffers and destroy monitors */
  480. qemu_mutex_lock(&monitor_lock);
  481. monitor_destroyed = true;
  482. while (!QTAILQ_EMPTY(&mon_list)) {
  483. Monitor *mon = QTAILQ_FIRST(&mon_list);
  484. QTAILQ_REMOVE(&mon_list, mon, entry);
  485. /* Permit QAPI event emission from character frontend release */
  486. qemu_mutex_unlock(&monitor_lock);
  487. monitor_flush(mon);
  488. monitor_data_destroy(mon);
  489. qemu_mutex_lock(&monitor_lock);
  490. g_free(mon);
  491. }
  492. qemu_mutex_unlock(&monitor_lock);
  493. /* QEMUBHs needs to be deleted before destroying the I/O thread */
  494. qemu_bh_delete(qmp_dispatcher_bh);
  495. qmp_dispatcher_bh = NULL;
  496. if (mon_iothread) {
  497. iothread_destroy(mon_iothread);
  498. mon_iothread = NULL;
  499. }
  500. }
  501. static void monitor_qapi_event_init(void)
  502. {
  503. monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
  504. qapi_event_throttle_equal);
  505. }
  506. void monitor_init_globals_core(void)
  507. {
  508. monitor_qapi_event_init();
  509. qemu_mutex_init(&monitor_lock);
  510. /*
  511. * The dispatcher BH must run in the main loop thread, since we
  512. * have commands assuming that context. It would be nice to get
  513. * rid of those assumptions.
  514. */
  515. qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
  516. monitor_qmp_bh_dispatcher,
  517. NULL);
  518. }
  519. QemuOptsList qemu_mon_opts = {
  520. .name = "mon",
  521. .implied_opt_name = "chardev",
  522. .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
  523. .desc = {
  524. {
  525. .name = "mode",
  526. .type = QEMU_OPT_STRING,
  527. },{
  528. .name = "chardev",
  529. .type = QEMU_OPT_STRING,
  530. },{
  531. .name = "pretty",
  532. .type = QEMU_OPT_BOOL,
  533. },
  534. { /* end of list */ }
  535. },
  536. };