xref: /openbmc/qemu/qemu-io.c (revision a6e03739)
1 /*
2  * Command line utility to exercise the QEMU I/O path.
3  *
4  * Copyright (C) 2009 Red Hat, Inc.
5  * Copyright (c) 2003-2005 Silicon Graphics, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or later.
8  * See the COPYING file in the top-level directory.
9  */
10 
11 #include "qemu/osdep.h"
12 #include <getopt.h>
13 #include <libgen.h>
14 #ifndef _WIN32
15 #include <termios.h>
16 #endif
17 
18 #include "qemu-common.h"
19 #include "qapi/error.h"
20 #include "qemu-io.h"
21 #include "qemu/error-report.h"
22 #include "qemu/main-loop.h"
23 #include "qemu/module.h"
24 #include "qemu/option.h"
25 #include "qemu/config-file.h"
26 #include "qemu/readline.h"
27 #include "qemu/log.h"
28 #include "qemu/sockets.h"
29 #include "qapi/qmp/qstring.h"
30 #include "qapi/qmp/qdict.h"
31 #include "qom/object_interfaces.h"
32 #include "sysemu/block-backend.h"
33 #include "block/block_int.h"
34 #include "trace/control.h"
35 #include "crypto/init.h"
36 #include "qemu-version.h"
37 
38 #define CMD_NOFILE_OK   0x01
39 
40 static BlockBackend *qemuio_blk;
41 static bool quit_qemu_io;
42 
43 /* qemu-io commands passed using -c */
44 static int ncmdline;
45 static char **cmdline;
46 static bool imageOpts;
47 
48 static ReadLineState *readline_state;
49 
50 static int ttyEOF;
51 
52 static int get_eof_char(void)
53 {
54 #ifdef _WIN32
55     return 0x4; /* Ctrl-D */
56 #else
57     struct termios tty;
58     if (tcgetattr(STDIN_FILENO, &tty) != 0) {
59         if (errno == ENOTTY) {
60             return 0x0; /* just expect read() == 0 */
61         } else {
62             return 0x4; /* Ctrl-D */
63         }
64     }
65 
66     return tty.c_cc[VEOF];
67 #endif
68 }
69 
70 static int close_f(BlockBackend *blk, int argc, char **argv)
71 {
72     blk_unref(qemuio_blk);
73     qemuio_blk = NULL;
74     return 0;
75 }
76 
77 static const cmdinfo_t close_cmd = {
78     .name       = "close",
79     .altname    = "c",
80     .cfunc      = close_f,
81     .oneline    = "close the current open file",
82 };
83 
84 static int openfile(char *name, int flags, bool writethrough, bool force_share,
85                     QDict *opts)
86 {
87     Error *local_err = NULL;
88 
89     if (qemuio_blk) {
90         error_report("file open already, try 'help close'");
91         qobject_unref(opts);
92         return 1;
93     }
94 
95     if (force_share) {
96         if (!opts) {
97             opts = qdict_new();
98         }
99         if (qdict_haskey(opts, BDRV_OPT_FORCE_SHARE)
100             && strcmp(qdict_get_str(opts, BDRV_OPT_FORCE_SHARE), "on")) {
101             error_report("-U conflicts with image options");
102             qobject_unref(opts);
103             return 1;
104         }
105         qdict_put_str(opts, BDRV_OPT_FORCE_SHARE, "on");
106     }
107     qemuio_blk = blk_new_open(name, NULL, opts, flags, &local_err);
108     if (!qemuio_blk) {
109         error_reportf_err(local_err, "can't open%s%s: ",
110                           name ? " device " : "", name ?: "");
111         return 1;
112     }
113 
114     blk_set_enable_write_cache(qemuio_blk, !writethrough);
115 
116     return 0;
117 }
118 
119 static void open_help(void)
120 {
121     printf(
122 "\n"
123 " opens a new file in the requested mode\n"
124 "\n"
125 " Example:\n"
126 " 'open -n -o driver=raw /tmp/data' - opens raw data file read-write, uncached\n"
127 "\n"
128 " Opens a file for subsequent use by all of the other qemu-io commands.\n"
129 " -r, -- open file read-only\n"
130 " -s, -- use snapshot file\n"
131 " -C, -- use copy-on-read\n"
132 " -n, -- disable host cache, short for -t none\n"
133 " -U, -- force shared permissions\n"
134 " -k, -- use kernel AIO implementation (Linux only, prefer use of -i)\n"
135 " -i, -- use AIO mode (threads, native or io_uring)\n"
136 " -t, -- use the given cache mode for the image\n"
137 " -d, -- use the given discard mode for the image\n"
138 " -o, -- options to be given to the block driver"
139 "\n");
140 }
141 
142 static int open_f(BlockBackend *blk, int argc, char **argv);
143 
144 static const cmdinfo_t open_cmd = {
145     .name       = "open",
146     .altname    = "o",
147     .cfunc      = open_f,
148     .argmin     = 1,
149     .argmax     = -1,
150     .flags      = CMD_NOFILE_OK,
151     .args       = "[-rsCnkU] [-t cache] [-d discard] [-o options] [path]",
152     .oneline    = "open the file specified by path",
153     .help       = open_help,
154 };
155 
156 static QemuOptsList empty_opts = {
157     .name = "drive",
158     .merge_lists = true,
159     .head = QTAILQ_HEAD_INITIALIZER(empty_opts.head),
160     .desc = {
161         /* no elements => accept any params */
162         { /* end of list */ }
163     },
164 };
165 
166 static int open_f(BlockBackend *blk, int argc, char **argv)
167 {
168     int flags = BDRV_O_UNMAP;
169     int readonly = 0;
170     bool writethrough = true;
171     int c;
172     int ret;
173     QemuOpts *qopts;
174     QDict *opts;
175     bool force_share = false;
176 
177     while ((c = getopt(argc, argv, "snCro:ki:t:d:U")) != -1) {
178         switch (c) {
179         case 's':
180             flags |= BDRV_O_SNAPSHOT;
181             break;
182         case 'n':
183             flags |= BDRV_O_NOCACHE;
184             writethrough = false;
185             break;
186         case 'C':
187             flags |= BDRV_O_COPY_ON_READ;
188             break;
189         case 'r':
190             readonly = 1;
191             break;
192         case 'k':
193             flags |= BDRV_O_NATIVE_AIO;
194             break;
195         case 't':
196             if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) < 0) {
197                 error_report("Invalid cache option: %s", optarg);
198                 qemu_opts_reset(&empty_opts);
199                 return -EINVAL;
200             }
201             break;
202         case 'd':
203             if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
204                 error_report("Invalid discard option: %s", optarg);
205                 qemu_opts_reset(&empty_opts);
206                 return -EINVAL;
207             }
208             break;
209         case 'i':
210             if (bdrv_parse_aio(optarg, &flags) < 0) {
211                 error_report("Invalid aio option: %s", optarg);
212                 qemu_opts_reset(&empty_opts);
213                 return -EINVAL;
214             }
215             break;
216         case 'o':
217             if (imageOpts) {
218                 printf("--image-opts and 'open -o' are mutually exclusive\n");
219                 qemu_opts_reset(&empty_opts);
220                 return -EINVAL;
221             }
222             if (!qemu_opts_parse_noisily(&empty_opts, optarg, false)) {
223                 qemu_opts_reset(&empty_opts);
224                 return -EINVAL;
225             }
226             break;
227         case 'U':
228             force_share = true;
229             break;
230         default:
231             qemu_opts_reset(&empty_opts);
232             qemuio_command_usage(&open_cmd);
233             return -EINVAL;
234         }
235     }
236 
237     if (!readonly) {
238         flags |= BDRV_O_RDWR;
239     }
240 
241     if (imageOpts && (optind == argc - 1)) {
242         if (!qemu_opts_parse_noisily(&empty_opts, argv[optind], false)) {
243             qemu_opts_reset(&empty_opts);
244             return -EINVAL;
245         }
246         optind++;
247     }
248 
249     qopts = qemu_opts_find(&empty_opts, NULL);
250     opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : NULL;
251     qemu_opts_reset(&empty_opts);
252 
253     if (optind == argc - 1) {
254         ret = openfile(argv[optind], flags, writethrough, force_share, opts);
255     } else if (optind == argc) {
256         ret = openfile(NULL, flags, writethrough, force_share, opts);
257     } else {
258         qobject_unref(opts);
259         qemuio_command_usage(&open_cmd);
260         return -EINVAL;
261     }
262 
263     if (ret) {
264         return -EINVAL;
265     }
266 
267     return 0;
268 }
269 
270 static int quit_f(BlockBackend *blk, int argc, char **argv)
271 {
272     quit_qemu_io = true;
273     return 0;
274 }
275 
276 static const cmdinfo_t quit_cmd = {
277     .name       = "quit",
278     .altname    = "q",
279     .cfunc      = quit_f,
280     .argmin     = -1,
281     .argmax     = -1,
282     .flags      = CMD_FLAG_GLOBAL,
283     .oneline    = "exit the program",
284 };
285 
286 static void usage(const char *name)
287 {
288     printf(
289 "Usage: %s [OPTIONS]... [-c STRING]... [file]\n"
290 "QEMU Disk exerciser\n"
291 "\n"
292 "  --object OBJECTDEF   define an object such as 'secret' for\n"
293 "                       passwords and/or encryption keys\n"
294 "  --image-opts         treat file as option string\n"
295 "  -c, --cmd STRING     execute command with its arguments\n"
296 "                       from the given string\n"
297 "  -f, --format FMT     specifies the block driver to use\n"
298 "  -r, --read-only      export read-only\n"
299 "  -s, --snapshot       use snapshot file\n"
300 "  -n, --nocache        disable host cache, short for -t none\n"
301 "  -C, --copy-on-read   enable copy-on-read\n"
302 "  -m, --misalign       misalign allocations for O_DIRECT\n"
303 "  -k, --native-aio     use kernel AIO implementation\n"
304 "                       (Linux only, prefer use of -i)\n"
305 "  -i, --aio=MODE       use AIO mode (threads, native or io_uring)\n"
306 "  -t, --cache=MODE     use the given cache mode for the image\n"
307 "  -d, --discard=MODE   use the given discard mode for the image\n"
308 "  -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
309 "                       specify tracing options\n"
310 "                       see qemu-img(1) man page for full description\n"
311 "  -U, --force-share    force shared permissions\n"
312 "  -h, --help           display this help and exit\n"
313 "  -V, --version        output version information and exit\n"
314 "\n"
315 "See '%s -c help' for information on available commands.\n"
316 "\n"
317 QEMU_HELP_BOTTOM "\n",
318     name, name);
319 }
320 
321 static char *get_prompt(void)
322 {
323     static char prompt[FILENAME_MAX + 2 /*"> "*/ + 1 /*"\0"*/ ];
324 
325     if (!prompt[0]) {
326         snprintf(prompt, sizeof(prompt), "%s> ", error_get_progname());
327     }
328 
329     return prompt;
330 }
331 
332 static void GCC_FMT_ATTR(2, 3) readline_printf_func(void *opaque,
333                                                     const char *fmt, ...)
334 {
335     va_list ap;
336     va_start(ap, fmt);
337     vprintf(fmt, ap);
338     va_end(ap);
339 }
340 
341 static void readline_flush_func(void *opaque)
342 {
343     fflush(stdout);
344 }
345 
346 static void readline_func(void *opaque, const char *str, void *readline_opaque)
347 {
348     char **line = readline_opaque;
349     *line = g_strdup(str);
350 }
351 
352 static void completion_match(const char *cmd, void *opaque)
353 {
354     readline_add_completion(readline_state, cmd);
355 }
356 
357 static void readline_completion_func(void *opaque, const char *str)
358 {
359     readline_set_completion_index(readline_state, strlen(str));
360     qemuio_complete_command(str, completion_match, NULL);
361 }
362 
363 static char *fetchline_readline(void)
364 {
365     char *line = NULL;
366 
367     readline_start(readline_state, get_prompt(), 0, readline_func, &line);
368     while (!line) {
369         int ch = getchar();
370         if (ttyEOF != 0x0 && ch == ttyEOF) {
371             printf("\n");
372             break;
373         }
374         readline_handle_byte(readline_state, ch);
375     }
376     return line;
377 }
378 
379 #define MAXREADLINESZ 1024
380 static char *fetchline_fgets(void)
381 {
382     char *p, *line = g_malloc(MAXREADLINESZ);
383 
384     if (!fgets(line, MAXREADLINESZ, stdin)) {
385         g_free(line);
386         return NULL;
387     }
388 
389     p = line + strlen(line);
390     if (p != line && p[-1] == '\n') {
391         p[-1] = '\0';
392     }
393 
394     return line;
395 }
396 
397 static char *fetchline(void)
398 {
399     if (readline_state) {
400         return fetchline_readline();
401     } else {
402         return fetchline_fgets();
403     }
404 }
405 
406 static void prep_fetchline(void *opaque)
407 {
408     int *fetchable = opaque;
409 
410     qemu_set_fd_handler(STDIN_FILENO, NULL, NULL, NULL);
411     *fetchable= 1;
412 }
413 
414 static int command_loop(void)
415 {
416     int i, fetchable = 0, prompted = 0;
417     int ret, last_error = 0;
418     char *input;
419 
420     for (i = 0; !quit_qemu_io && i < ncmdline; i++) {
421         ret = qemuio_command(qemuio_blk, cmdline[i]);
422         if (ret < 0) {
423             last_error = ret;
424         }
425     }
426     if (cmdline) {
427         g_free(cmdline);
428         return last_error;
429     }
430 
431     while (!quit_qemu_io) {
432         if (!prompted) {
433             printf("%s", get_prompt());
434             fflush(stdout);
435             qemu_set_fd_handler(STDIN_FILENO, prep_fetchline, NULL, &fetchable);
436             prompted = 1;
437         }
438 
439         main_loop_wait(false);
440 
441         if (!fetchable) {
442             continue;
443         }
444 
445         input = fetchline();
446         if (input == NULL) {
447             break;
448         }
449         ret = qemuio_command(qemuio_blk, input);
450         g_free(input);
451 
452         if (ret < 0) {
453             last_error = ret;
454         }
455 
456         prompted = 0;
457         fetchable = 0;
458     }
459     qemu_set_fd_handler(STDIN_FILENO, NULL, NULL, NULL);
460 
461     return last_error;
462 }
463 
464 static void add_user_command(char *optarg)
465 {
466     cmdline = g_renew(char *, cmdline, ++ncmdline);
467     cmdline[ncmdline-1] = optarg;
468 }
469 
470 static void reenable_tty_echo(void)
471 {
472     qemu_set_tty_echo(STDIN_FILENO, true);
473 }
474 
475 enum {
476     OPTION_OBJECT = 256,
477     OPTION_IMAGE_OPTS = 257,
478 };
479 
480 static QemuOptsList qemu_object_opts = {
481     .name = "object",
482     .implied_opt_name = "qom-type",
483     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
484     .desc = {
485         { }
486     },
487 };
488 
489 static bool qemu_io_object_print_help(const char *type, QemuOpts *opts)
490 {
491     if (user_creatable_print_help(type, opts)) {
492         exit(0);
493     }
494     return true;
495 }
496 
497 static QemuOptsList file_opts = {
498     .name = "file",
499     .implied_opt_name = "file",
500     .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
501     .desc = {
502         /* no elements => accept any params */
503         { /* end of list */ }
504     },
505 };
506 
507 int main(int argc, char **argv)
508 {
509     int readonly = 0;
510     const char *sopt = "hVc:d:f:rsnCmki:t:T:U";
511     const struct option lopt[] = {
512         { "help", no_argument, NULL, 'h' },
513         { "version", no_argument, NULL, 'V' },
514         { "cmd", required_argument, NULL, 'c' },
515         { "format", required_argument, NULL, 'f' },
516         { "read-only", no_argument, NULL, 'r' },
517         { "snapshot", no_argument, NULL, 's' },
518         { "nocache", no_argument, NULL, 'n' },
519         { "copy-on-read", no_argument, NULL, 'C' },
520         { "misalign", no_argument, NULL, 'm' },
521         { "native-aio", no_argument, NULL, 'k' },
522         { "aio", required_argument, NULL, 'i' },
523         { "discard", required_argument, NULL, 'd' },
524         { "cache", required_argument, NULL, 't' },
525         { "trace", required_argument, NULL, 'T' },
526         { "object", required_argument, NULL, OPTION_OBJECT },
527         { "image-opts", no_argument, NULL, OPTION_IMAGE_OPTS },
528         { "force-share", no_argument, 0, 'U'},
529         { NULL, 0, NULL, 0 }
530     };
531     int c;
532     int opt_index = 0;
533     int flags = BDRV_O_UNMAP;
534     int ret;
535     bool writethrough = true;
536     Error *local_error = NULL;
537     QDict *opts = NULL;
538     const char *format = NULL;
539     bool force_share = false;
540 
541 #ifdef CONFIG_POSIX
542     signal(SIGPIPE, SIG_IGN);
543 #endif
544 
545     socket_init();
546     error_init(argv[0]);
547     module_call_init(MODULE_INIT_TRACE);
548     qemu_init_exec_dir(argv[0]);
549 
550     qcrypto_init(&error_fatal);
551 
552     module_call_init(MODULE_INIT_QOM);
553     qemu_add_opts(&qemu_object_opts);
554     qemu_add_opts(&qemu_trace_opts);
555     bdrv_init();
556 
557     while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
558         switch (c) {
559         case 's':
560             flags |= BDRV_O_SNAPSHOT;
561             break;
562         case 'n':
563             flags |= BDRV_O_NOCACHE;
564             writethrough = false;
565             break;
566         case 'C':
567             flags |= BDRV_O_COPY_ON_READ;
568             break;
569         case 'd':
570             if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
571                 error_report("Invalid discard option: %s", optarg);
572                 exit(1);
573             }
574             break;
575         case 'f':
576             format = optarg;
577             break;
578         case 'c':
579             add_user_command(optarg);
580             break;
581         case 'r':
582             readonly = 1;
583             break;
584         case 'm':
585             qemuio_misalign = true;
586             break;
587         case 'k':
588             flags |= BDRV_O_NATIVE_AIO;
589             break;
590         case 'i':
591             if (bdrv_parse_aio(optarg, &flags) < 0) {
592                 error_report("Invalid aio option: %s", optarg);
593                 exit(1);
594             }
595             break;
596         case 't':
597             if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) < 0) {
598                 error_report("Invalid cache option: %s", optarg);
599                 exit(1);
600             }
601             break;
602         case 'T':
603             trace_opt_parse(optarg);
604             break;
605         case 'V':
606             printf("%s version " QEMU_FULL_VERSION "\n"
607                    QEMU_COPYRIGHT "\n", error_get_progname());
608             exit(0);
609         case 'h':
610             usage(error_get_progname());
611             exit(0);
612         case 'U':
613             force_share = true;
614             break;
615         case OPTION_OBJECT: {
616             QemuOpts *qopts;
617             qopts = qemu_opts_parse_noisily(&qemu_object_opts,
618                                             optarg, true);
619             if (!qopts) {
620                 exit(1);
621             }
622         }   break;
623         case OPTION_IMAGE_OPTS:
624             imageOpts = true;
625             break;
626         default:
627             usage(error_get_progname());
628             exit(1);
629         }
630     }
631 
632     if ((argc - optind) > 1) {
633         usage(error_get_progname());
634         exit(1);
635     }
636 
637     if (format && imageOpts) {
638         error_report("--image-opts and -f are mutually exclusive");
639         exit(1);
640     }
641 
642     if (qemu_init_main_loop(&local_error)) {
643         error_report_err(local_error);
644         exit(1);
645     }
646 
647     qemu_opts_foreach(&qemu_object_opts,
648                       user_creatable_add_opts_foreach,
649                       qemu_io_object_print_help, &error_fatal);
650 
651     if (!trace_init_backends()) {
652         exit(1);
653     }
654     trace_init_file();
655     qemu_set_log(LOG_TRACE);
656 
657     /* initialize commands */
658     qemuio_add_command(&quit_cmd);
659     qemuio_add_command(&open_cmd);
660     qemuio_add_command(&close_cmd);
661 
662     if (isatty(STDIN_FILENO)) {
663         ttyEOF = get_eof_char();
664         readline_state = readline_init(readline_printf_func,
665                                        readline_flush_func,
666                                        NULL,
667                                        readline_completion_func);
668         qemu_set_tty_echo(STDIN_FILENO, false);
669         atexit(reenable_tty_echo);
670     }
671 
672     /* open the device */
673     if (!readonly) {
674         flags |= BDRV_O_RDWR;
675     }
676 
677     if ((argc - optind) == 1) {
678         if (imageOpts) {
679             QemuOpts *qopts = NULL;
680             qopts = qemu_opts_parse_noisily(&file_opts, argv[optind], false);
681             if (!qopts) {
682                 exit(1);
683             }
684             opts = qemu_opts_to_qdict(qopts, NULL);
685             if (openfile(NULL, flags, writethrough, force_share, opts)) {
686                 exit(1);
687             }
688         } else {
689             if (format) {
690                 opts = qdict_new();
691                 qdict_put_str(opts, "driver", format);
692             }
693             if (openfile(argv[optind], flags, writethrough,
694                          force_share, opts)) {
695                 exit(1);
696             }
697         }
698     }
699     ret = command_loop();
700 
701     /*
702      * Make sure all outstanding requests complete before the program exits.
703      */
704     bdrv_drain_all();
705 
706     blk_unref(qemuio_blk);
707     g_free(readline_state);
708 
709     if (ret < 0) {
710         return 1;
711     } else {
712         return 0;
713     }
714 }
715