xref: /openbmc/qemu/docs/devel/writing-monitor-commands.rst (revision 59807e2098a1987f24f2f8c32c8db7f84077a0a5)
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
11:doc:`qapi-code-gen`.  For the QMP protocol, see the
12:doc:`/interop/qmp-spec`.
13
14New commands may be implemented in QMP only.  New HMP commands should be
15implemented on top of QMP.  The typical HMP command wraps around an
16equivalent QMP command, but HMP convenience commands built from QMP
17building blocks are also fine.  The long term goal is to make all
18existing HMP commands conform to this, to fully isolate HMP from the
19internals of QEMU. Refer to the `Writing a debugging aid returning
20unstructured text`_ section for further guidance on commands that
21would have traditionally been HMP only.
22
23Overview
24--------
25
26Generally speaking, the following steps should be taken in order to write a
27new QMP command.
28
291. Define the command and any types it needs in the appropriate QAPI
30   schema module.
31
322. Write the QMP command itself, which is a regular C function. Preferably,
33   the command should be exported by some QEMU subsystem. But it can also be
34   added to the monitor/qmp-cmds.c file
35
363. At this point the command can be tested under the QMP protocol
37
384. Write the HMP command equivalent. This is not required and should only be
39   done if it does make sense to have the functionality in HMP. The HMP command
40   is implemented in terms of the QMP command
41
42The following sections will demonstrate each of the steps above. We will start
43very simple and get more complex as we progress.
44
45
46Testing
47-------
48
49For all the examples in the next sections, the test setup is the same and is
50shown here.
51
52First, QEMU should be started like this::
53
54 # qemu-system-TARGET [...] \
55     -chardev socket,id=qmp,port=4444,host=localhost,server=on \
56     -mon chardev=qmp,mode=control,pretty=on
57
58Then, in a different terminal::
59
60 $ telnet localhost 4444
61 Trying 127.0.0.1...
62 Connected to localhost.
63 Escape character is '^]'.
64 {
65     "QMP": {
66         "version": {
67             "qemu": {
68                 "micro": 50,
69                 "minor": 2,
70                 "major": 8
71             },
72             "package": ...
73         },
74         "capabilities": [
75             "oob"
76         ]
77     }
78 }
79
80The above output is the QMP server saying you're connected. The server is
81actually in capabilities negotiation mode. To enter in command mode type::
82
83 { "execute": "qmp_capabilities" }
84
85Then the server should respond::
86
87 {
88     "return": {
89     }
90 }
91
92Which is QMP's way of saying "the latest command executed OK and didn't return
93any data". Now you're ready to enter the QMP example commands as explained in
94the following sections.
95
96
97Writing a simple command: hello-world
98-------------------------------------
99
100That's the most simple QMP command that can be written. Usually, this kind of
101command carries some meaningful action in QEMU but here it will just print
102"Hello, world" to the standard output.
103
104Our command will be called "hello-world". It takes no arguments, nor does it
105return any data.
106
107The first step is defining the command in the appropriate QAPI schema
108module.  We pick module qapi/misc.json, and add the following line at
109the bottom::
110
111 ##
112 # @hello-world:
113 #
114 # Since: 9.0
115 ##
116 { 'command': 'hello-world' }
117
118The "command" keyword defines a new QMP command. It's an JSON object. All
119schema entries are JSON objects. The line above will instruct the QAPI to
120generate any prototypes and the necessary code to marshal and unmarshal
121protocol data.
122
123The next step is to write the "hello-world" implementation. As explained
124earlier, it's preferable for commands to live in QEMU subsystems. But
125"hello-world" doesn't pertain to any, so we put its implementation in
126monitor/qmp-cmds.c::
127
128 void qmp_hello_world(Error **errp)
129 {
130     printf("Hello, world!\n");
131 }
132
133There are a few things to be noticed:
134
1351. QMP command implementation functions must be prefixed with "qmp\_"
1362. qmp_hello_world() returns void, this is in accordance with the fact that the
137   command doesn't return any data
1383. It takes an "Error \*\*" argument. This is required. Later we will see how to
139   return errors and take additional arguments. The Error argument should not
140   be touched if the command doesn't return errors
1414. We won't add the function's prototype. That's automatically done by the QAPI
1425. Printing to the terminal is discouraged for QMP commands, we do it here
143   because it's the easiest way to demonstrate a QMP command
144
145You're done. Now build qemu, run it as suggested in the "Testing" section,
146and then type the following QMP command::
147
148 { "execute": "hello-world" }
149
150Then check the terminal running qemu and look for the "Hello, world" string. If
151you don't see it then something went wrong.
152
153
154Arguments
155~~~~~~~~~
156
157Let's add arguments to our "hello-world" command.
158
159The first change we have to do is to modify the command specification in the
160schema file to the following::
161
162 ##
163 # @hello-world:
164 #
165 # @message: message to be printed (default: "Hello, world!")
166 #
167 # @times: how many times to print the message (default: 1)
168 #
169 # Since: 9.0
170 ##
171 { 'command': 'hello-world',
172   'data': { '*message': 'str', '*times': 'int' } }
173
174Notice the new 'data' member in the schema. It specifies an argument
175'message' of QAPI type 'str', and an argument 'times' of QAPI type
176'int'.  Also notice the asterisk, it's used to mark the argument
177optional.
178
179Now, let's update our C implementation in monitor/qmp-cmds.c::
180
181 void qmp_hello_world(const char *message, bool has_times, int64_t times,
182                      Error **errp)
183 {
184     if (!message) {
185         message = "Hello, world";
186     }
187     if (!has_times) {
188         times = 1;
189     }
190
191     for (int i = 0; i < times; i++) {
192         printf("%s\n", message);
193     }
194 }
195
196There are two important details to be noticed:
197
1981. Optional arguments other than pointers are accompanied by a 'has\_'
199   boolean, which is set if the optional argument is present or false
200   otherwise
2012. The C implementation signature must follow the schema's argument ordering,
202   which is defined by the "data" member
203
204Time to test our new version of the "hello-world" command. Build qemu, run it as
205described in the "Testing" section and then send two commands::
206
207 { "execute": "hello-world" }
208 {
209     "return": {
210     }
211 }
212
213 { "execute": "hello-world", "arguments": { "message": "We love qemu" } }
214 {
215     "return": {
216     }
217 }
218
219You should see "Hello, world" and "We love qemu" in the terminal running qemu,
220if you don't see these strings, then something went wrong.
221
222
223Errors
224~~~~~~
225
226QMP commands should use the error interface exported by the error.h header
227file. Basically, most errors are set by calling the error_setg() function.
228
229Let's say we don't accept the string "message" to contain the word "love". If
230it does contain it, we want the "hello-world" command to return an error::
231
232 void qmp_hello_world(const char *message, Error **errp)
233 {
234     if (message) {
235         if (strstr(message, "love")) {
236             error_setg(errp, "the word 'love' is not allowed");
237             return;
238         }
239         printf("%s\n", message);
240     } else {
241         printf("Hello, world\n");
242     }
243 }
244
245The first argument to the error_setg() function is the Error pointer
246to pointer, which is passed to all QMP functions. The next argument is a human
247description of the error, this is a free-form printf-like string.
248
249Let's test the example above. Build qemu, run it as defined in the "Testing"
250section, and then issue the following command::
251
252 { "execute": "hello-world", "arguments": { "message": "all you need is love" } }
253
254The QMP server's response should be::
255
256 {
257     "error": {
258         "class": "GenericError",
259         "desc": "the word 'love' is not allowed"
260     }
261 }
262
263Note that error_setg() produces a "GenericError" class.  In general,
264all QMP errors should have that error class.  There are two exceptions
265to this rule:
266
267 1. To support a management application's need to recognize a specific
268    error for special handling
269
270 2. Backward compatibility
271
272If the failure you want to report falls into one of the two cases above,
273use error_set() with a second argument of an ErrorClass value.
274
275
276Implementing the HMP command
277~~~~~~~~~~~~~~~~~~~~~~~~~~~~
278
279Now that the QMP command is in place, we can also make it available in the human
280monitor (HMP).
281
282With the introduction of the QAPI, HMP commands make QMP calls. Most of the
283time HMP commands are simple wrappers. All HMP commands implementation exist in
284the monitor/hmp-cmds.c file.
285
286Here's the implementation of the "hello-world" HMP command::
287
288 void hmp_hello_world(Monitor *mon, const QDict *qdict)
289 {
290     const char *message = qdict_get_try_str(qdict, "message");
291     Error *err = NULL;
292
293     qmp_hello_world(!!message, message, &err);
294     if (hmp_handle_error(mon, err)) {
295         return;
296     }
297 }
298
299Add it to monitor/hmp-cmds.c.  Also, add its prototype to
300include/monitor/hmp.h.
301
302There are four important points to be noticed:
303
3041. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
305   former is the monitor object. The latter is how the monitor passes
306   arguments entered by the user to the command implementation
3072. We chose not to support the "times" argument in HMP
3083. 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
3124. 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 SRST
327 ``hello_world`` *message*
328   Print message to the standard output
329 ERST
330
331To test this you have to open a user monitor and issue the "hello-world"
332command. It might be instructive to check the command's documentation with
333HMP's "help" command.
334
335Please, check the "-monitor" command-line option to know how to open a user
336monitor.
337
338
339Writing more complex commands
340-----------------------------
341
342A QMP command is capable of returning any data the QAPI supports like integers,
343strings, booleans, enumerations and user defined types.
344
345In this section we will focus on user defined types. Please, check the QAPI
346documentation for information about the other types.
347
348
349Modelling data in QAPI
350~~~~~~~~~~~~~~~~~~~~~~
351
352For a QMP command that to be considered stable and supported long term,
353there is a requirement returned data should be explicitly modelled
354using fine-grained QAPI types. As a general guide, a caller of the QMP
355command should never need to parse individual returned data fields. If
356a field appears to need parsing, then it should be split into separate
357fields corresponding to each distinct data item. This should be the
358common case for any new QMP command that is intended to be used by
359machines, as opposed to exclusively human operators.
360
361Some QMP commands, however, are only intended as ad hoc debugging aids
362for human operators. While they may return large amounts of formatted
363data, it is not expected that machines will need to parse the result.
364The overhead of defining a fine grained QAPI type for the data may not
365be justified by the potential benefit. In such cases, it is permitted
366to have a command return a simple string that contains formatted data,
367however, it is mandatory for the command to be marked unstable.
368This indicates that the command is not guaranteed to be long term
369stable / liable to change in future and is not following QAPI design
370best practices. An example where this approach is taken is the QMP
371command "x-query-registers". This returns a formatted dump of the
372architecture specific CPU state. The way the data is formatted varies
373across QEMU targets, is liable to change over time, and is only
374intended to be consumed as an opaque string by machines. Refer to the
375`Writing a debugging aid returning unstructured text`_ section for
376an illustration.
377
378User Defined Types
379~~~~~~~~~~~~~~~~~~
380
381For this example we will write the query-option-roms command, which
382returns information about ROMs loaded into the option ROM space. For
383more information about it, please check the "-option-rom" command-line
384option.
385
386For each option ROM, we want to return two pieces of information: the
387ROM image's file name, and its bootindex, if any.  We need to create a
388new QAPI type for that, as shown below::
389
390 ##
391 # @OptionRomInfo:
392 #
393 # @filename: option ROM image file name
394 #
395 # @bootindex: option ROM's bootindex
396 #
397 # Since: 9.0
398 ##
399 { 'struct': 'OptionRomInfo',
400   'data': { 'filename': 'str', '*bootindex': 'int' } }
401
402The "struct" keyword defines a new QAPI type. Its "data" member
403contains the type's members. In this example our members are
404"filename" and "bootindex". The latter is optional.
405
406Now let's define the query-option-roms command::
407
408 ##
409 # @query-option-roms:
410 #
411 # Query information on ROMs loaded into the option ROM space.
412 #
413 # Returns: OptionRomInfo
414 #
415 # Since: 9.0
416 ##
417 { 'command': 'query-option-roms',
418   'returns': ['OptionRomInfo'] }
419
420Notice the "returns" keyword. As its name suggests, it's used to define the
421data returned by a command.
422
423Notice the syntax ['OptionRomInfo']". This should be read as "returns
424a list of OptionRomInfo".
425
426It's time to implement the qmp_query_option_roms() function.  Add to
427monitor/qmp-cmds.c::
428
429 OptionRomInfoList *qmp_query_option_roms(Error **errp)
430 {
431     OptionRomInfoList *info_list = NULL;
432     OptionRomInfoList **tailp = &info_list;
433     OptionRomInfo *info;
434
435     for (int i = 0; i < nb_option_roms; i++) {
436         info = g_malloc0(sizeof(*info));
437         info->filename = g_strdup(option_rom[i].name);
438         info->has_bootindex = option_rom[i].bootindex >= 0;
439         if (info->has_bootindex) {
440             info->bootindex = option_rom[i].bootindex;
441         }
442         QAPI_LIST_APPEND(tailp, info);
443     }
444
445     return info_list;
446 }
447
448There are a number of things to be noticed:
449
4501. Type OptionRomInfo is automatically generated by the QAPI framework,
451   its members correspond to the type's specification in the schema
452   file
4532. Type OptionRomInfoList is also generated.  It's a singly linked
454   list.
4553. As specified in the schema file, the function returns a
456   OptionRomInfoList, and takes no arguments (besides the "errp" one,
457   which is mandatory for all QMP functions)
4584. The returned object is dynamically allocated
4595. All strings are dynamically allocated. This is so because QAPI also
460   generates a function to free its types and it cannot distinguish
461   between dynamically or statically allocated strings
4626. Remember that "bootindex" is optional? As a non-pointer optional
463   member, it comes with a 'has_bootindex' member that needs to be set
464   by the implementation, as shown above
465
466Time to test the new command. Build qemu, run it as described in the "Testing"
467section and try this::
468
469 { "execute": "query-option-rom" }
470 {
471     "return": [
472         {
473             "filename": "kvmvapic.bin"
474         }
475     ]
476 }
477
478
479The HMP command
480~~~~~~~~~~~~~~~
481
482Here's the HMP counterpart of the query-option-roms command::
483
484 void hmp_info_option_roms(Monitor *mon, const QDict *qdict)
485 {
486     Error *err = NULL;
487     OptionRomInfoList *info_list, *tail;
488     OptionRomInfo *info;
489
490     info_list = qmp_query_option_roms(&err);
491     if (hmp_handle_error(mon, err)) {
492         return;
493     }
494
495     for (tail = info_list; tail; tail = tail->next) {
496         info = tail->value;
497         monitor_printf(mon, "%s", info->filename);
498         if (info->has_bootindex) {
499             monitor_printf(mon, " %" PRId64, info->bootindex);
500         }
501         monitor_printf(mon, "\n");
502     }
503
504     qapi_free_OptionRomInfoList(info_list);
505 }
506
507It's important to notice that hmp_info_option_roms() calls
508qapi_free_OptionRomInfoList() to free the data returned by
509qmp_query_option_roms().  For user defined types, QAPI will generate a
510qapi_free_QAPI_TYPE_NAME() function, and that's what you have to use to
511free the types you define and qapi_free_QAPI_TYPE_NAMEList() for list
512types (explained in the next section). If the QMP function returns a
513string, then you should g_free() to free it.
514
515Also note that hmp_info_option_roms() performs error handling. That's
516not strictly required when you're sure the QMP function doesn't return
517errors; you could instead pass it &error_abort then.
518
519Another important detail is that HMP's "info" commands go into
520hmp-commands-info.hx, not hmp-commands.hx. The entry for the "info
521option-roms" follows::
522
523     {
524         .name       = "option-roms",
525         .args_type  = "",
526         .params     = "",
527         .help       = "show roms",
528         .cmd        = hmp_info_option_roms,
529     },
530 SRST
531 ``info option-roms``
532   Show the option ROMs.
533 ERST
534
535To test this, run qemu and type "info option-roms" in the user monitor.
536
537
538Writing a debugging aid returning unstructured text
539---------------------------------------------------
540
541As discussed in section `Modelling data in QAPI`_, it is required that
542commands expecting machine usage be using fine-grained QAPI data types.
543The exception to this rule applies when the command is solely intended
544as a debugging aid and allows for returning unstructured text, such as
545a query command that report aspects of QEMU's internal state that are
546useful only to human operators.
547
548In this example we will consider the existing QMP command
549``x-query-roms`` in qapi/machine.json.  It has no parameters and
550returns a ``HumanReadableText``::
551
552 ##
553 # @x-query-roms:
554 #
555 # Query information on the registered ROMS
556 #
557 # Features:
558 #
559 # @unstable: This command is meant for debugging.
560 #
561 # Returns: registered ROMs
562 #
563 # Since: 6.2
564 ##
565 { 'command': 'x-query-roms',
566   'returns': 'HumanReadableText',
567   'features': [ 'unstable' ] }
568
569The ``HumanReadableText`` struct is defined in qapi/common.json as a
570struct with a string member. It is intended to be used for all
571commands that are returning unstructured text targeted at
572humans. These should all have feature 'unstable'.  Note that the
573feature's documentation states why the command is unstable.  We
574commonly use a ``x-`` command name prefix to make lack of stability
575obvious to human users.
576
577Implementing the QMP command
578~~~~~~~~~~~~~~~~~~~~~~~~~~~~
579
580The QMP implementation will typically involve creating a ``GString``
581object and printing formatted data into it, like this::
582
583 HumanReadableText *qmp_x_query_roms(Error **errp)
584 {
585     g_autoptr(GString) buf = g_string_new("");
586     Rom *rom;
587
588     QTAILQ_FOREACH(rom, &roms, next) {
589        g_string_append_printf("%s size=0x%06zx name=\"%s\"\n",
590                               memory_region_name(rom->mr),
591                               rom->romsize,
592                               rom->name);
593     }
594
595     return human_readable_text_from_str(buf);
596 }
597
598The actual implementation emits more information.  You can find it in
599hw/core/loader.c.
600
601
602Implementing the HMP command
603~~~~~~~~~~~~~~~~~~~~~~~~~~~~
604
605Now that the QMP command is in place, we can also make it available in
606the human monitor (HMP) as shown in previous examples. The HMP
607implementations will all look fairly similar, as all they need do is
608invoke the QMP command and then print the resulting text or error
609message. Here's an implementation of the "info roms" HMP command::
610
611 void hmp_info_roms(Monitor *mon, const QDict *qdict)
612 {
613     Error err = NULL;
614     g_autoptr(HumanReadableText) info = qmp_x_query_roms(&err);
615
616     if (hmp_handle_error(mon, err)) {
617         return;
618     }
619     monitor_puts(mon, info->human_readable_text);
620 }
621
622Also, you have to add the function's prototype to the hmp.h file.
623
624There's one last step to actually make the command available to
625monitor users, we should add it to the hmp-commands-info.hx file::
626
627    {
628        .name       = "roms",
629        .args_type  = "",
630        .params     = "",
631        .help       = "show roms",
632        .cmd        = hmp_info_roms,
633    },
634
635The case of writing a HMP info handler that calls a no-parameter QMP query
636command is quite common. To simplify the implementation there is a general
637purpose HMP info handler for this scenario. All that is required to expose
638a no-parameter QMP query command via HMP is to declare it using the
639'.cmd_info_hrt' field to point to the QMP handler, and leave the '.cmd'
640field NULL::
641
642    {
643        .name         = "roms",
644        .args_type    = "",
645        .params       = "",
646        .help         = "show roms",
647        .cmd_info_hrt = qmp_x_query_roms,
648    },
649
650This is how the actual HMP command is done.
651