migration/vmstate: split up vmstate_base_addr
[qemu.git] / qemu-io-cmds.c
blob7ac1576d4c58d878ea849d11ed085c1f10932916
1 /*
2 * Command line utility to exercise the QEMU I/O path.
4 * Copyright (C) 2009-2016 Red Hat, Inc.
5 * Copyright (c) 2003-2005 Silicon Graphics, Inc.
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 */
11 #include "qemu/osdep.h"
12 #include "qapi/error.h"
13 #include "qemu-io.h"
14 #include "sysemu/block-backend.h"
15 #include "block/block.h"
16 #include "block/block_int.h" /* for info_f() */
17 #include "block/qapi.h"
18 #include "qemu/error-report.h"
19 #include "qemu/main-loop.h"
20 #include "qemu/timer.h"
21 #include "qemu/cutils.h"
23 #define CMD_NOFILE_OK 0x01
25 bool qemuio_misalign;
27 static cmdinfo_t *cmdtab;
28 static int ncmds;
30 static int compare_cmdname(const void *a, const void *b)
32 return strcmp(((const cmdinfo_t *)a)->name,
33 ((const cmdinfo_t *)b)->name);
36 void qemuio_add_command(const cmdinfo_t *ci)
38 cmdtab = g_renew(cmdinfo_t, cmdtab, ++ncmds);
39 cmdtab[ncmds - 1] = *ci;
40 qsort(cmdtab, ncmds, sizeof(*cmdtab), compare_cmdname);
43 int qemuio_command_usage(const cmdinfo_t *ci)
45 printf("%s %s -- %s\n", ci->name, ci->args, ci->oneline);
46 return 0;
49 static int init_check_command(BlockBackend *blk, const cmdinfo_t *ct)
51 if (ct->flags & CMD_FLAG_GLOBAL) {
52 return 1;
54 if (!(ct->flags & CMD_NOFILE_OK) && !blk) {
55 fprintf(stderr, "no file open, try 'help open'\n");
56 return 0;
58 return 1;
61 static int command(BlockBackend *blk, const cmdinfo_t *ct, int argc,
62 char **argv)
64 char *cmd = argv[0];
66 if (!init_check_command(blk, ct)) {
67 return 0;
70 if (argc - 1 < ct->argmin || (ct->argmax != -1 && argc - 1 > ct->argmax)) {
71 if (ct->argmax == -1) {
72 fprintf(stderr,
73 "bad argument count %d to %s, expected at least %d arguments\n",
74 argc-1, cmd, ct->argmin);
75 } else if (ct->argmin == ct->argmax) {
76 fprintf(stderr,
77 "bad argument count %d to %s, expected %d arguments\n",
78 argc-1, cmd, ct->argmin);
79 } else {
80 fprintf(stderr,
81 "bad argument count %d to %s, expected between %d and %d arguments\n",
82 argc-1, cmd, ct->argmin, ct->argmax);
84 return 0;
86 optind = 0;
87 return ct->cfunc(blk, argc, argv);
90 static const cmdinfo_t *find_command(const char *cmd)
92 cmdinfo_t *ct;
94 for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
95 if (strcmp(ct->name, cmd) == 0 ||
96 (ct->altname && strcmp(ct->altname, cmd) == 0))
98 return (const cmdinfo_t *)ct;
101 return NULL;
104 /* Invoke fn() for commands with a matching prefix */
105 void qemuio_complete_command(const char *input,
106 void (*fn)(const char *cmd, void *opaque),
107 void *opaque)
109 cmdinfo_t *ct;
110 size_t input_len = strlen(input);
112 for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
113 if (strncmp(input, ct->name, input_len) == 0) {
114 fn(ct->name, opaque);
119 static char **breakline(char *input, int *count)
121 int c = 0;
122 char *p;
123 char **rval = g_new0(char *, 1);
125 while (rval && (p = qemu_strsep(&input, " ")) != NULL) {
126 if (!*p) {
127 continue;
129 c++;
130 rval = g_renew(char *, rval, (c + 1));
131 rval[c - 1] = p;
132 rval[c] = NULL;
134 *count = c;
135 return rval;
138 static int64_t cvtnum(const char *s)
140 int err;
141 uint64_t value;
143 err = qemu_strtosz(s, NULL, &value);
144 if (err < 0) {
145 return err;
147 if (value > INT64_MAX) {
148 return -ERANGE;
150 return value;
153 static void print_cvtnum_err(int64_t rc, const char *arg)
155 switch (rc) {
156 case -EINVAL:
157 printf("Parsing error: non-numeric argument,"
158 " or extraneous/unrecognized suffix -- %s\n", arg);
159 break;
160 case -ERANGE:
161 printf("Parsing error: argument too large -- %s\n", arg);
162 break;
163 default:
164 printf("Parsing error: %s\n", arg);
168 #define EXABYTES(x) ((long long)(x) << 60)
169 #define PETABYTES(x) ((long long)(x) << 50)
170 #define TERABYTES(x) ((long long)(x) << 40)
171 #define GIGABYTES(x) ((long long)(x) << 30)
172 #define MEGABYTES(x) ((long long)(x) << 20)
173 #define KILOBYTES(x) ((long long)(x) << 10)
175 #define TO_EXABYTES(x) ((x) / EXABYTES(1))
176 #define TO_PETABYTES(x) ((x) / PETABYTES(1))
177 #define TO_TERABYTES(x) ((x) / TERABYTES(1))
178 #define TO_GIGABYTES(x) ((x) / GIGABYTES(1))
179 #define TO_MEGABYTES(x) ((x) / MEGABYTES(1))
180 #define TO_KILOBYTES(x) ((x) / KILOBYTES(1))
182 static void cvtstr(double value, char *str, size_t size)
184 char *trim;
185 const char *suffix;
187 if (value >= EXABYTES(1)) {
188 suffix = " EiB";
189 snprintf(str, size - 4, "%.3f", TO_EXABYTES(value));
190 } else if (value >= PETABYTES(1)) {
191 suffix = " PiB";
192 snprintf(str, size - 4, "%.3f", TO_PETABYTES(value));
193 } else if (value >= TERABYTES(1)) {
194 suffix = " TiB";
195 snprintf(str, size - 4, "%.3f", TO_TERABYTES(value));
196 } else if (value >= GIGABYTES(1)) {
197 suffix = " GiB";
198 snprintf(str, size - 4, "%.3f", TO_GIGABYTES(value));
199 } else if (value >= MEGABYTES(1)) {
200 suffix = " MiB";
201 snprintf(str, size - 4, "%.3f", TO_MEGABYTES(value));
202 } else if (value >= KILOBYTES(1)) {
203 suffix = " KiB";
204 snprintf(str, size - 4, "%.3f", TO_KILOBYTES(value));
205 } else {
206 suffix = " bytes";
207 snprintf(str, size - 6, "%f", value);
210 trim = strstr(str, ".000");
211 if (trim) {
212 strcpy(trim, suffix);
213 } else {
214 strcat(str, suffix);
220 static struct timeval tsub(struct timeval t1, struct timeval t2)
222 t1.tv_usec -= t2.tv_usec;
223 if (t1.tv_usec < 0) {
224 t1.tv_usec += 1000000;
225 t1.tv_sec--;
227 t1.tv_sec -= t2.tv_sec;
228 return t1;
231 static double tdiv(double value, struct timeval tv)
233 return value / ((double)tv.tv_sec + ((double)tv.tv_usec / 1000000.0));
236 #define HOURS(sec) ((sec) / (60 * 60))
237 #define MINUTES(sec) (((sec) % (60 * 60)) / 60)
238 #define SECONDS(sec) ((sec) % 60)
240 enum {
241 DEFAULT_TIME = 0x0,
242 TERSE_FIXED_TIME = 0x1,
243 VERBOSE_FIXED_TIME = 0x2,
246 static void timestr(struct timeval *tv, char *ts, size_t size, int format)
248 double usec = (double)tv->tv_usec / 1000000.0;
250 if (format & TERSE_FIXED_TIME) {
251 if (!HOURS(tv->tv_sec)) {
252 snprintf(ts, size, "%u:%02u.%02u",
253 (unsigned int) MINUTES(tv->tv_sec),
254 (unsigned int) SECONDS(tv->tv_sec),
255 (unsigned int) (usec * 100));
256 return;
258 format |= VERBOSE_FIXED_TIME; /* fallback if hours needed */
261 if ((format & VERBOSE_FIXED_TIME) || tv->tv_sec) {
262 snprintf(ts, size, "%u:%02u:%02u.%02u",
263 (unsigned int) HOURS(tv->tv_sec),
264 (unsigned int) MINUTES(tv->tv_sec),
265 (unsigned int) SECONDS(tv->tv_sec),
266 (unsigned int) (usec * 100));
267 } else {
268 snprintf(ts, size, "0.%04u sec", (unsigned int) (usec * 10000));
273 * Parse the pattern argument to various sub-commands.
275 * Because the pattern is used as an argument to memset it must evaluate
276 * to an unsigned integer that fits into a single byte.
278 static int parse_pattern(const char *arg)
280 char *endptr = NULL;
281 long pattern;
283 pattern = strtol(arg, &endptr, 0);
284 if (pattern < 0 || pattern > UCHAR_MAX || *endptr != '\0') {
285 printf("%s is not a valid pattern byte\n", arg);
286 return -1;
289 return pattern;
293 * Memory allocation helpers.
295 * Make sure memory is aligned by default, or purposefully misaligned if
296 * that is specified on the command line.
299 #define MISALIGN_OFFSET 16
300 static void *qemu_io_alloc(BlockBackend *blk, size_t len, int pattern)
302 void *buf;
304 if (qemuio_misalign) {
305 len += MISALIGN_OFFSET;
307 buf = blk_blockalign(blk, len);
308 memset(buf, pattern, len);
309 if (qemuio_misalign) {
310 buf += MISALIGN_OFFSET;
312 return buf;
315 static void qemu_io_free(void *p)
317 if (qemuio_misalign) {
318 p -= MISALIGN_OFFSET;
320 qemu_vfree(p);
323 static void dump_buffer(const void *buffer, int64_t offset, int64_t len)
325 uint64_t i;
326 int j;
327 const uint8_t *p;
329 for (i = 0, p = buffer; i < len; i += 16) {
330 const uint8_t *s = p;
332 printf("%08" PRIx64 ": ", offset + i);
333 for (j = 0; j < 16 && i + j < len; j++, p++) {
334 printf("%02x ", *p);
336 printf(" ");
337 for (j = 0; j < 16 && i + j < len; j++, s++) {
338 if (isalnum(*s)) {
339 printf("%c", *s);
340 } else {
341 printf(".");
344 printf("\n");
348 static void print_report(const char *op, struct timeval *t, int64_t offset,
349 int64_t count, int64_t total, int cnt, bool Cflag)
351 char s1[64], s2[64], ts[64];
353 timestr(t, ts, sizeof(ts), Cflag ? VERBOSE_FIXED_TIME : 0);
354 if (!Cflag) {
355 cvtstr((double)total, s1, sizeof(s1));
356 cvtstr(tdiv((double)total, *t), s2, sizeof(s2));
357 printf("%s %"PRId64"/%"PRId64" bytes at offset %" PRId64 "\n",
358 op, total, count, offset);
359 printf("%s, %d ops; %s (%s/sec and %.4f ops/sec)\n",
360 s1, cnt, ts, s2, tdiv((double)cnt, *t));
361 } else {/* bytes,ops,time,bytes/sec,ops/sec */
362 printf("%"PRId64",%d,%s,%.3f,%.3f\n",
363 total, cnt, ts,
364 tdiv((double)total, *t),
365 tdiv((double)cnt, *t));
370 * Parse multiple length statements for vectored I/O, and construct an I/O
371 * vector matching it.
373 static void *
374 create_iovec(BlockBackend *blk, QEMUIOVector *qiov, char **argv, int nr_iov,
375 int pattern)
377 size_t *sizes = g_new0(size_t, nr_iov);
378 size_t count = 0;
379 void *buf = NULL;
380 void *p;
381 int i;
383 for (i = 0; i < nr_iov; i++) {
384 char *arg = argv[i];
385 int64_t len;
387 len = cvtnum(arg);
388 if (len < 0) {
389 print_cvtnum_err(len, arg);
390 goto fail;
393 if (len > BDRV_REQUEST_MAX_BYTES) {
394 printf("Argument '%s' exceeds maximum size %" PRIu64 "\n", arg,
395 (uint64_t)BDRV_REQUEST_MAX_BYTES);
396 goto fail;
399 if (count > BDRV_REQUEST_MAX_BYTES - len) {
400 printf("The total number of bytes exceed the maximum size %" PRIu64
401 "\n", (uint64_t)BDRV_REQUEST_MAX_BYTES);
402 goto fail;
405 sizes[i] = len;
406 count += len;
409 qemu_iovec_init(qiov, nr_iov);
411 buf = p = qemu_io_alloc(blk, count, pattern);
413 for (i = 0; i < nr_iov; i++) {
414 qemu_iovec_add(qiov, p, sizes[i]);
415 p += sizes[i];
418 fail:
419 g_free(sizes);
420 return buf;
423 static int do_pread(BlockBackend *blk, char *buf, int64_t offset,
424 int64_t count, int64_t *total)
426 if (count > INT_MAX) {
427 return -ERANGE;
430 *total = blk_pread(blk, offset, (uint8_t *)buf, count);
431 if (*total < 0) {
432 return *total;
434 return 1;
437 static int do_pwrite(BlockBackend *blk, char *buf, int64_t offset,
438 int64_t count, int flags, int64_t *total)
440 if (count > INT_MAX) {
441 return -ERANGE;
444 *total = blk_pwrite(blk, offset, (uint8_t *)buf, count, flags);
445 if (*total < 0) {
446 return *total;
448 return 1;
451 typedef struct {
452 BlockBackend *blk;
453 int64_t offset;
454 int64_t count;
455 int64_t *total;
456 int flags;
457 int ret;
458 bool done;
459 } CoWriteZeroes;
461 static void coroutine_fn co_pwrite_zeroes_entry(void *opaque)
463 CoWriteZeroes *data = opaque;
465 data->ret = blk_co_pwrite_zeroes(data->blk, data->offset, data->count,
466 data->flags);
467 data->done = true;
468 if (data->ret < 0) {
469 *data->total = data->ret;
470 return;
473 *data->total = data->count;
476 static int do_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
477 int64_t count, int flags, int64_t *total)
479 Coroutine *co;
480 CoWriteZeroes data = {
481 .blk = blk,
482 .offset = offset,
483 .count = count,
484 .total = total,
485 .flags = flags,
486 .done = false,
489 if (count > INT_MAX) {
490 return -ERANGE;
493 co = qemu_coroutine_create(co_pwrite_zeroes_entry, &data);
494 qemu_coroutine_enter(co);
495 while (!data.done) {
496 aio_poll(blk_get_aio_context(blk), true);
498 if (data.ret < 0) {
499 return data.ret;
500 } else {
501 return 1;
505 static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,
506 int64_t count, int64_t *total)
508 int ret;
510 if (count >> 9 > BDRV_REQUEST_MAX_SECTORS) {
511 return -ERANGE;
514 ret = blk_pwrite_compressed(blk, offset, buf, count);
515 if (ret < 0) {
516 return ret;
518 *total = count;
519 return 1;
522 static int do_load_vmstate(BlockBackend *blk, char *buf, int64_t offset,
523 int64_t count, int64_t *total)
525 if (count > INT_MAX) {
526 return -ERANGE;
529 *total = blk_load_vmstate(blk, (uint8_t *)buf, offset, count);
530 if (*total < 0) {
531 return *total;
533 return 1;
536 static int do_save_vmstate(BlockBackend *blk, char *buf, int64_t offset,
537 int64_t count, int64_t *total)
539 if (count > INT_MAX) {
540 return -ERANGE;
543 *total = blk_save_vmstate(blk, (uint8_t *)buf, offset, count);
544 if (*total < 0) {
545 return *total;
547 return 1;
550 #define NOT_DONE 0x7fffffff
551 static void aio_rw_done(void *opaque, int ret)
553 *(int *)opaque = ret;
556 static int do_aio_readv(BlockBackend *blk, QEMUIOVector *qiov,
557 int64_t offset, int *total)
559 int async_ret = NOT_DONE;
561 blk_aio_preadv(blk, offset, qiov, 0, aio_rw_done, &async_ret);
562 while (async_ret == NOT_DONE) {
563 main_loop_wait(false);
566 *total = qiov->size;
567 return async_ret < 0 ? async_ret : 1;
570 static int do_aio_writev(BlockBackend *blk, QEMUIOVector *qiov,
571 int64_t offset, int flags, int *total)
573 int async_ret = NOT_DONE;
575 blk_aio_pwritev(blk, offset, qiov, flags, aio_rw_done, &async_ret);
576 while (async_ret == NOT_DONE) {
577 main_loop_wait(false);
580 *total = qiov->size;
581 return async_ret < 0 ? async_ret : 1;
584 static void read_help(void)
586 printf(
587 "\n"
588 " reads a range of bytes from the given offset\n"
589 "\n"
590 " Example:\n"
591 " 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n"
592 "\n"
593 " Reads a segment of the currently open file, optionally dumping it to the\n"
594 " standard output stream (with -v option) for subsequent inspection.\n"
595 " -b, -- read from the VM state rather than the virtual disk\n"
596 " -C, -- report statistics in a machine parsable format\n"
597 " -l, -- length for pattern verification (only with -P)\n"
598 " -p, -- ignored for backwards compatibility\n"
599 " -P, -- use a pattern to verify read data\n"
600 " -q, -- quiet mode, do not show I/O statistics\n"
601 " -s, -- start offset for pattern verification (only with -P)\n"
602 " -v, -- dump buffer to standard output\n"
603 "\n");
606 static int read_f(BlockBackend *blk, int argc, char **argv);
608 static const cmdinfo_t read_cmd = {
609 .name = "read",
610 .altname = "r",
611 .cfunc = read_f,
612 .argmin = 2,
613 .argmax = -1,
614 .args = "[-abCqv] [-P pattern [-s off] [-l len]] off len",
615 .oneline = "reads a number of bytes at a specified offset",
616 .help = read_help,
619 static int read_f(BlockBackend *blk, int argc, char **argv)
621 struct timeval t1, t2;
622 bool Cflag = false, qflag = false, vflag = false;
623 bool Pflag = false, sflag = false, lflag = false, bflag = false;
624 int c, cnt;
625 char *buf;
626 int64_t offset;
627 int64_t count;
628 /* Some compilers get confused and warn if this is not initialized. */
629 int64_t total = 0;
630 int pattern = 0;
631 int64_t pattern_offset = 0, pattern_count = 0;
633 while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != -1) {
634 switch (c) {
635 case 'b':
636 bflag = true;
637 break;
638 case 'C':
639 Cflag = true;
640 break;
641 case 'l':
642 lflag = true;
643 pattern_count = cvtnum(optarg);
644 if (pattern_count < 0) {
645 print_cvtnum_err(pattern_count, optarg);
646 return 0;
648 break;
649 case 'p':
650 /* Ignored for backwards compatibility */
651 break;
652 case 'P':
653 Pflag = true;
654 pattern = parse_pattern(optarg);
655 if (pattern < 0) {
656 return 0;
658 break;
659 case 'q':
660 qflag = true;
661 break;
662 case 's':
663 sflag = true;
664 pattern_offset = cvtnum(optarg);
665 if (pattern_offset < 0) {
666 print_cvtnum_err(pattern_offset, optarg);
667 return 0;
669 break;
670 case 'v':
671 vflag = true;
672 break;
673 default:
674 return qemuio_command_usage(&read_cmd);
678 if (optind != argc - 2) {
679 return qemuio_command_usage(&read_cmd);
682 offset = cvtnum(argv[optind]);
683 if (offset < 0) {
684 print_cvtnum_err(offset, argv[optind]);
685 return 0;
688 optind++;
689 count = cvtnum(argv[optind]);
690 if (count < 0) {
691 print_cvtnum_err(count, argv[optind]);
692 return 0;
693 } else if (count > BDRV_REQUEST_MAX_BYTES) {
694 printf("length cannot exceed %" PRIu64 ", given %s\n",
695 (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
696 return 0;
699 if (!Pflag && (lflag || sflag)) {
700 return qemuio_command_usage(&read_cmd);
703 if (!lflag) {
704 pattern_count = count - pattern_offset;
707 if ((pattern_count < 0) || (pattern_count + pattern_offset > count)) {
708 printf("pattern verification range exceeds end of read data\n");
709 return 0;
712 if (bflag) {
713 if (offset & 0x1ff) {
714 printf("offset %" PRId64 " is not sector aligned\n",
715 offset);
716 return 0;
718 if (count & 0x1ff) {
719 printf("count %"PRId64" is not sector aligned\n",
720 count);
721 return 0;
725 buf = qemu_io_alloc(blk, count, 0xab);
727 gettimeofday(&t1, NULL);
728 if (bflag) {
729 cnt = do_load_vmstate(blk, buf, offset, count, &total);
730 } else {
731 cnt = do_pread(blk, buf, offset, count, &total);
733 gettimeofday(&t2, NULL);
735 if (cnt < 0) {
736 printf("read failed: %s\n", strerror(-cnt));
737 goto out;
740 if (Pflag) {
741 void *cmp_buf = g_malloc(pattern_count);
742 memset(cmp_buf, pattern, pattern_count);
743 if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {
744 printf("Pattern verification failed at offset %"
745 PRId64 ", %"PRId64" bytes\n",
746 offset + pattern_offset, pattern_count);
748 g_free(cmp_buf);
751 if (qflag) {
752 goto out;
755 if (vflag) {
756 dump_buffer(buf, offset, count);
759 /* Finally, report back -- -C gives a parsable format */
760 t2 = tsub(t2, t1);
761 print_report("read", &t2, offset, count, total, cnt, Cflag);
763 out:
764 qemu_io_free(buf);
766 return 0;
769 static void readv_help(void)
771 printf(
772 "\n"
773 " reads a range of bytes from the given offset into multiple buffers\n"
774 "\n"
775 " Example:\n"
776 " 'readv -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
777 "\n"
778 " Reads a segment of the currently open file, optionally dumping it to the\n"
779 " standard output stream (with -v option) for subsequent inspection.\n"
780 " Uses multiple iovec buffers if more than one byte range is specified.\n"
781 " -C, -- report statistics in a machine parsable format\n"
782 " -P, -- use a pattern to verify read data\n"
783 " -v, -- dump buffer to standard output\n"
784 " -q, -- quiet mode, do not show I/O statistics\n"
785 "\n");
788 static int readv_f(BlockBackend *blk, int argc, char **argv);
790 static const cmdinfo_t readv_cmd = {
791 .name = "readv",
792 .cfunc = readv_f,
793 .argmin = 2,
794 .argmax = -1,
795 .args = "[-Cqv] [-P pattern] off len [len..]",
796 .oneline = "reads a number of bytes at a specified offset",
797 .help = readv_help,
800 static int readv_f(BlockBackend *blk, int argc, char **argv)
802 struct timeval t1, t2;
803 bool Cflag = false, qflag = false, vflag = false;
804 int c, cnt;
805 char *buf;
806 int64_t offset;
807 /* Some compilers get confused and warn if this is not initialized. */
808 int total = 0;
809 int nr_iov;
810 QEMUIOVector qiov;
811 int pattern = 0;
812 bool Pflag = false;
814 while ((c = getopt(argc, argv, "CP:qv")) != -1) {
815 switch (c) {
816 case 'C':
817 Cflag = true;
818 break;
819 case 'P':
820 Pflag = true;
821 pattern = parse_pattern(optarg);
822 if (pattern < 0) {
823 return 0;
825 break;
826 case 'q':
827 qflag = true;
828 break;
829 case 'v':
830 vflag = true;
831 break;
832 default:
833 return qemuio_command_usage(&readv_cmd);
837 if (optind > argc - 2) {
838 return qemuio_command_usage(&readv_cmd);
842 offset = cvtnum(argv[optind]);
843 if (offset < 0) {
844 print_cvtnum_err(offset, argv[optind]);
845 return 0;
847 optind++;
849 nr_iov = argc - optind;
850 buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, 0xab);
851 if (buf == NULL) {
852 return 0;
855 gettimeofday(&t1, NULL);
856 cnt = do_aio_readv(blk, &qiov, offset, &total);
857 gettimeofday(&t2, NULL);
859 if (cnt < 0) {
860 printf("readv failed: %s\n", strerror(-cnt));
861 goto out;
864 if (Pflag) {
865 void *cmp_buf = g_malloc(qiov.size);
866 memset(cmp_buf, pattern, qiov.size);
867 if (memcmp(buf, cmp_buf, qiov.size)) {
868 printf("Pattern verification failed at offset %"
869 PRId64 ", %zd bytes\n", offset, qiov.size);
871 g_free(cmp_buf);
874 if (qflag) {
875 goto out;
878 if (vflag) {
879 dump_buffer(buf, offset, qiov.size);
882 /* Finally, report back -- -C gives a parsable format */
883 t2 = tsub(t2, t1);
884 print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
886 out:
887 qemu_iovec_destroy(&qiov);
888 qemu_io_free(buf);
889 return 0;
892 static void write_help(void)
894 printf(
895 "\n"
896 " writes a range of bytes from the given offset\n"
897 "\n"
898 " Example:\n"
899 " 'write 512 1k' - writes 1 kilobyte at 512 bytes into the open file\n"
900 "\n"
901 " Writes into a segment of the currently open file, using a buffer\n"
902 " filled with a set pattern (0xcdcdcdcd).\n"
903 " -b, -- write to the VM state rather than the virtual disk\n"
904 " -c, -- write compressed data with blk_write_compressed\n"
905 " -f, -- use Force Unit Access semantics\n"
906 " -p, -- ignored for backwards compatibility\n"
907 " -P, -- use different pattern to fill file\n"
908 " -C, -- report statistics in a machine parsable format\n"
909 " -q, -- quiet mode, do not show I/O statistics\n"
910 " -u, -- with -z, allow unmapping\n"
911 " -z, -- write zeroes using blk_co_pwrite_zeroes\n"
912 "\n");
915 static int write_f(BlockBackend *blk, int argc, char **argv);
917 static const cmdinfo_t write_cmd = {
918 .name = "write",
919 .altname = "w",
920 .cfunc = write_f,
921 .argmin = 2,
922 .argmax = -1,
923 .args = "[-bcCfquz] [-P pattern] off len",
924 .oneline = "writes a number of bytes at a specified offset",
925 .help = write_help,
928 static int write_f(BlockBackend *blk, int argc, char **argv)
930 struct timeval t1, t2;
931 bool Cflag = false, qflag = false, bflag = false;
932 bool Pflag = false, zflag = false, cflag = false;
933 int flags = 0;
934 int c, cnt;
935 char *buf = NULL;
936 int64_t offset;
937 int64_t count;
938 /* Some compilers get confused and warn if this is not initialized. */
939 int64_t total = 0;
940 int pattern = 0xcd;
942 while ((c = getopt(argc, argv, "bcCfpP:quz")) != -1) {
943 switch (c) {
944 case 'b':
945 bflag = true;
946 break;
947 case 'c':
948 cflag = true;
949 break;
950 case 'C':
951 Cflag = true;
952 break;
953 case 'f':
954 flags |= BDRV_REQ_FUA;
955 break;
956 case 'p':
957 /* Ignored for backwards compatibility */
958 break;
959 case 'P':
960 Pflag = true;
961 pattern = parse_pattern(optarg);
962 if (pattern < 0) {
963 return 0;
965 break;
966 case 'q':
967 qflag = true;
968 break;
969 case 'u':
970 flags |= BDRV_REQ_MAY_UNMAP;
971 break;
972 case 'z':
973 zflag = true;
974 break;
975 default:
976 return qemuio_command_usage(&write_cmd);
980 if (optind != argc - 2) {
981 return qemuio_command_usage(&write_cmd);
984 if (bflag && zflag) {
985 printf("-b and -z cannot be specified at the same time\n");
986 return 0;
989 if ((flags & BDRV_REQ_FUA) && (bflag || cflag)) {
990 printf("-f and -b or -c cannot be specified at the same time\n");
991 return 0;
994 if ((flags & BDRV_REQ_MAY_UNMAP) && !zflag) {
995 printf("-u requires -z to be specified\n");
996 return 0;
999 if (zflag && Pflag) {
1000 printf("-z and -P cannot be specified at the same time\n");
1001 return 0;
1004 offset = cvtnum(argv[optind]);
1005 if (offset < 0) {
1006 print_cvtnum_err(offset, argv[optind]);
1007 return 0;
1010 optind++;
1011 count = cvtnum(argv[optind]);
1012 if (count < 0) {
1013 print_cvtnum_err(count, argv[optind]);
1014 return 0;
1015 } else if (count > BDRV_REQUEST_MAX_BYTES) {
1016 printf("length cannot exceed %" PRIu64 ", given %s\n",
1017 (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
1018 return 0;
1021 if (bflag || cflag) {
1022 if (offset & 0x1ff) {
1023 printf("offset %" PRId64 " is not sector aligned\n",
1024 offset);
1025 return 0;
1028 if (count & 0x1ff) {
1029 printf("count %"PRId64" is not sector aligned\n",
1030 count);
1031 return 0;
1035 if (!zflag) {
1036 buf = qemu_io_alloc(blk, count, pattern);
1039 gettimeofday(&t1, NULL);
1040 if (bflag) {
1041 cnt = do_save_vmstate(blk, buf, offset, count, &total);
1042 } else if (zflag) {
1043 cnt = do_co_pwrite_zeroes(blk, offset, count, flags, &total);
1044 } else if (cflag) {
1045 cnt = do_write_compressed(blk, buf, offset, count, &total);
1046 } else {
1047 cnt = do_pwrite(blk, buf, offset, count, flags, &total);
1049 gettimeofday(&t2, NULL);
1051 if (cnt < 0) {
1052 printf("write failed: %s\n", strerror(-cnt));
1053 goto out;
1056 if (qflag) {
1057 goto out;
1060 /* Finally, report back -- -C gives a parsable format */
1061 t2 = tsub(t2, t1);
1062 print_report("wrote", &t2, offset, count, total, cnt, Cflag);
1064 out:
1065 if (!zflag) {
1066 qemu_io_free(buf);
1069 return 0;
1072 static void
1073 writev_help(void)
1075 printf(
1076 "\n"
1077 " writes a range of bytes from the given offset source from multiple buffers\n"
1078 "\n"
1079 " Example:\n"
1080 " 'writev 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
1081 "\n"
1082 " Writes into a segment of the currently open file, using a buffer\n"
1083 " filled with a set pattern (0xcdcdcdcd).\n"
1084 " -P, -- use different pattern to fill file\n"
1085 " -C, -- report statistics in a machine parsable format\n"
1086 " -f, -- use Force Unit Access semantics\n"
1087 " -q, -- quiet mode, do not show I/O statistics\n"
1088 "\n");
1091 static int writev_f(BlockBackend *blk, int argc, char **argv);
1093 static const cmdinfo_t writev_cmd = {
1094 .name = "writev",
1095 .cfunc = writev_f,
1096 .argmin = 2,
1097 .argmax = -1,
1098 .args = "[-Cfq] [-P pattern] off len [len..]",
1099 .oneline = "writes a number of bytes at a specified offset",
1100 .help = writev_help,
1103 static int writev_f(BlockBackend *blk, int argc, char **argv)
1105 struct timeval t1, t2;
1106 bool Cflag = false, qflag = false;
1107 int flags = 0;
1108 int c, cnt;
1109 char *buf;
1110 int64_t offset;
1111 /* Some compilers get confused and warn if this is not initialized. */
1112 int total = 0;
1113 int nr_iov;
1114 int pattern = 0xcd;
1115 QEMUIOVector qiov;
1117 while ((c = getopt(argc, argv, "CfqP:")) != -1) {
1118 switch (c) {
1119 case 'C':
1120 Cflag = true;
1121 break;
1122 case 'f':
1123 flags |= BDRV_REQ_FUA;
1124 break;
1125 case 'q':
1126 qflag = true;
1127 break;
1128 case 'P':
1129 pattern = parse_pattern(optarg);
1130 if (pattern < 0) {
1131 return 0;
1133 break;
1134 default:
1135 return qemuio_command_usage(&writev_cmd);
1139 if (optind > argc - 2) {
1140 return qemuio_command_usage(&writev_cmd);
1143 offset = cvtnum(argv[optind]);
1144 if (offset < 0) {
1145 print_cvtnum_err(offset, argv[optind]);
1146 return 0;
1148 optind++;
1150 nr_iov = argc - optind;
1151 buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern);
1152 if (buf == NULL) {
1153 return 0;
1156 gettimeofday(&t1, NULL);
1157 cnt = do_aio_writev(blk, &qiov, offset, flags, &total);
1158 gettimeofday(&t2, NULL);
1160 if (cnt < 0) {
1161 printf("writev failed: %s\n", strerror(-cnt));
1162 goto out;
1165 if (qflag) {
1166 goto out;
1169 /* Finally, report back -- -C gives a parsable format */
1170 t2 = tsub(t2, t1);
1171 print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);
1172 out:
1173 qemu_iovec_destroy(&qiov);
1174 qemu_io_free(buf);
1175 return 0;
1178 struct aio_ctx {
1179 BlockBackend *blk;
1180 QEMUIOVector qiov;
1181 int64_t offset;
1182 char *buf;
1183 bool qflag;
1184 bool vflag;
1185 bool Cflag;
1186 bool Pflag;
1187 bool zflag;
1188 BlockAcctCookie acct;
1189 int pattern;
1190 struct timeval t1;
1193 static void aio_write_done(void *opaque, int ret)
1195 struct aio_ctx *ctx = opaque;
1196 struct timeval t2;
1198 gettimeofday(&t2, NULL);
1201 if (ret < 0) {
1202 printf("aio_write failed: %s\n", strerror(-ret));
1203 block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
1204 goto out;
1207 block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
1209 if (ctx->qflag) {
1210 goto out;
1213 /* Finally, report back -- -C gives a parsable format */
1214 t2 = tsub(t2, ctx->t1);
1215 print_report("wrote", &t2, ctx->offset, ctx->qiov.size,
1216 ctx->qiov.size, 1, ctx->Cflag);
1217 out:
1218 if (!ctx->zflag) {
1219 qemu_io_free(ctx->buf);
1220 qemu_iovec_destroy(&ctx->qiov);
1222 g_free(ctx);
1225 static void aio_read_done(void *opaque, int ret)
1227 struct aio_ctx *ctx = opaque;
1228 struct timeval t2;
1230 gettimeofday(&t2, NULL);
1232 if (ret < 0) {
1233 printf("readv failed: %s\n", strerror(-ret));
1234 block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
1235 goto out;
1238 if (ctx->Pflag) {
1239 void *cmp_buf = g_malloc(ctx->qiov.size);
1241 memset(cmp_buf, ctx->pattern, ctx->qiov.size);
1242 if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {
1243 printf("Pattern verification failed at offset %"
1244 PRId64 ", %zd bytes\n", ctx->offset, ctx->qiov.size);
1246 g_free(cmp_buf);
1249 block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
1251 if (ctx->qflag) {
1252 goto out;
1255 if (ctx->vflag) {
1256 dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);
1259 /* Finally, report back -- -C gives a parsable format */
1260 t2 = tsub(t2, ctx->t1);
1261 print_report("read", &t2, ctx->offset, ctx->qiov.size,
1262 ctx->qiov.size, 1, ctx->Cflag);
1263 out:
1264 qemu_io_free(ctx->buf);
1265 qemu_iovec_destroy(&ctx->qiov);
1266 g_free(ctx);
1269 static void aio_read_help(void)
1271 printf(
1272 "\n"
1273 " asynchronously reads a range of bytes from the given offset\n"
1274 "\n"
1275 " Example:\n"
1276 " 'aio_read -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
1277 "\n"
1278 " Reads a segment of the currently open file, optionally dumping it to the\n"
1279 " standard output stream (with -v option) for subsequent inspection.\n"
1280 " The read is performed asynchronously and the aio_flush command must be\n"
1281 " used to ensure all outstanding aio requests have been completed.\n"
1282 " -C, -- report statistics in a machine parsable format\n"
1283 " -P, -- use a pattern to verify read data\n"
1284 " -i, -- treat request as invalid, for exercising stats\n"
1285 " -v, -- dump buffer to standard output\n"
1286 " -q, -- quiet mode, do not show I/O statistics\n"
1287 "\n");
1290 static int aio_read_f(BlockBackend *blk, int argc, char **argv);
1292 static const cmdinfo_t aio_read_cmd = {
1293 .name = "aio_read",
1294 .cfunc = aio_read_f,
1295 .argmin = 2,
1296 .argmax = -1,
1297 .args = "[-Ciqv] [-P pattern] off len [len..]",
1298 .oneline = "asynchronously reads a number of bytes",
1299 .help = aio_read_help,
1302 static int aio_read_f(BlockBackend *blk, int argc, char **argv)
1304 int nr_iov, c;
1305 struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
1307 ctx->blk = blk;
1308 while ((c = getopt(argc, argv, "CP:iqv")) != -1) {
1309 switch (c) {
1310 case 'C':
1311 ctx->Cflag = true;
1312 break;
1313 case 'P':
1314 ctx->Pflag = true;
1315 ctx->pattern = parse_pattern(optarg);
1316 if (ctx->pattern < 0) {
1317 g_free(ctx);
1318 return 0;
1320 break;
1321 case 'i':
1322 printf("injecting invalid read request\n");
1323 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
1324 g_free(ctx);
1325 return 0;
1326 case 'q':
1327 ctx->qflag = true;
1328 break;
1329 case 'v':
1330 ctx->vflag = true;
1331 break;
1332 default:
1333 g_free(ctx);
1334 return qemuio_command_usage(&aio_read_cmd);
1338 if (optind > argc - 2) {
1339 g_free(ctx);
1340 return qemuio_command_usage(&aio_read_cmd);
1343 ctx->offset = cvtnum(argv[optind]);
1344 if (ctx->offset < 0) {
1345 print_cvtnum_err(ctx->offset, argv[optind]);
1346 g_free(ctx);
1347 return 0;
1349 optind++;
1351 nr_iov = argc - optind;
1352 ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, 0xab);
1353 if (ctx->buf == NULL) {
1354 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
1355 g_free(ctx);
1356 return 0;
1359 gettimeofday(&ctx->t1, NULL);
1360 block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
1361 BLOCK_ACCT_READ);
1362 blk_aio_preadv(blk, ctx->offset, &ctx->qiov, 0, aio_read_done, ctx);
1363 return 0;
1366 static void aio_write_help(void)
1368 printf(
1369 "\n"
1370 " asynchronously writes a range of bytes from the given offset source\n"
1371 " from multiple buffers\n"
1372 "\n"
1373 " Example:\n"
1374 " 'aio_write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
1375 "\n"
1376 " Writes into a segment of the currently open file, using a buffer\n"
1377 " filled with a set pattern (0xcdcdcdcd).\n"
1378 " The write is performed asynchronously and the aio_flush command must be\n"
1379 " used to ensure all outstanding aio requests have been completed.\n"
1380 " -P, -- use different pattern to fill file\n"
1381 " -C, -- report statistics in a machine parsable format\n"
1382 " -f, -- use Force Unit Access semantics\n"
1383 " -i, -- treat request as invalid, for exercising stats\n"
1384 " -q, -- quiet mode, do not show I/O statistics\n"
1385 " -u, -- with -z, allow unmapping\n"
1386 " -z, -- write zeroes using blk_aio_pwrite_zeroes\n"
1387 "\n");
1390 static int aio_write_f(BlockBackend *blk, int argc, char **argv);
1392 static const cmdinfo_t aio_write_cmd = {
1393 .name = "aio_write",
1394 .cfunc = aio_write_f,
1395 .argmin = 2,
1396 .argmax = -1,
1397 .args = "[-Cfiquz] [-P pattern] off len [len..]",
1398 .oneline = "asynchronously writes a number of bytes",
1399 .help = aio_write_help,
1402 static int aio_write_f(BlockBackend *blk, int argc, char **argv)
1404 int nr_iov, c;
1405 int pattern = 0xcd;
1406 struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
1407 int flags = 0;
1409 ctx->blk = blk;
1410 while ((c = getopt(argc, argv, "CfiqP:uz")) != -1) {
1411 switch (c) {
1412 case 'C':
1413 ctx->Cflag = true;
1414 break;
1415 case 'f':
1416 flags |= BDRV_REQ_FUA;
1417 break;
1418 case 'q':
1419 ctx->qflag = true;
1420 break;
1421 case 'u':
1422 flags |= BDRV_REQ_MAY_UNMAP;
1423 break;
1424 case 'P':
1425 pattern = parse_pattern(optarg);
1426 if (pattern < 0) {
1427 g_free(ctx);
1428 return 0;
1430 break;
1431 case 'i':
1432 printf("injecting invalid write request\n");
1433 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
1434 g_free(ctx);
1435 return 0;
1436 case 'z':
1437 ctx->zflag = true;
1438 break;
1439 default:
1440 g_free(ctx);
1441 return qemuio_command_usage(&aio_write_cmd);
1445 if (optind > argc - 2) {
1446 g_free(ctx);
1447 return qemuio_command_usage(&aio_write_cmd);
1450 if (ctx->zflag && optind != argc - 2) {
1451 printf("-z supports only a single length parameter\n");
1452 g_free(ctx);
1453 return 0;
1456 if ((flags & BDRV_REQ_MAY_UNMAP) && !ctx->zflag) {
1457 printf("-u requires -z to be specified\n");
1458 g_free(ctx);
1459 return 0;
1462 if (ctx->zflag && ctx->Pflag) {
1463 printf("-z and -P cannot be specified at the same time\n");
1464 g_free(ctx);
1465 return 0;
1468 ctx->offset = cvtnum(argv[optind]);
1469 if (ctx->offset < 0) {
1470 print_cvtnum_err(ctx->offset, argv[optind]);
1471 g_free(ctx);
1472 return 0;
1474 optind++;
1476 if (ctx->zflag) {
1477 int64_t count = cvtnum(argv[optind]);
1478 if (count < 0) {
1479 print_cvtnum_err(count, argv[optind]);
1480 g_free(ctx);
1481 return 0;
1484 ctx->qiov.size = count;
1485 blk_aio_pwrite_zeroes(blk, ctx->offset, count, flags, aio_write_done,
1486 ctx);
1487 } else {
1488 nr_iov = argc - optind;
1489 ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov,
1490 pattern);
1491 if (ctx->buf == NULL) {
1492 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
1493 g_free(ctx);
1494 return 0;
1497 gettimeofday(&ctx->t1, NULL);
1498 block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
1499 BLOCK_ACCT_WRITE);
1501 blk_aio_pwritev(blk, ctx->offset, &ctx->qiov, flags, aio_write_done,
1502 ctx);
1504 return 0;
1507 static int aio_flush_f(BlockBackend *blk, int argc, char **argv)
1509 BlockAcctCookie cookie;
1510 block_acct_start(blk_get_stats(blk), &cookie, 0, BLOCK_ACCT_FLUSH);
1511 blk_drain_all();
1512 block_acct_done(blk_get_stats(blk), &cookie);
1513 return 0;
1516 static const cmdinfo_t aio_flush_cmd = {
1517 .name = "aio_flush",
1518 .cfunc = aio_flush_f,
1519 .oneline = "completes all outstanding aio requests"
1522 static int flush_f(BlockBackend *blk, int argc, char **argv)
1524 blk_flush(blk);
1525 return 0;
1528 static const cmdinfo_t flush_cmd = {
1529 .name = "flush",
1530 .altname = "f",
1531 .cfunc = flush_f,
1532 .oneline = "flush all in-core file state to disk",
1535 static int truncate_f(BlockBackend *blk, int argc, char **argv)
1537 int64_t offset;
1538 int ret;
1540 offset = cvtnum(argv[1]);
1541 if (offset < 0) {
1542 print_cvtnum_err(offset, argv[1]);
1543 return 0;
1546 ret = blk_truncate(blk, offset);
1547 if (ret < 0) {
1548 printf("truncate: %s\n", strerror(-ret));
1549 return 0;
1552 return 0;
1555 static const cmdinfo_t truncate_cmd = {
1556 .name = "truncate",
1557 .altname = "t",
1558 .cfunc = truncate_f,
1559 .argmin = 1,
1560 .argmax = 1,
1561 .args = "off",
1562 .oneline = "truncates the current file at the given offset",
1565 static int length_f(BlockBackend *blk, int argc, char **argv)
1567 int64_t size;
1568 char s1[64];
1570 size = blk_getlength(blk);
1571 if (size < 0) {
1572 printf("getlength: %s\n", strerror(-size));
1573 return 0;
1576 cvtstr(size, s1, sizeof(s1));
1577 printf("%s\n", s1);
1578 return 0;
1582 static const cmdinfo_t length_cmd = {
1583 .name = "length",
1584 .altname = "l",
1585 .cfunc = length_f,
1586 .oneline = "gets the length of the current file",
1590 static int info_f(BlockBackend *blk, int argc, char **argv)
1592 BlockDriverState *bs = blk_bs(blk);
1593 BlockDriverInfo bdi;
1594 ImageInfoSpecific *spec_info;
1595 char s1[64], s2[64];
1596 int ret;
1598 if (bs->drv && bs->drv->format_name) {
1599 printf("format name: %s\n", bs->drv->format_name);
1601 if (bs->drv && bs->drv->protocol_name) {
1602 printf("format name: %s\n", bs->drv->protocol_name);
1605 ret = bdrv_get_info(bs, &bdi);
1606 if (ret) {
1607 return 0;
1610 cvtstr(bdi.cluster_size, s1, sizeof(s1));
1611 cvtstr(bdi.vm_state_offset, s2, sizeof(s2));
1613 printf("cluster size: %s\n", s1);
1614 printf("vm state offset: %s\n", s2);
1616 spec_info = bdrv_get_specific_info(bs);
1617 if (spec_info) {
1618 printf("Format specific information:\n");
1619 bdrv_image_info_specific_dump(fprintf, stdout, spec_info);
1620 qapi_free_ImageInfoSpecific(spec_info);
1623 return 0;
1628 static const cmdinfo_t info_cmd = {
1629 .name = "info",
1630 .altname = "i",
1631 .cfunc = info_f,
1632 .oneline = "prints information about the current file",
1635 static void discard_help(void)
1637 printf(
1638 "\n"
1639 " discards a range of bytes from the given offset\n"
1640 "\n"
1641 " Example:\n"
1642 " 'discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n"
1643 "\n"
1644 " Discards a segment of the currently open file.\n"
1645 " -C, -- report statistics in a machine parsable format\n"
1646 " -q, -- quiet mode, do not show I/O statistics\n"
1647 "\n");
1650 static int discard_f(BlockBackend *blk, int argc, char **argv);
1652 static const cmdinfo_t discard_cmd = {
1653 .name = "discard",
1654 .altname = "d",
1655 .cfunc = discard_f,
1656 .argmin = 2,
1657 .argmax = -1,
1658 .args = "[-Cq] off len",
1659 .oneline = "discards a number of bytes at a specified offset",
1660 .help = discard_help,
1663 static int discard_f(BlockBackend *blk, int argc, char **argv)
1665 struct timeval t1, t2;
1666 bool Cflag = false, qflag = false;
1667 int c, ret;
1668 int64_t offset, count;
1670 while ((c = getopt(argc, argv, "Cq")) != -1) {
1671 switch (c) {
1672 case 'C':
1673 Cflag = true;
1674 break;
1675 case 'q':
1676 qflag = true;
1677 break;
1678 default:
1679 return qemuio_command_usage(&discard_cmd);
1683 if (optind != argc - 2) {
1684 return qemuio_command_usage(&discard_cmd);
1687 offset = cvtnum(argv[optind]);
1688 if (offset < 0) {
1689 print_cvtnum_err(offset, argv[optind]);
1690 return 0;
1693 optind++;
1694 count = cvtnum(argv[optind]);
1695 if (count < 0) {
1696 print_cvtnum_err(count, argv[optind]);
1697 return 0;
1698 } else if (count >> BDRV_SECTOR_BITS > BDRV_REQUEST_MAX_SECTORS) {
1699 printf("length cannot exceed %"PRIu64", given %s\n",
1700 (uint64_t)BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS,
1701 argv[optind]);
1702 return 0;
1705 gettimeofday(&t1, NULL);
1706 ret = blk_pdiscard(blk, offset, count);
1707 gettimeofday(&t2, NULL);
1709 if (ret < 0) {
1710 printf("discard failed: %s\n", strerror(-ret));
1711 goto out;
1714 /* Finally, report back -- -C gives a parsable format */
1715 if (!qflag) {
1716 t2 = tsub(t2, t1);
1717 print_report("discard", &t2, offset, count, count, 1, Cflag);
1720 out:
1721 return 0;
1724 static int alloc_f(BlockBackend *blk, int argc, char **argv)
1726 BlockDriverState *bs = blk_bs(blk);
1727 int64_t offset, sector_num, nb_sectors, remaining;
1728 char s1[64];
1729 int num, ret;
1730 int64_t sum_alloc;
1732 offset = cvtnum(argv[1]);
1733 if (offset < 0) {
1734 print_cvtnum_err(offset, argv[1]);
1735 return 0;
1736 } else if (offset & 0x1ff) {
1737 printf("offset %" PRId64 " is not sector aligned\n",
1738 offset);
1739 return 0;
1742 if (argc == 3) {
1743 nb_sectors = cvtnum(argv[2]);
1744 if (nb_sectors < 0) {
1745 print_cvtnum_err(nb_sectors, argv[2]);
1746 return 0;
1747 } else if (nb_sectors > INT_MAX) {
1748 printf("length argument cannot exceed %d, given %s\n",
1749 INT_MAX, argv[2]);
1750 return 0;
1752 } else {
1753 nb_sectors = 1;
1756 remaining = nb_sectors;
1757 sum_alloc = 0;
1758 sector_num = offset >> 9;
1759 while (remaining) {
1760 ret = bdrv_is_allocated(bs, sector_num, remaining, &num);
1761 if (ret < 0) {
1762 printf("is_allocated failed: %s\n", strerror(-ret));
1763 return 0;
1765 sector_num += num;
1766 remaining -= num;
1767 if (ret) {
1768 sum_alloc += num;
1770 if (num == 0) {
1771 nb_sectors -= remaining;
1772 remaining = 0;
1776 cvtstr(offset, s1, sizeof(s1));
1778 printf("%"PRId64"/%"PRId64" sectors allocated at offset %s\n",
1779 sum_alloc, nb_sectors, s1);
1780 return 0;
1783 static const cmdinfo_t alloc_cmd = {
1784 .name = "alloc",
1785 .altname = "a",
1786 .argmin = 1,
1787 .argmax = 2,
1788 .cfunc = alloc_f,
1789 .args = "off [sectors]",
1790 .oneline = "checks if a sector is present in the file",
1794 static int map_is_allocated(BlockDriverState *bs, int64_t sector_num,
1795 int64_t nb_sectors, int64_t *pnum)
1797 int num, num_checked;
1798 int ret, firstret;
1800 num_checked = MIN(nb_sectors, INT_MAX);
1801 ret = bdrv_is_allocated(bs, sector_num, num_checked, &num);
1802 if (ret < 0) {
1803 return ret;
1806 firstret = ret;
1807 *pnum = num;
1809 while (nb_sectors > 0 && ret == firstret) {
1810 sector_num += num;
1811 nb_sectors -= num;
1813 num_checked = MIN(nb_sectors, INT_MAX);
1814 ret = bdrv_is_allocated(bs, sector_num, num_checked, &num);
1815 if (ret == firstret && num) {
1816 *pnum += num;
1817 } else {
1818 break;
1822 return firstret;
1825 static int map_f(BlockBackend *blk, int argc, char **argv)
1827 int64_t offset;
1828 int64_t nb_sectors, total_sectors;
1829 char s1[64];
1830 int64_t num;
1831 int ret;
1832 const char *retstr;
1834 offset = 0;
1835 total_sectors = blk_nb_sectors(blk);
1836 if (total_sectors < 0) {
1837 error_report("Failed to query image length: %s",
1838 strerror(-total_sectors));
1839 return 0;
1842 nb_sectors = total_sectors;
1844 do {
1845 ret = map_is_allocated(blk_bs(blk), offset, nb_sectors, &num);
1846 if (ret < 0) {
1847 error_report("Failed to get allocation status: %s", strerror(-ret));
1848 return 0;
1849 } else if (!num) {
1850 error_report("Unexpected end of image");
1851 return 0;
1854 retstr = ret ? " allocated" : "not allocated";
1855 cvtstr(offset << 9ULL, s1, sizeof(s1));
1856 printf("[% 24" PRId64 "] % 8" PRId64 "/% 8" PRId64 " sectors %s "
1857 "at offset %s (%d)\n",
1858 offset << 9ULL, num, nb_sectors, retstr, s1, ret);
1860 offset += num;
1861 nb_sectors -= num;
1862 } while (offset < total_sectors);
1864 return 0;
1867 static const cmdinfo_t map_cmd = {
1868 .name = "map",
1869 .argmin = 0,
1870 .argmax = 0,
1871 .cfunc = map_f,
1872 .args = "",
1873 .oneline = "prints the allocated areas of a file",
1876 static void reopen_help(void)
1878 printf(
1879 "\n"
1880 " Changes the open options of an already opened image\n"
1881 "\n"
1882 " Example:\n"
1883 " 'reopen -o lazy-refcounts=on' - activates lazy refcount writeback on a qcow2 image\n"
1884 "\n"
1885 " -r, -- Reopen the image read-only\n"
1886 " -c, -- Change the cache mode to the given value\n"
1887 " -o, -- Changes block driver options (cf. 'open' command)\n"
1888 "\n");
1891 static int reopen_f(BlockBackend *blk, int argc, char **argv);
1893 static QemuOptsList reopen_opts = {
1894 .name = "reopen",
1895 .merge_lists = true,
1896 .head = QTAILQ_HEAD_INITIALIZER(reopen_opts.head),
1897 .desc = {
1898 /* no elements => accept any params */
1899 { /* end of list */ }
1903 static const cmdinfo_t reopen_cmd = {
1904 .name = "reopen",
1905 .argmin = 0,
1906 .argmax = -1,
1907 .cfunc = reopen_f,
1908 .args = "[-r] [-c cache] [-o options]",
1909 .oneline = "reopens an image with new options",
1910 .help = reopen_help,
1913 static int reopen_f(BlockBackend *blk, int argc, char **argv)
1915 BlockDriverState *bs = blk_bs(blk);
1916 QemuOpts *qopts;
1917 QDict *opts;
1918 int c;
1919 int flags = bs->open_flags;
1920 bool writethrough = !blk_enable_write_cache(blk);
1922 BlockReopenQueue *brq;
1923 Error *local_err = NULL;
1925 while ((c = getopt(argc, argv, "c:o:r")) != -1) {
1926 switch (c) {
1927 case 'c':
1928 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) < 0) {
1929 error_report("Invalid cache option: %s", optarg);
1930 return 0;
1932 break;
1933 case 'o':
1934 if (!qemu_opts_parse_noisily(&reopen_opts, optarg, 0)) {
1935 qemu_opts_reset(&reopen_opts);
1936 return 0;
1938 break;
1939 case 'r':
1940 flags &= ~BDRV_O_RDWR;
1941 break;
1942 default:
1943 qemu_opts_reset(&reopen_opts);
1944 return qemuio_command_usage(&reopen_cmd);
1948 if (optind != argc) {
1949 qemu_opts_reset(&reopen_opts);
1950 return qemuio_command_usage(&reopen_cmd);
1953 if (writethrough != blk_enable_write_cache(blk) &&
1954 blk_get_attached_dev(blk))
1956 error_report("Cannot change cache.writeback: Device attached");
1957 qemu_opts_reset(&reopen_opts);
1958 return 0;
1961 qopts = qemu_opts_find(&reopen_opts, NULL);
1962 opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : NULL;
1963 qemu_opts_reset(&reopen_opts);
1965 brq = bdrv_reopen_queue(NULL, bs, opts, flags);
1966 bdrv_reopen_multiple(bdrv_get_aio_context(bs), brq, &local_err);
1967 if (local_err) {
1968 error_report_err(local_err);
1969 } else {
1970 blk_set_enable_write_cache(blk, !writethrough);
1973 return 0;
1976 static int break_f(BlockBackend *blk, int argc, char **argv)
1978 int ret;
1980 ret = bdrv_debug_breakpoint(blk_bs(blk), argv[1], argv[2]);
1981 if (ret < 0) {
1982 printf("Could not set breakpoint: %s\n", strerror(-ret));
1985 return 0;
1988 static int remove_break_f(BlockBackend *blk, int argc, char **argv)
1990 int ret;
1992 ret = bdrv_debug_remove_breakpoint(blk_bs(blk), argv[1]);
1993 if (ret < 0) {
1994 printf("Could not remove breakpoint %s: %s\n", argv[1], strerror(-ret));
1997 return 0;
2000 static const cmdinfo_t break_cmd = {
2001 .name = "break",
2002 .argmin = 2,
2003 .argmax = 2,
2004 .cfunc = break_f,
2005 .args = "event tag",
2006 .oneline = "sets a breakpoint on event and tags the stopped "
2007 "request as tag",
2010 static const cmdinfo_t remove_break_cmd = {
2011 .name = "remove_break",
2012 .argmin = 1,
2013 .argmax = 1,
2014 .cfunc = remove_break_f,
2015 .args = "tag",
2016 .oneline = "remove a breakpoint by tag",
2019 static int resume_f(BlockBackend *blk, int argc, char **argv)
2021 int ret;
2023 ret = bdrv_debug_resume(blk_bs(blk), argv[1]);
2024 if (ret < 0) {
2025 printf("Could not resume request: %s\n", strerror(-ret));
2028 return 0;
2031 static const cmdinfo_t resume_cmd = {
2032 .name = "resume",
2033 .argmin = 1,
2034 .argmax = 1,
2035 .cfunc = resume_f,
2036 .args = "tag",
2037 .oneline = "resumes the request tagged as tag",
2040 static int wait_break_f(BlockBackend *blk, int argc, char **argv)
2042 while (!bdrv_debug_is_suspended(blk_bs(blk), argv[1])) {
2043 aio_poll(blk_get_aio_context(blk), true);
2046 return 0;
2049 static const cmdinfo_t wait_break_cmd = {
2050 .name = "wait_break",
2051 .argmin = 1,
2052 .argmax = 1,
2053 .cfunc = wait_break_f,
2054 .args = "tag",
2055 .oneline = "waits for the suspension of a request",
2058 static int abort_f(BlockBackend *blk, int argc, char **argv)
2060 abort();
2063 static const cmdinfo_t abort_cmd = {
2064 .name = "abort",
2065 .cfunc = abort_f,
2066 .flags = CMD_NOFILE_OK,
2067 .oneline = "simulate a program crash using abort(3)",
2070 static void sigraise_help(void)
2072 printf(
2073 "\n"
2074 " raises the given signal\n"
2075 "\n"
2076 " Example:\n"
2077 " 'sigraise %i' - raises SIGTERM\n"
2078 "\n"
2079 " Invokes raise(signal), where \"signal\" is the mandatory integer argument\n"
2080 " given to sigraise.\n"
2081 "\n", SIGTERM);
2084 static int sigraise_f(BlockBackend *blk, int argc, char **argv);
2086 static const cmdinfo_t sigraise_cmd = {
2087 .name = "sigraise",
2088 .cfunc = sigraise_f,
2089 .argmin = 1,
2090 .argmax = 1,
2091 .flags = CMD_NOFILE_OK,
2092 .args = "signal",
2093 .oneline = "raises a signal",
2094 .help = sigraise_help,
2097 static int sigraise_f(BlockBackend *blk, int argc, char **argv)
2099 int64_t sig = cvtnum(argv[1]);
2100 if (sig < 0) {
2101 print_cvtnum_err(sig, argv[1]);
2102 return 0;
2103 } else if (sig > NSIG) {
2104 printf("signal argument '%s' is too large to be a valid signal\n",
2105 argv[1]);
2106 return 0;
2109 /* Using raise() to kill this process does not necessarily flush all open
2110 * streams. At least stdout and stderr (although the latter should be
2111 * non-buffered anyway) should be flushed, though. */
2112 fflush(stdout);
2113 fflush(stderr);
2115 raise(sig);
2116 return 0;
2119 static void sleep_cb(void *opaque)
2121 bool *expired = opaque;
2122 *expired = true;
2125 static int sleep_f(BlockBackend *blk, int argc, char **argv)
2127 char *endptr;
2128 long ms;
2129 struct QEMUTimer *timer;
2130 bool expired = false;
2132 ms = strtol(argv[1], &endptr, 0);
2133 if (ms < 0 || *endptr != '\0') {
2134 printf("%s is not a valid number\n", argv[1]);
2135 return 0;
2138 timer = timer_new_ns(QEMU_CLOCK_HOST, sleep_cb, &expired);
2139 timer_mod(timer, qemu_clock_get_ns(QEMU_CLOCK_HOST) + SCALE_MS * ms);
2141 while (!expired) {
2142 main_loop_wait(false);
2145 timer_free(timer);
2147 return 0;
2150 static const cmdinfo_t sleep_cmd = {
2151 .name = "sleep",
2152 .argmin = 1,
2153 .argmax = 1,
2154 .cfunc = sleep_f,
2155 .flags = CMD_NOFILE_OK,
2156 .oneline = "waits for the given value in milliseconds",
2159 static void help_oneline(const char *cmd, const cmdinfo_t *ct)
2161 if (cmd) {
2162 printf("%s ", cmd);
2163 } else {
2164 printf("%s ", ct->name);
2165 if (ct->altname) {
2166 printf("(or %s) ", ct->altname);
2170 if (ct->args) {
2171 printf("%s ", ct->args);
2173 printf("-- %s\n", ct->oneline);
2176 static void help_onecmd(const char *cmd, const cmdinfo_t *ct)
2178 help_oneline(cmd, ct);
2179 if (ct->help) {
2180 ct->help();
2184 static void help_all(void)
2186 const cmdinfo_t *ct;
2188 for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
2189 help_oneline(ct->name, ct);
2191 printf("\nUse 'help commandname' for extended help.\n");
2194 static int help_f(BlockBackend *blk, int argc, char **argv)
2196 const cmdinfo_t *ct;
2198 if (argc == 1) {
2199 help_all();
2200 return 0;
2203 ct = find_command(argv[1]);
2204 if (ct == NULL) {
2205 printf("command %s not found\n", argv[1]);
2206 return 0;
2209 help_onecmd(argv[1], ct);
2210 return 0;
2213 static const cmdinfo_t help_cmd = {
2214 .name = "help",
2215 .altname = "?",
2216 .cfunc = help_f,
2217 .argmin = 0,
2218 .argmax = 1,
2219 .flags = CMD_FLAG_GLOBAL,
2220 .args = "[command]",
2221 .oneline = "help for one or all commands",
2224 bool qemuio_command(BlockBackend *blk, const char *cmd)
2226 AioContext *ctx;
2227 char *input;
2228 const cmdinfo_t *ct;
2229 char **v;
2230 int c;
2231 bool done = false;
2233 input = g_strdup(cmd);
2234 v = breakline(input, &c);
2235 if (c) {
2236 ct = find_command(v[0]);
2237 if (ct) {
2238 ctx = blk ? blk_get_aio_context(blk) : qemu_get_aio_context();
2239 aio_context_acquire(ctx);
2240 done = command(blk, ct, c, v);
2241 aio_context_release(ctx);
2242 } else {
2243 fprintf(stderr, "command \"%s\" not found\n", v[0]);
2246 g_free(input);
2247 g_free(v);
2249 return done;
2252 static void __attribute((constructor)) init_qemuio_commands(void)
2254 /* initialize commands */
2255 qemuio_add_command(&help_cmd);
2256 qemuio_add_command(&read_cmd);
2257 qemuio_add_command(&readv_cmd);
2258 qemuio_add_command(&write_cmd);
2259 qemuio_add_command(&writev_cmd);
2260 qemuio_add_command(&aio_read_cmd);
2261 qemuio_add_command(&aio_write_cmd);
2262 qemuio_add_command(&aio_flush_cmd);
2263 qemuio_add_command(&flush_cmd);
2264 qemuio_add_command(&truncate_cmd);
2265 qemuio_add_command(&length_cmd);
2266 qemuio_add_command(&info_cmd);
2267 qemuio_add_command(&discard_cmd);
2268 qemuio_add_command(&alloc_cmd);
2269 qemuio_add_command(&map_cmd);
2270 qemuio_add_command(&reopen_cmd);
2271 qemuio_add_command(&break_cmd);
2272 qemuio_add_command(&remove_break_cmd);
2273 qemuio_add_command(&resume_cmd);
2274 qemuio_add_command(&wait_break_cmd);
2275 qemuio_add_command(&abort_cmd);
2276 qemuio_add_command(&sleep_cmd);
2277 qemuio_add_command(&sigraise_cmd);