xref: /openbmc/qemu/docs/devel/writing-monitor-commands.rst (revision a45cfcbb0158af05716bc06fd77f93ba883b13e7)
1How to write monitor commands
2=============================
3
4This document is a step-by-step guide on how to write new QMP commands using
5the QAPI framework and HMP commands.
6
7This document doesn't discuss QMP protocol level details, nor does it dive
8into the QAPI framework implementation.
9
10For an in-depth introduction to the QAPI framework, please refer to
11docs/devel/qapi-code-gen.txt. For documentation about the QMP protocol,
12start with docs/interop/qmp-intro.txt.
13
14
15Overview
16--------
17
18Generally speaking, the following steps should be taken in order to write a
19new QMP command.
20
211. Define the command and any types it needs in the appropriate QAPI
22   schema module.
23
242. Write the QMP command itself, which is a regular C function. Preferably,
25   the command should be exported by some QEMU subsystem. But it can also be
26   added to the monitor/qmp-cmds.c file
27
283. At this point the command can be tested under the QMP protocol
29
304. Write the HMP command equivalent. This is not required and should only be
31   done if it does make sense to have the functionality in HMP. The HMP command
32   is implemented in terms of the QMP command
33
34The following sections will demonstrate each of the steps above. We will start
35very simple and get more complex as we progress.
36
37
38Testing
39-------
40
41For all the examples in the next sections, the test setup is the same and is
42shown here.
43
44First, QEMU should be started like this::
45
46 # qemu-system-TARGET [...] \
47     -chardev socket,id=qmp,port=4444,host=localhost,server=on \
48     -mon chardev=qmp,mode=control,pretty=on
49
50Then, in a different terminal::
51
52 $ telnet localhost 4444
53 Trying 127.0.0.1...
54 Connected to localhost.
55 Escape character is '^]'.
56 {
57     "QMP": {
58         "version": {
59             "qemu": {
60                 "micro": 50,
61                 "minor": 15,
62                 "major": 0
63             },
64             "package": ""
65         },
66         "capabilities": [
67         ]
68     }
69 }
70
71The above output is the QMP server saying you're connected. The server is
72actually in capabilities negotiation mode. To enter in command mode type::
73
74 { "execute": "qmp_capabilities" }
75
76Then the server should respond::
77
78 {
79     "return": {
80     }
81 }
82
83Which is QMP's way of saying "the latest command executed OK and didn't return
84any data". Now you're ready to enter the QMP example commands as explained in
85the following sections.
86
87
88Writing a simple command: hello-world
89-------------------------------------
90
91That's the most simple QMP command that can be written. Usually, this kind of
92command carries some meaningful action in QEMU but here it will just print
93"Hello, world" to the standard output.
94
95Our command will be called "hello-world". It takes no arguments, nor does it
96return any data.
97
98The first step is defining the command in the appropriate QAPI schema
99module.  We pick module qapi/misc.json, and add the following line at
100the bottom::
101
102 { 'command': 'hello-world' }
103
104The "command" keyword defines a new QMP command. It's an JSON object. All
105schema entries are JSON objects. The line above will instruct the QAPI to
106generate any prototypes and the necessary code to marshal and unmarshal
107protocol data.
108
109The next step is to write the "hello-world" implementation. As explained
110earlier, it's preferable for commands to live in QEMU subsystems. But
111"hello-world" doesn't pertain to any, so we put its implementation in
112monitor/qmp-cmds.c::
113
114 void qmp_hello_world(Error **errp)
115 {
116     printf("Hello, world!\n");
117 }
118
119There are a few things to be noticed:
120
1211. QMP command implementation functions must be prefixed with "qmp\_"
1222. qmp_hello_world() returns void, this is in accordance with the fact that the
123   command doesn't return any data
1243. It takes an "Error \*\*" argument. This is required. Later we will see how to
125   return errors and take additional arguments. The Error argument should not
126   be touched if the command doesn't return errors
1274. We won't add the function's prototype. That's automatically done by the QAPI
1285. Printing to the terminal is discouraged for QMP commands, we do it here
129   because it's the easiest way to demonstrate a QMP command
130
131You're done. Now build qemu, run it as suggested in the "Testing" section,
132and then type the following QMP command::
133
134 { "execute": "hello-world" }
135
136Then check the terminal running qemu and look for the "Hello, world" string. If
137you don't see it then something went wrong.
138
139
140Arguments
141~~~~~~~~~
142
143Let's add an argument called "message" to our "hello-world" command. The new
144argument will contain the string to be printed to stdout. It's an optional
145argument, if it's not present we print our default "Hello, World" string.
146
147The first change we have to do is to modify the command specification in the
148schema file to the following::
149
150 { 'command': 'hello-world', 'data': { '*message': 'str' } }
151
152Notice the new 'data' member in the schema. It's an JSON object whose each
153element is an argument to the command in question. Also notice the asterisk,
154it's used to mark the argument optional (that means that you shouldn't use it
155for mandatory arguments). Finally, 'str' is the argument's type, which
156stands for "string". The QAPI also supports integers, booleans, enumerations
157and user defined types.
158
159Now, let's update our C implementation in monitor/qmp-cmds.c::
160
161 void qmp_hello_world(bool has_message, const char *message, Error **errp)
162 {
163     if (has_message) {
164         printf("%s\n", message);
165     } else {
166         printf("Hello, world\n");
167     }
168 }
169
170There are two important details to be noticed:
171
1721. All optional arguments are accompanied by a 'has\_' boolean, which is set
173   if the optional argument is present or false otherwise
1742. The C implementation signature must follow the schema's argument ordering,
175   which is defined by the "data" member
176
177Time to test our new version of the "hello-world" command. Build qemu, run it as
178described in the "Testing" section and then send two commands::
179
180 { "execute": "hello-world" }
181 {
182     "return": {
183     }
184 }
185
186 { "execute": "hello-world", "arguments": { "message": "We love qemu" } }
187 {
188     "return": {
189     }
190 }
191
192You should see "Hello, world" and "We love qemu" in the terminal running qemu,
193if you don't see these strings, then something went wrong.
194
195
196Errors
197~~~~~~
198
199QMP commands should use the error interface exported by the error.h header
200file. Basically, most errors are set by calling the error_setg() function.
201
202Let's say we don't accept the string "message" to contain the word "love". If
203it does contain it, we want the "hello-world" command to return an error::
204
205 void qmp_hello_world(bool has_message, const char *message, Error **errp)
206 {
207     if (has_message) {
208         if (strstr(message, "love")) {
209             error_setg(errp, "the word 'love' is not allowed");
210             return;
211         }
212         printf("%s\n", message);
213     } else {
214         printf("Hello, world\n");
215     }
216 }
217
218The first argument to the error_setg() function is the Error pointer
219to pointer, which is passed to all QMP functions. The next argument is a human
220description of the error, this is a free-form printf-like string.
221
222Let's test the example above. Build qemu, run it as defined in the "Testing"
223section, and then issue the following command::
224
225 { "execute": "hello-world", "arguments": { "message": "all you need is love" } }
226
227The QMP server's response should be::
228
229 {
230     "error": {
231         "class": "GenericError",
232         "desc": "the word 'love' is not allowed"
233     }
234 }
235
236Note that error_setg() produces a "GenericError" class.  In general,
237all QMP errors should have that error class.  There are two exceptions
238to this rule:
239
240 1. To support a management application's need to recognize a specific
241    error for special handling
242
243 2. Backward compatibility
244
245If the failure you want to report falls into one of the two cases above,
246use error_set() with a second argument of an ErrorClass value.
247
248
249Command Documentation
250~~~~~~~~~~~~~~~~~~~~~
251
252There's only one step missing to make "hello-world"'s implementation complete,
253and that's its documentation in the schema file.
254
255There are many examples of such documentation in the schema file already, but
256here goes "hello-world"'s new entry for qapi/misc.json::
257
258 ##
259 # @hello-world:
260 #
261 # Print a client provided string to the standard output stream.
262 #
263 # @message: string to be printed
264 #
265 # Returns: Nothing on success.
266 #
267 # Notes: if @message is not provided, the "Hello, world" string will
268 #        be printed instead
269 #
270 # Since: <next qemu stable release, eg. 1.0>
271 ##
272 { 'command': 'hello-world', 'data': { '*message': 'str' } }
273
274Please, note that the "Returns" clause is optional if a command doesn't return
275any data nor any errors.
276
277
278Implementing the HMP command
279~~~~~~~~~~~~~~~~~~~~~~~~~~~~
280
281Now that the QMP command is in place, we can also make it available in the human
282monitor (HMP).
283
284With the introduction of the QAPI, HMP commands make QMP calls. Most of the
285time HMP commands are simple wrappers. All HMP commands implementation exist in
286the monitor/hmp-cmds.c file.
287
288Here's the implementation of the "hello-world" HMP command::
289
290 void hmp_hello_world(Monitor *mon, const QDict *qdict)
291 {
292     const char *message = qdict_get_try_str(qdict, "message");
293     Error *err = NULL;
294
295     qmp_hello_world(!!message, message, &err);
296     if (hmp_handle_error(mon, err)) {
297         return;
298     }
299 }
300
301Also, you have to add the function's prototype to the hmp.h file.
302
303There are three important points to be noticed:
304
3051. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
306   former is the monitor object. The latter is how the monitor passes
307   arguments entered by the user to the command implementation
3082. hmp_hello_world() performs error checking. In this example we just call
309   hmp_handle_error() which prints a message to the user, but we could do
310   more, like taking different actions depending on the error
311   qmp_hello_world() returns
3123. The "err" variable must be initialized to NULL before performing the
313   QMP call
314
315There's one last step to actually make the command available to monitor users,
316we should add it to the hmp-commands.hx file::
317
318    {
319        .name       = "hello-world",
320        .args_type  = "message:s?",
321        .params     = "hello-world [message]",
322        .help       = "Print message to the standard output",
323        .cmd        = hmp_hello_world,
324    },
325
326::
327
328 STEXI
329 @item hello_world @var{message}
330 @findex hello_world
331 Print message to the standard output
332 ETEXI
333
334To test this you have to open a user monitor and issue the "hello-world"
335command. It might be instructive to check the command's documentation with
336HMP's "help" command.
337
338Please, check the "-monitor" command-line option to know how to open a user
339monitor.
340
341
342Writing more complex commands
343-----------------------------
344
345A QMP command is capable of returning any data the QAPI supports like integers,
346strings, booleans, enumerations and user defined types.
347
348In this section we will focus on user defined types. Please, check the QAPI
349documentation for information about the other types.
350
351
352Modelling data in QAPI
353~~~~~~~~~~~~~~~~~~~~~~
354
355For a QMP command that to be considered stable and supported long term,
356there is a requirement returned data should be explicitly modelled
357using fine-grained QAPI types. As a general guide, a caller of the QMP
358command should never need to parse individual returned data fields. If
359a field appears to need parsing, then it should be split into separate
360fields corresponding to each distinct data item. This should be the
361common case for any new QMP command that is intended to be used by
362machines, as opposed to exclusively human operators.
363
364Some QMP commands, however, are only intended as ad hoc debugging aids
365for human operators. While they may return large amounts of formatted
366data, it is not expected that machines will need to parse the result.
367The overhead of defining a fine grained QAPI type for the data may not
368be justified by the potential benefit. In such cases, it is permitted
369to have a command return a simple string that contains formatted data,
370however, it is mandatory for the command to use the 'x-' name prefix.
371This indicates that the command is not guaranteed to be long term
372stable / liable to change in future and is not following QAPI design
373best practices. An example where this approach is taken is the QMP
374command "x-query-registers". This returns a formatted dump of the
375architecture specific CPU state. The way the data is formatted varies
376across QEMU targets, is liable to change over time, and is only
377intended to be consumed as an opaque string by machines. Refer to the
378`Writing a debugging aid returning unstructured text`_ section for
379an illustration.
380
381User Defined Types
382~~~~~~~~~~~~~~~~~~
383
384FIXME This example needs to be redone after commit 6d32717
385
386For this example we will write the query-alarm-clock command, which returns
387information about QEMU's timer alarm. For more information about it, please
388check the "-clock" command-line option.
389
390We want to return two pieces of information. The first one is the alarm clock's
391name. The second one is when the next alarm will fire. The former information is
392returned as a string, the latter is an integer in nanoseconds (which is not
393very useful in practice, as the timer has probably already fired when the
394information reaches the client).
395
396The best way to return that data is to create a new QAPI type, as shown below::
397
398 ##
399 # @QemuAlarmClock
400 #
401 # QEMU alarm clock information.
402 #
403 # @clock-name: The alarm clock method's name.
404 #
405 # @next-deadline: The time (in nanoseconds) the next alarm will fire.
406 #
407 # Since: 1.0
408 ##
409 { 'type': 'QemuAlarmClock',
410   'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
411
412The "type" keyword defines a new QAPI type. Its "data" member contains the
413type's members. In this example our members are the "clock-name" and the
414"next-deadline" one, which is optional.
415
416Now let's define the query-alarm-clock command::
417
418 ##
419 # @query-alarm-clock
420 #
421 # Return information about QEMU's alarm clock.
422 #
423 # Returns a @QemuAlarmClock instance describing the alarm clock method
424 # being currently used by QEMU (this is usually set by the '-clock'
425 # command-line option).
426 #
427 # Since: 1.0
428 ##
429 { 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
430
431Notice the "returns" keyword. As its name suggests, it's used to define the
432data returned by a command.
433
434It's time to implement the qmp_query_alarm_clock() function, you can put it
435in the qemu-timer.c file::
436
437 QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
438 {
439     QemuAlarmClock *clock;
440     int64_t deadline;
441
442     clock = g_malloc0(sizeof(*clock));
443
444     deadline = qemu_next_alarm_deadline();
445     if (deadline > 0) {
446         clock->has_next_deadline = true;
447         clock->next_deadline = deadline;
448     }
449     clock->clock_name = g_strdup(alarm_timer->name);
450
451     return clock;
452 }
453
454There are a number of things to be noticed:
455
4561. The QemuAlarmClock type is automatically generated by the QAPI framework,
457   its members correspond to the type's specification in the schema file
4582. As specified in the schema file, the function returns a QemuAlarmClock
459   instance and takes no arguments (besides the "errp" one, which is mandatory
460   for all QMP functions)
4613. The "clock" variable (which will point to our QAPI type instance) is
462   allocated by the regular g_malloc0() function. Note that we chose to
463   initialize the memory to zero. This is recommended for all QAPI types, as
464   it helps avoiding bad surprises (specially with booleans)
4654. Remember that "next_deadline" is optional? All optional members have a
466   'has_TYPE_NAME' member that should be properly set by the implementation,
467   as shown above
4685. Even static strings, such as "alarm_timer->name", should be dynamically
469   allocated by the implementation. This is so because the QAPI also generates
470   a function to free its types and it cannot distinguish between dynamically
471   or statically allocated strings
4726. You have to include "qapi/qapi-commands-misc.h" in qemu-timer.c
473
474Time to test the new command. Build qemu, run it as described in the "Testing"
475section and try this::
476
477 { "execute": "query-alarm-clock" }
478 {
479     "return": {
480         "next-deadline": 2368219,
481         "clock-name": "dynticks"
482     }
483 }
484
485
486The HMP command
487~~~~~~~~~~~~~~~
488
489Here's the HMP counterpart of the query-alarm-clock command::
490
491 void hmp_info_alarm_clock(Monitor *mon)
492 {
493     QemuAlarmClock *clock;
494     Error *err = NULL;
495
496     clock = qmp_query_alarm_clock(&err);
497     if (hmp_handle_error(mon, err)) {
498         return;
499     }
500
501     monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
502     if (clock->has_next_deadline) {
503         monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
504                        clock->next_deadline);
505     }
506
507    qapi_free_QemuAlarmClock(clock);
508 }
509
510It's important to notice that hmp_info_alarm_clock() calls
511qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
512For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
513function and that's what you have to use to free the types you define and
514qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
515If the QMP call returns a string, then you should g_free() to free it.
516
517Also note that hmp_info_alarm_clock() performs error handling. That's not
518strictly required if you're sure the QMP function doesn't return errors, but
519it's good practice to always check for errors.
520
521Another important detail is that HMP's "info" commands don't go into the
522hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
523in the monitor/misc.c file. The entry for the "info alarmclock" follows::
524
525    {
526        .name       = "alarmclock",
527        .args_type  = "",
528        .params     = "",
529        .help       = "show information about the alarm clock",
530        .cmd        = hmp_info_alarm_clock,
531    },
532
533To test this, run qemu and type "info alarmclock" in the user monitor.
534
535
536Returning Lists
537~~~~~~~~~~~~~~~
538
539For this example, we're going to return all available methods for the timer
540alarm, which is pretty much what the command-line option "-clock ?" does,
541except that we're also going to inform which method is in use.
542
543This first step is to define a new type::
544
545 ##
546 # @TimerAlarmMethod
547 #
548 # Timer alarm method information.
549 #
550 # @method-name: The method's name.
551 #
552 # @current: true if this alarm method is currently in use, false otherwise
553 #
554 # Since: 1.0
555 ##
556 { 'type': 'TimerAlarmMethod',
557   'data': { 'method-name': 'str', 'current': 'bool' } }
558
559The command will be called "query-alarm-methods", here is its schema
560specification::
561
562 ##
563 # @query-alarm-methods
564 #
565 # Returns information about available alarm methods.
566 #
567 # Returns: a list of @TimerAlarmMethod for each method
568 #
569 # Since: 1.0
570 ##
571 { 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
572
573Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
574should be read as "returns a list of TimerAlarmMethod instances".
575
576The C implementation follows::
577
578 TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
579 {
580     TimerAlarmMethodList *method_list = NULL;
581     const struct qemu_alarm_timer *p;
582     bool current = true;
583
584     for (p = alarm_timers; p->name; p++) {
585         TimerAlarmMethod *value = g_malloc0(*value);
586         value->method_name = g_strdup(p->name);
587         value->current = current;
588         QAPI_LIST_PREPEND(method_list, value);
589         current = false;
590     }
591
592     return method_list;
593 }
594
595The most important difference from the previous examples is the
596TimerAlarmMethodList type, which is automatically generated by the QAPI from
597the TimerAlarmMethod type.
598
599Each list node is represented by a TimerAlarmMethodList instance. We have to
600allocate it, and that's done inside the for loop: the "info" pointer points to
601an allocated node. We also have to allocate the node's contents, which is
602stored in its "value" member. In our example, the "value" member is a pointer
603to an TimerAlarmMethod instance.
604
605Notice that the "current" variable is used as "true" only in the first
606iteration of the loop. That's because the alarm timer method in use is the
607first element of the alarm_timers array. Also notice that QAPI lists are handled
608by hand and we return the head of the list.
609
610Now Build qemu, run it as explained in the "Testing" section and try our new
611command::
612
613 { "execute": "query-alarm-methods" }
614 {
615     "return": [
616         {
617             "current": false,
618             "method-name": "unix"
619         },
620         {
621             "current": true,
622             "method-name": "dynticks"
623         }
624     ]
625 }
626
627The HMP counterpart is a bit more complex than previous examples because it
628has to traverse the list, it's shown below for reference::
629
630 void hmp_info_alarm_methods(Monitor *mon)
631 {
632     TimerAlarmMethodList *method_list, *method;
633     Error *err = NULL;
634
635     method_list = qmp_query_alarm_methods(&err);
636     if (hmp_handle_error(mon, err)) {
637         return;
638     }
639
640     for (method = method_list; method; method = method->next) {
641         monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ',
642                                        method->value->method_name);
643     }
644
645     qapi_free_TimerAlarmMethodList(method_list);
646 }
647
648Writing a debugging aid returning unstructured text
649---------------------------------------------------
650
651As discussed in section `Modelling data in QAPI`_, it is required that
652commands expecting machine usage be using fine-grained QAPI data types.
653The exception to this rule applies when the command is solely intended
654as a debugging aid and allows for returning unstructured text. This is
655commonly needed for query commands that report aspects of QEMU's
656internal state that are useful to human operators.
657
658In this example we will consider a simplified variant of the HMP
659command ``info roms``. Following the earlier rules, this command will
660need to live under the ``x-`` name prefix, so its QMP implementation
661will be called ``x-query-roms``. It will have no parameters and will
662return a single text string::
663
664 { 'struct': 'HumanReadableText',
665   'data': { 'human-readable-text': 'str' } }
666
667 { 'command': 'x-query-roms',
668   'returns': 'HumanReadableText' }
669
670The ``HumanReadableText`` struct is intended to be used for all
671commands, under the ``x-`` name prefix that are returning unstructured
672text targetted at humans. It should never be used for commands outside
673the ``x-`` name prefix, as those should be using structured QAPI types.
674
675Implementing the QMP command
676~~~~~~~~~~~~~~~~~~~~~~~~~~~~
677
678The QMP implementation will typically involve creating a ``GString``
679object and printing formatted data into it::
680
681 HumanReadableText *qmp_x_query_roms(Error **errp)
682 {
683     g_autoptr(GString) buf = g_string_new("");
684     Rom *rom;
685
686     QTAILQ_FOREACH(rom, &roms, next) {
687        g_string_append_printf("%s size=0x%06zx name=\"%s\"\n",
688                               memory_region_name(rom->mr),
689                               rom->romsize,
690                               rom->name);
691     }
692
693     return human_readable_text_from_str(buf);
694 }
695
696
697Implementing the HMP command
698~~~~~~~~~~~~~~~~~~~~~~~~~~~~
699
700Now that the QMP command is in place, we can also make it available in
701the human monitor (HMP) as shown in previous examples. The HMP
702implementations will all look fairly similar, as all they need do is
703invoke the QMP command and then print the resulting text or error
704message. Here's the implementation of the "info roms" HMP command::
705
706 void hmp_info_roms(Monitor *mon, const QDict *qdict)
707 {
708     Error err = NULL;
709     g_autoptr(HumanReadableText) info = qmp_x_query_roms(&err);
710
711     if (hmp_handle_error(mon, err)) {
712         return;
713     }
714     monitor_printf(mon, "%s", info->human_readable_text);
715 }
716
717Also, you have to add the function's prototype to the hmp.h file.
718
719There's one last step to actually make the command available to
720monitor users, we should add it to the hmp-commands-info.hx file::
721
722    {
723        .name       = "roms",
724        .args_type  = "",
725        .params     = "",
726        .help       = "show roms",
727        .cmd        = hmp_info_roms,
728    },
729
730The case of writing a HMP info handler that calls a no-parameter QMP query
731command is quite common. To simplify the implementation there is a general
732purpose HMP info handler for this scenario. All that is required to expose
733a no-parameter QMP query command via HMP is to declare it using the
734'.cmd_info_hrt' field to point to the QMP handler, and leave the '.cmd'
735field NULL::
736
737    {
738        .name         = "roms",
739        .args_type    = "",
740        .params       = "",
741        .help         = "show roms",
742        .cmd_info_hrt = qmp_x_query_roms,
743    },
744