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