qmp.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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 "chardev/char-io.h"
  26. #include "monitor-internal.h"
  27. #include "qapi/error.h"
  28. #include "qapi/qapi-commands-control.h"
  29. #include "qobject/qdict.h"
  30. #include "qobject/qjson.h"
  31. #include "qobject/qlist.h"
  32. #include "trace.h"
  33. /*
  34. * qmp_dispatcher_co_busy is used for synchronisation between the
  35. * monitor thread and the main thread to ensure that the dispatcher
  36. * coroutine never gets scheduled a second time when it's already
  37. * scheduled (scheduling the same coroutine twice is forbidden).
  38. *
  39. * It is true if the coroutine will process at least one more request
  40. * before going to sleep. Either it has been kicked already, or it
  41. * is active and processing requests. Additional requests may therefore
  42. * be pushed onto mon->qmp_requests, and @qmp_dispatcher_co_shutdown may
  43. * be set without further ado. @qmp_dispatcher_co must not be woken up
  44. * in this case.
  45. *
  46. * If false, you have to wake up @qmp_dispatcher_co after pushing new
  47. * requests. You also have to set @qmp_dispatcher_co_busy to true
  48. * before waking up the coroutine.
  49. *
  50. * The coroutine will automatically change this variable back to false
  51. * before it yields. Nobody else may set the variable to false.
  52. *
  53. * Access must be atomic for thread safety.
  54. */
  55. static bool qmp_dispatcher_co_busy = true;
  56. struct QMPRequest {
  57. /* Owner of the request */
  58. MonitorQMP *mon;
  59. /*
  60. * Request object to be handled or Error to be reported
  61. * (exactly one of them is non-null)
  62. */
  63. QObject *req;
  64. Error *err;
  65. };
  66. typedef struct QMPRequest QMPRequest;
  67. QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
  68. static bool qmp_oob_enabled(MonitorQMP *mon)
  69. {
  70. return mon->capab[QMP_CAPABILITY_OOB];
  71. }
  72. static void monitor_qmp_caps_reset(MonitorQMP *mon)
  73. {
  74. memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
  75. memset(mon->capab, 0, sizeof(mon->capab));
  76. mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
  77. }
  78. static void qmp_request_free(QMPRequest *req)
  79. {
  80. qobject_unref(req->req);
  81. error_free(req->err);
  82. g_free(req);
  83. }
  84. /* Caller must hold mon->qmp.qmp_queue_lock */
  85. static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
  86. {
  87. while (!g_queue_is_empty(mon->qmp_requests)) {
  88. qmp_request_free(g_queue_pop_head(mon->qmp_requests));
  89. }
  90. }
  91. static void monitor_qmp_cleanup_queue_and_resume(MonitorQMP *mon)
  92. {
  93. QEMU_LOCK_GUARD(&mon->qmp_queue_lock);
  94. /*
  95. * Same condition as in monitor_qmp_dispatcher_co(), but before
  96. * removing an element from the queue (hence no `- 1`).
  97. * Also, the queue should not be empty either, otherwise the
  98. * monitor hasn't been suspended yet (or was already resumed).
  99. */
  100. bool need_resume = (!qmp_oob_enabled(mon) ||
  101. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX)
  102. && !g_queue_is_empty(mon->qmp_requests);
  103. monitor_qmp_cleanup_req_queue_locked(mon);
  104. if (need_resume) {
  105. /*
  106. * handle_qmp_command() suspended the monitor because the
  107. * request queue filled up, to be resumed when the queue has
  108. * space again. We just emptied it; resume the monitor.
  109. *
  110. * Without this, the monitor would remain suspended forever
  111. * when we get here while the monitor is suspended. An
  112. * unfortunately timed CHR_EVENT_CLOSED can do the trick.
  113. */
  114. monitor_resume(&mon->common);
  115. }
  116. }
  117. void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
  118. {
  119. const QObject *data = QOBJECT(rsp);
  120. GString *json;
  121. json = qobject_to_json_pretty(data, mon->pretty);
  122. assert(json != NULL);
  123. trace_monitor_qmp_respond(mon, json->str);
  124. g_string_append_c(json, '\n');
  125. monitor_puts(&mon->common, json->str);
  126. g_string_free(json, true);
  127. }
  128. /*
  129. * Emit QMP response @rsp to @mon.
  130. * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
  131. * Nothing is emitted then.
  132. */
  133. static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
  134. {
  135. if (rsp) {
  136. qmp_send_response(mon, rsp);
  137. }
  138. }
  139. /*
  140. * Runs outside of coroutine context for OOB commands, but in
  141. * coroutine context for everything else.
  142. */
  143. static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
  144. {
  145. QDict *rsp;
  146. QDict *error;
  147. rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon),
  148. &mon->common);
  149. if (mon->commands == &qmp_cap_negotiation_commands) {
  150. error = qdict_get_qdict(rsp, "error");
  151. if (error
  152. && !g_strcmp0(qdict_get_try_str(error, "class"),
  153. QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
  154. /* Provide a more useful error message */
  155. qdict_del(error, "desc");
  156. qdict_put_str(error, "desc", "Expecting capabilities negotiation"
  157. " with 'qmp_capabilities'");
  158. }
  159. }
  160. monitor_qmp_respond(mon, rsp);
  161. qobject_unref(rsp);
  162. }
  163. /*
  164. * Pop a QMP request from a monitor request queue.
  165. * Return the request, or NULL all request queues are empty.
  166. * We are using round-robin fashion to pop the request, to avoid
  167. * processing commands only on a very busy monitor. To achieve that,
  168. * when we process one request on a specific monitor, we put that
  169. * monitor to the end of mon_list queue.
  170. *
  171. * Note: if the function returned with non-NULL, then the caller will
  172. * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
  173. * to release it.
  174. */
  175. static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
  176. {
  177. QMPRequest *req_obj = NULL;
  178. Monitor *mon;
  179. MonitorQMP *qmp_mon;
  180. QTAILQ_FOREACH(mon, &mon_list, entry) {
  181. if (!monitor_is_qmp(mon)) {
  182. continue;
  183. }
  184. qmp_mon = container_of(mon, MonitorQMP, common);
  185. qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
  186. req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
  187. if (req_obj) {
  188. /* With the lock of corresponding queue held */
  189. break;
  190. }
  191. qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
  192. }
  193. if (req_obj) {
  194. /*
  195. * We found one request on the monitor. Degrade this monitor's
  196. * priority to lowest by re-inserting it to end of queue.
  197. */
  198. QTAILQ_REMOVE(&mon_list, mon, entry);
  199. QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
  200. }
  201. return req_obj;
  202. }
  203. static QMPRequest *monitor_qmp_dispatcher_pop_any(void)
  204. {
  205. while (true) {
  206. /*
  207. * To avoid double scheduling, busy is true on entry to
  208. * monitor_qmp_dispatcher_co(), and must be set again before
  209. * aio_co_wake()-ing it.
  210. */
  211. assert(qatomic_read(&qmp_dispatcher_co_busy) == true);
  212. /*
  213. * Mark the dispatcher as not busy already here so that we
  214. * don't miss any new requests coming in the middle of our
  215. * processing.
  216. *
  217. * Clear qmp_dispatcher_co_busy before reading request.
  218. */
  219. qatomic_set_mb(&qmp_dispatcher_co_busy, false);
  220. WITH_QEMU_LOCK_GUARD(&monitor_lock) {
  221. QMPRequest *req_obj;
  222. /* On shutdown, don't take any more requests from the queue */
  223. if (qmp_dispatcher_co_shutdown) {
  224. return NULL;
  225. }
  226. req_obj = monitor_qmp_requests_pop_any_with_lock();
  227. if (req_obj) {
  228. return req_obj;
  229. }
  230. }
  231. /*
  232. * No more requests to process. Wait to be reentered from
  233. * handle_qmp_command() when it pushes more requests, or
  234. * from monitor_cleanup() when it requests shutdown.
  235. */
  236. qemu_coroutine_yield();
  237. }
  238. }
  239. void coroutine_fn monitor_qmp_dispatcher_co(void *data)
  240. {
  241. QMPRequest *req_obj;
  242. QDict *rsp;
  243. bool oob_enabled;
  244. MonitorQMP *mon;
  245. while ((req_obj = monitor_qmp_dispatcher_pop_any()) != NULL) {
  246. trace_monitor_qmp_in_band_dequeue(req_obj,
  247. req_obj->mon->qmp_requests->length);
  248. /*
  249. * @req_obj has a request, we hold req_obj->mon->qmp_queue_lock
  250. */
  251. mon = req_obj->mon;
  252. /*
  253. * We need to resume the monitor if handle_qmp_command()
  254. * suspended it. Two cases:
  255. * 1. OOB enabled: mon->qmp_requests has no more space
  256. * Resume right away, so that OOB commands can get executed while
  257. * this request is being processed.
  258. * 2. OOB disabled: always
  259. * Resume only after we're done processing the request,
  260. * We need to save qmp_oob_enabled() for later, because
  261. * qmp_qmp_capabilities() can change it.
  262. */
  263. oob_enabled = qmp_oob_enabled(mon);
  264. if (oob_enabled
  265. && mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
  266. monitor_resume(&mon->common);
  267. }
  268. /*
  269. * Drop the queue mutex now, before yielding, otherwise we might
  270. * deadlock if the main thread tries to lock it.
  271. */
  272. qemu_mutex_unlock(&mon->qmp_queue_lock);
  273. if (qatomic_xchg(&qmp_dispatcher_co_busy, true) == true) {
  274. /*
  275. * Someone rescheduled us (probably because a new requests
  276. * came in), but we didn't actually yield. Do that now,
  277. * only to be immediately reentered and removed from the
  278. * list of scheduled coroutines.
  279. */
  280. qemu_coroutine_yield();
  281. }
  282. /* Process request */
  283. if (req_obj->req) {
  284. if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_IN_BAND)) {
  285. QDict *qdict = qobject_to(QDict, req_obj->req);
  286. QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
  287. GString *id_json;
  288. id_json = id ? qobject_to_json(id) : g_string_new(NULL);
  289. trace_monitor_qmp_cmd_in_band(id_json->str);
  290. g_string_free(id_json, true);
  291. }
  292. monitor_qmp_dispatch(mon, req_obj->req);
  293. } else {
  294. assert(req_obj->err);
  295. trace_monitor_qmp_err_in_band(error_get_pretty(req_obj->err));
  296. rsp = qmp_error_response(req_obj->err);
  297. req_obj->err = NULL;
  298. monitor_qmp_respond(mon, rsp);
  299. qobject_unref(rsp);
  300. }
  301. if (!oob_enabled) {
  302. monitor_resume(&mon->common);
  303. }
  304. qmp_request_free(req_obj);
  305. }
  306. qatomic_set(&qmp_dispatcher_co, NULL);
  307. }
  308. void qmp_dispatcher_co_wake(void)
  309. {
  310. /* Write request before reading qmp_dispatcher_co_busy. */
  311. smp_mb__before_rmw();
  312. if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
  313. aio_co_wake(qmp_dispatcher_co);
  314. }
  315. }
  316. static void handle_qmp_command(void *opaque, QObject *req, Error *err)
  317. {
  318. MonitorQMP *mon = opaque;
  319. QDict *qdict = qobject_to(QDict, req);
  320. QMPRequest *req_obj;
  321. assert(!req != !err);
  322. if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
  323. GString *req_json = qobject_to_json(req);
  324. trace_handle_qmp_command(mon, req_json->str);
  325. g_string_free(req_json, true);
  326. }
  327. if (qdict && qmp_is_oob(qdict)) {
  328. /* OOB commands are executed immediately */
  329. if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_OUT_OF_BAND)) {
  330. QObject *id = qdict_get(qdict, "id");
  331. GString *id_json;
  332. id_json = id ? qobject_to_json(id) : g_string_new(NULL);
  333. trace_monitor_qmp_cmd_out_of_band(id_json->str);
  334. g_string_free(id_json, true);
  335. }
  336. monitor_qmp_dispatch(mon, req);
  337. qobject_unref(req);
  338. return;
  339. }
  340. req_obj = g_new0(QMPRequest, 1);
  341. req_obj->mon = mon;
  342. req_obj->req = req;
  343. req_obj->err = err;
  344. /* Protect qmp_requests and fetching its length. */
  345. WITH_QEMU_LOCK_GUARD(&mon->qmp_queue_lock) {
  346. /*
  347. * Suspend the monitor when we can't queue more requests after
  348. * this one. Dequeuing in monitor_qmp_dispatcher_co() or
  349. * monitor_qmp_cleanup_queue_and_resume() will resume it.
  350. * Note that when OOB is disabled, we queue at most one command,
  351. * for backward compatibility.
  352. */
  353. if (!qmp_oob_enabled(mon) ||
  354. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
  355. monitor_suspend(&mon->common);
  356. }
  357. /*
  358. * Put the request to the end of queue so that requests will be
  359. * handled in time order. Ownership for req_obj, req,
  360. * etc. will be delivered to the handler side.
  361. */
  362. trace_monitor_qmp_in_band_enqueue(req_obj, mon,
  363. mon->qmp_requests->length);
  364. assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
  365. g_queue_push_tail(mon->qmp_requests, req_obj);
  366. }
  367. /* Kick the dispatcher routine */
  368. qmp_dispatcher_co_wake();
  369. }
  370. static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
  371. {
  372. MonitorQMP *mon = opaque;
  373. json_message_parser_feed(&mon->parser, (const char *) buf, size);
  374. }
  375. static QDict *qmp_greeting(MonitorQMP *mon)
  376. {
  377. QList *cap_list = qlist_new();
  378. QObject *ver = NULL;
  379. QDict *args;
  380. QMPCapability cap;
  381. args = qdict_new();
  382. qmp_marshal_query_version(args, &ver, NULL);
  383. qobject_unref(args);
  384. for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
  385. if (mon->capab_offered[cap]) {
  386. qlist_append_str(cap_list, QMPCapability_str(cap));
  387. }
  388. }
  389. return qdict_from_jsonf_nofail(
  390. "{'QMP': {'version': %p, 'capabilities': %p}}",
  391. ver, cap_list);
  392. }
  393. static void monitor_qmp_event(void *opaque, QEMUChrEvent event)
  394. {
  395. QDict *data;
  396. MonitorQMP *mon = opaque;
  397. switch (event) {
  398. case CHR_EVENT_OPENED:
  399. mon->commands = &qmp_cap_negotiation_commands;
  400. monitor_qmp_caps_reset(mon);
  401. data = qmp_greeting(mon);
  402. qmp_send_response(mon, data);
  403. qobject_unref(data);
  404. break;
  405. case CHR_EVENT_CLOSED:
  406. /*
  407. * Note: this is only useful when the output of the chardev
  408. * backend is still open. For example, when the backend is
  409. * stdio, it's possible that stdout is still open when stdin
  410. * is closed.
  411. */
  412. monitor_qmp_cleanup_queue_and_resume(mon);
  413. json_message_parser_destroy(&mon->parser);
  414. json_message_parser_init(&mon->parser, handle_qmp_command,
  415. mon, NULL);
  416. monitor_fdsets_cleanup();
  417. break;
  418. case CHR_EVENT_BREAK:
  419. case CHR_EVENT_MUX_IN:
  420. case CHR_EVENT_MUX_OUT:
  421. /* Ignore */
  422. break;
  423. }
  424. }
  425. void monitor_data_destroy_qmp(MonitorQMP *mon)
  426. {
  427. json_message_parser_destroy(&mon->parser);
  428. qemu_mutex_destroy(&mon->qmp_queue_lock);
  429. monitor_qmp_cleanup_req_queue_locked(mon);
  430. g_queue_free(mon->qmp_requests);
  431. }
  432. static void monitor_qmp_setup_handlers_bh(void *opaque)
  433. {
  434. MonitorQMP *mon = opaque;
  435. GMainContext *context;
  436. assert(mon->common.use_io_thread);
  437. context = iothread_get_g_main_context(mon_iothread);
  438. assert(context);
  439. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  440. monitor_qmp_read, monitor_qmp_event,
  441. NULL, &mon->common, context, true);
  442. monitor_list_append(&mon->common);
  443. }
  444. void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
  445. {
  446. MonitorQMP *mon = g_new0(MonitorQMP, 1);
  447. if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
  448. g_free(mon);
  449. return;
  450. }
  451. qemu_chr_fe_set_echo(&mon->common.chr, true);
  452. /* Note: we run QMP monitor in I/O thread when @chr supports that */
  453. monitor_data_init(&mon->common, true, false,
  454. qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
  455. mon->pretty = pretty;
  456. qemu_mutex_init(&mon->qmp_queue_lock);
  457. mon->qmp_requests = g_queue_new();
  458. json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
  459. if (mon->common.use_io_thread) {
  460. /*
  461. * Make sure the old iowatch is gone. It's possible when
  462. * e.g. the chardev is in client mode, with wait=on.
  463. */
  464. remove_fd_in_watch(chr);
  465. /*
  466. * We can't call qemu_chr_fe_set_handlers() directly here
  467. * since chardev might be running in the monitor I/O
  468. * thread. Schedule a bottom half.
  469. */
  470. aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
  471. monitor_qmp_setup_handlers_bh, mon);
  472. /* The bottom half will add @mon to @mon_list */
  473. } else {
  474. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  475. monitor_qmp_read, monitor_qmp_event,
  476. NULL, &mon->common, NULL, true);
  477. monitor_list_append(&mon->common);
  478. }
  479. }