]> git.proxmox.com Git - mirror_qemu.git/blob - qemu-io-cmds.c
util/cutils: Return qemu_strtosz*() error and value separately
[mirror_qemu.git] / qemu-io-cmds.c
1 /*
2 * Command line utility to exercise the QEMU I/O path.
3 *
4 * Copyright (C) 2009-2016 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 "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"
22
23 #define CMD_NOFILE_OK 0x01
24
25 bool qemuio_misalign;
26
27 static cmdinfo_t *cmdtab;
28 static int ncmds;
29
30 static int compare_cmdname(const void *a, const void *b)
31 {
32 return strcmp(((const cmdinfo_t *)a)->name,
33 ((const cmdinfo_t *)b)->name);
34 }
35
36 void qemuio_add_command(const cmdinfo_t *ci)
37 {
38 cmdtab = g_renew(cmdinfo_t, cmdtab, ++ncmds);
39 cmdtab[ncmds - 1] = *ci;
40 qsort(cmdtab, ncmds, sizeof(*cmdtab), compare_cmdname);
41 }
42
43 int qemuio_command_usage(const cmdinfo_t *ci)
44 {
45 printf("%s %s -- %s\n", ci->name, ci->args, ci->oneline);
46 return 0;
47 }
48
49 static int init_check_command(BlockBackend *blk, const cmdinfo_t *ct)
50 {
51 if (ct->flags & CMD_FLAG_GLOBAL) {
52 return 1;
53 }
54 if (!(ct->flags & CMD_NOFILE_OK) && !blk) {
55 fprintf(stderr, "no file open, try 'help open'\n");
56 return 0;
57 }
58 return 1;
59 }
60
61 static int command(BlockBackend *blk, const cmdinfo_t *ct, int argc,
62 char **argv)
63 {
64 char *cmd = argv[0];
65
66 if (!init_check_command(blk, ct)) {
67 return 0;
68 }
69
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);
83 }
84 return 0;
85 }
86 optind = 0;
87 return ct->cfunc(blk, argc, argv);
88 }
89
90 static const cmdinfo_t *find_command(const char *cmd)
91 {
92 cmdinfo_t *ct;
93
94 for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
95 if (strcmp(ct->name, cmd) == 0 ||
96 (ct->altname && strcmp(ct->altname, cmd) == 0))
97 {
98 return (const cmdinfo_t *)ct;
99 }
100 }
101 return NULL;
102 }
103
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)
108 {
109 cmdinfo_t *ct;
110 size_t input_len = strlen(input);
111
112 for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
113 if (strncmp(input, ct->name, input_len) == 0) {
114 fn(ct->name, opaque);
115 }
116 }
117 }
118
119 static char **breakline(char *input, int *count)
120 {
121 int c = 0;
122 char *p;
123 char **rval = g_new0(char *, 1);
124
125 while (rval && (p = qemu_strsep(&input, " ")) != NULL) {
126 if (!*p) {
127 continue;
128 }
129 c++;
130 rval = g_renew(char *, rval, (c + 1));
131 rval[c - 1] = p;
132 rval[c] = NULL;
133 }
134 *count = c;
135 return rval;
136 }
137
138 static int64_t cvtnum(const char *s)
139 {
140 int err;
141 int64_t value;
142
143 err = qemu_strtosz(s, NULL, &value);
144 if (err < 0) {
145 return err;
146 }
147 return value;
148 }
149
150 static void print_cvtnum_err(int64_t rc, const char *arg)
151 {
152 switch (rc) {
153 case -EINVAL:
154 printf("Parsing error: non-numeric argument,"
155 " or extraneous/unrecognized suffix -- %s\n", arg);
156 break;
157 case -ERANGE:
158 printf("Parsing error: argument too large -- %s\n", arg);
159 break;
160 default:
161 printf("Parsing error: %s\n", arg);
162 }
163 }
164
165 #define EXABYTES(x) ((long long)(x) << 60)
166 #define PETABYTES(x) ((long long)(x) << 50)
167 #define TERABYTES(x) ((long long)(x) << 40)
168 #define GIGABYTES(x) ((long long)(x) << 30)
169 #define MEGABYTES(x) ((long long)(x) << 20)
170 #define KILOBYTES(x) ((long long)(x) << 10)
171
172 #define TO_EXABYTES(x) ((x) / EXABYTES(1))
173 #define TO_PETABYTES(x) ((x) / PETABYTES(1))
174 #define TO_TERABYTES(x) ((x) / TERABYTES(1))
175 #define TO_GIGABYTES(x) ((x) / GIGABYTES(1))
176 #define TO_MEGABYTES(x) ((x) / MEGABYTES(1))
177 #define TO_KILOBYTES(x) ((x) / KILOBYTES(1))
178
179 static void cvtstr(double value, char *str, size_t size)
180 {
181 char *trim;
182 const char *suffix;
183
184 if (value >= EXABYTES(1)) {
185 suffix = " EiB";
186 snprintf(str, size - 4, "%.3f", TO_EXABYTES(value));
187 } else if (value >= PETABYTES(1)) {
188 suffix = " PiB";
189 snprintf(str, size - 4, "%.3f", TO_PETABYTES(value));
190 } else if (value >= TERABYTES(1)) {
191 suffix = " TiB";
192 snprintf(str, size - 4, "%.3f", TO_TERABYTES(value));
193 } else if (value >= GIGABYTES(1)) {
194 suffix = " GiB";
195 snprintf(str, size - 4, "%.3f", TO_GIGABYTES(value));
196 } else if (value >= MEGABYTES(1)) {
197 suffix = " MiB";
198 snprintf(str, size - 4, "%.3f", TO_MEGABYTES(value));
199 } else if (value >= KILOBYTES(1)) {
200 suffix = " KiB";
201 snprintf(str, size - 4, "%.3f", TO_KILOBYTES(value));
202 } else {
203 suffix = " bytes";
204 snprintf(str, size - 6, "%f", value);
205 }
206
207 trim = strstr(str, ".000");
208 if (trim) {
209 strcpy(trim, suffix);
210 } else {
211 strcat(str, suffix);
212 }
213 }
214
215
216
217 static struct timeval tsub(struct timeval t1, struct timeval t2)
218 {
219 t1.tv_usec -= t2.tv_usec;
220 if (t1.tv_usec < 0) {
221 t1.tv_usec += 1000000;
222 t1.tv_sec--;
223 }
224 t1.tv_sec -= t2.tv_sec;
225 return t1;
226 }
227
228 static double tdiv(double value, struct timeval tv)
229 {
230 return value / ((double)tv.tv_sec + ((double)tv.tv_usec / 1000000.0));
231 }
232
233 #define HOURS(sec) ((sec) / (60 * 60))
234 #define MINUTES(sec) (((sec) % (60 * 60)) / 60)
235 #define SECONDS(sec) ((sec) % 60)
236
237 enum {
238 DEFAULT_TIME = 0x0,
239 TERSE_FIXED_TIME = 0x1,
240 VERBOSE_FIXED_TIME = 0x2,
241 };
242
243 static void timestr(struct timeval *tv, char *ts, size_t size, int format)
244 {
245 double usec = (double)tv->tv_usec / 1000000.0;
246
247 if (format & TERSE_FIXED_TIME) {
248 if (!HOURS(tv->tv_sec)) {
249 snprintf(ts, size, "%u:%02u.%02u",
250 (unsigned int) MINUTES(tv->tv_sec),
251 (unsigned int) SECONDS(tv->tv_sec),
252 (unsigned int) (usec * 100));
253 return;
254 }
255 format |= VERBOSE_FIXED_TIME; /* fallback if hours needed */
256 }
257
258 if ((format & VERBOSE_FIXED_TIME) || tv->tv_sec) {
259 snprintf(ts, size, "%u:%02u:%02u.%02u",
260 (unsigned int) HOURS(tv->tv_sec),
261 (unsigned int) MINUTES(tv->tv_sec),
262 (unsigned int) SECONDS(tv->tv_sec),
263 (unsigned int) (usec * 100));
264 } else {
265 snprintf(ts, size, "0.%04u sec", (unsigned int) (usec * 10000));
266 }
267 }
268
269 /*
270 * Parse the pattern argument to various sub-commands.
271 *
272 * Because the pattern is used as an argument to memset it must evaluate
273 * to an unsigned integer that fits into a single byte.
274 */
275 static int parse_pattern(const char *arg)
276 {
277 char *endptr = NULL;
278 long pattern;
279
280 pattern = strtol(arg, &endptr, 0);
281 if (pattern < 0 || pattern > UCHAR_MAX || *endptr != '\0') {
282 printf("%s is not a valid pattern byte\n", arg);
283 return -1;
284 }
285
286 return pattern;
287 }
288
289 /*
290 * Memory allocation helpers.
291 *
292 * Make sure memory is aligned by default, or purposefully misaligned if
293 * that is specified on the command line.
294 */
295
296 #define MISALIGN_OFFSET 16
297 static void *qemu_io_alloc(BlockBackend *blk, size_t len, int pattern)
298 {
299 void *buf;
300
301 if (qemuio_misalign) {
302 len += MISALIGN_OFFSET;
303 }
304 buf = blk_blockalign(blk, len);
305 memset(buf, pattern, len);
306 if (qemuio_misalign) {
307 buf += MISALIGN_OFFSET;
308 }
309 return buf;
310 }
311
312 static void qemu_io_free(void *p)
313 {
314 if (qemuio_misalign) {
315 p -= MISALIGN_OFFSET;
316 }
317 qemu_vfree(p);
318 }
319
320 static void dump_buffer(const void *buffer, int64_t offset, int64_t len)
321 {
322 uint64_t i;
323 int j;
324 const uint8_t *p;
325
326 for (i = 0, p = buffer; i < len; i += 16) {
327 const uint8_t *s = p;
328
329 printf("%08" PRIx64 ": ", offset + i);
330 for (j = 0; j < 16 && i + j < len; j++, p++) {
331 printf("%02x ", *p);
332 }
333 printf(" ");
334 for (j = 0; j < 16 && i + j < len; j++, s++) {
335 if (isalnum(*s)) {
336 printf("%c", *s);
337 } else {
338 printf(".");
339 }
340 }
341 printf("\n");
342 }
343 }
344
345 static void print_report(const char *op, struct timeval *t, int64_t offset,
346 int64_t count, int64_t total, int cnt, bool Cflag)
347 {
348 char s1[64], s2[64], ts[64];
349
350 timestr(t, ts, sizeof(ts), Cflag ? VERBOSE_FIXED_TIME : 0);
351 if (!Cflag) {
352 cvtstr((double)total, s1, sizeof(s1));
353 cvtstr(tdiv((double)total, *t), s2, sizeof(s2));
354 printf("%s %"PRId64"/%"PRId64" bytes at offset %" PRId64 "\n",
355 op, total, count, offset);
356 printf("%s, %d ops; %s (%s/sec and %.4f ops/sec)\n",
357 s1, cnt, ts, s2, tdiv((double)cnt, *t));
358 } else {/* bytes,ops,time,bytes/sec,ops/sec */
359 printf("%"PRId64",%d,%s,%.3f,%.3f\n",
360 total, cnt, ts,
361 tdiv((double)total, *t),
362 tdiv((double)cnt, *t));
363 }
364 }
365
366 /*
367 * Parse multiple length statements for vectored I/O, and construct an I/O
368 * vector matching it.
369 */
370 static void *
371 create_iovec(BlockBackend *blk, QEMUIOVector *qiov, char **argv, int nr_iov,
372 int pattern)
373 {
374 size_t *sizes = g_new0(size_t, nr_iov);
375 size_t count = 0;
376 void *buf = NULL;
377 void *p;
378 int i;
379
380 for (i = 0; i < nr_iov; i++) {
381 char *arg = argv[i];
382 int64_t len;
383
384 len = cvtnum(arg);
385 if (len < 0) {
386 print_cvtnum_err(len, arg);
387 goto fail;
388 }
389
390 if (len > BDRV_REQUEST_MAX_BYTES) {
391 printf("Argument '%s' exceeds maximum size %" PRIu64 "\n", arg,
392 (uint64_t)BDRV_REQUEST_MAX_BYTES);
393 goto fail;
394 }
395
396 if (count > BDRV_REQUEST_MAX_BYTES - len) {
397 printf("The total number of bytes exceed the maximum size %" PRIu64
398 "\n", (uint64_t)BDRV_REQUEST_MAX_BYTES);
399 goto fail;
400 }
401
402 sizes[i] = len;
403 count += len;
404 }
405
406 qemu_iovec_init(qiov, nr_iov);
407
408 buf = p = qemu_io_alloc(blk, count, pattern);
409
410 for (i = 0; i < nr_iov; i++) {
411 qemu_iovec_add(qiov, p, sizes[i]);
412 p += sizes[i];
413 }
414
415 fail:
416 g_free(sizes);
417 return buf;
418 }
419
420 static int do_pread(BlockBackend *blk, char *buf, int64_t offset,
421 int64_t count, int64_t *total)
422 {
423 if (count > INT_MAX) {
424 return -ERANGE;
425 }
426
427 *total = blk_pread(blk, offset, (uint8_t *)buf, count);
428 if (*total < 0) {
429 return *total;
430 }
431 return 1;
432 }
433
434 static int do_pwrite(BlockBackend *blk, char *buf, int64_t offset,
435 int64_t count, int flags, int64_t *total)
436 {
437 if (count > INT_MAX) {
438 return -ERANGE;
439 }
440
441 *total = blk_pwrite(blk, offset, (uint8_t *)buf, count, flags);
442 if (*total < 0) {
443 return *total;
444 }
445 return 1;
446 }
447
448 typedef struct {
449 BlockBackend *blk;
450 int64_t offset;
451 int64_t count;
452 int64_t *total;
453 int flags;
454 int ret;
455 bool done;
456 } CoWriteZeroes;
457
458 static void coroutine_fn co_pwrite_zeroes_entry(void *opaque)
459 {
460 CoWriteZeroes *data = opaque;
461
462 data->ret = blk_co_pwrite_zeroes(data->blk, data->offset, data->count,
463 data->flags);
464 data->done = true;
465 if (data->ret < 0) {
466 *data->total = data->ret;
467 return;
468 }
469
470 *data->total = data->count;
471 }
472
473 static int do_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
474 int64_t count, int flags, int64_t *total)
475 {
476 Coroutine *co;
477 CoWriteZeroes data = {
478 .blk = blk,
479 .offset = offset,
480 .count = count,
481 .total = total,
482 .flags = flags,
483 .done = false,
484 };
485
486 if (count > INT_MAX) {
487 return -ERANGE;
488 }
489
490 co = qemu_coroutine_create(co_pwrite_zeroes_entry, &data);
491 qemu_coroutine_enter(co);
492 while (!data.done) {
493 aio_poll(blk_get_aio_context(blk), true);
494 }
495 if (data.ret < 0) {
496 return data.ret;
497 } else {
498 return 1;
499 }
500 }
501
502 static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,
503 int64_t count, int64_t *total)
504 {
505 int ret;
506
507 if (count >> 9 > BDRV_REQUEST_MAX_SECTORS) {
508 return -ERANGE;
509 }
510
511 ret = blk_pwrite_compressed(blk, offset, buf, count);
512 if (ret < 0) {
513 return ret;
514 }
515 *total = count;
516 return 1;
517 }
518
519 static int do_load_vmstate(BlockBackend *blk, char *buf, int64_t offset,
520 int64_t count, int64_t *total)
521 {
522 if (count > INT_MAX) {
523 return -ERANGE;
524 }
525
526 *total = blk_load_vmstate(blk, (uint8_t *)buf, offset, count);
527 if (*total < 0) {
528 return *total;
529 }
530 return 1;
531 }
532
533 static int do_save_vmstate(BlockBackend *blk, char *buf, int64_t offset,
534 int64_t count, int64_t *total)
535 {
536 if (count > INT_MAX) {
537 return -ERANGE;
538 }
539
540 *total = blk_save_vmstate(blk, (uint8_t *)buf, offset, count);
541 if (*total < 0) {
542 return *total;
543 }
544 return 1;
545 }
546
547 #define NOT_DONE 0x7fffffff
548 static void aio_rw_done(void *opaque, int ret)
549 {
550 *(int *)opaque = ret;
551 }
552
553 static int do_aio_readv(BlockBackend *blk, QEMUIOVector *qiov,
554 int64_t offset, int *total)
555 {
556 int async_ret = NOT_DONE;
557
558 blk_aio_preadv(blk, offset, qiov, 0, aio_rw_done, &async_ret);
559 while (async_ret == NOT_DONE) {
560 main_loop_wait(false);
561 }
562
563 *total = qiov->size;
564 return async_ret < 0 ? async_ret : 1;
565 }
566
567 static int do_aio_writev(BlockBackend *blk, QEMUIOVector *qiov,
568 int64_t offset, int flags, int *total)
569 {
570 int async_ret = NOT_DONE;
571
572 blk_aio_pwritev(blk, offset, qiov, flags, aio_rw_done, &async_ret);
573 while (async_ret == NOT_DONE) {
574 main_loop_wait(false);
575 }
576
577 *total = qiov->size;
578 return async_ret < 0 ? async_ret : 1;
579 }
580
581 static void read_help(void)
582 {
583 printf(
584 "\n"
585 " reads a range of bytes from the given offset\n"
586 "\n"
587 " Example:\n"
588 " 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n"
589 "\n"
590 " Reads a segment of the currently open file, optionally dumping it to the\n"
591 " standard output stream (with -v option) for subsequent inspection.\n"
592 " -b, -- read from the VM state rather than the virtual disk\n"
593 " -C, -- report statistics in a machine parsable format\n"
594 " -l, -- length for pattern verification (only with -P)\n"
595 " -p, -- ignored for backwards compatibility\n"
596 " -P, -- use a pattern to verify read data\n"
597 " -q, -- quiet mode, do not show I/O statistics\n"
598 " -s, -- start offset for pattern verification (only with -P)\n"
599 " -v, -- dump buffer to standard output\n"
600 "\n");
601 }
602
603 static int read_f(BlockBackend *blk, int argc, char **argv);
604
605 static const cmdinfo_t read_cmd = {
606 .name = "read",
607 .altname = "r",
608 .cfunc = read_f,
609 .argmin = 2,
610 .argmax = -1,
611 .args = "[-abCqv] [-P pattern [-s off] [-l len]] off len",
612 .oneline = "reads a number of bytes at a specified offset",
613 .help = read_help,
614 };
615
616 static int read_f(BlockBackend *blk, int argc, char **argv)
617 {
618 struct timeval t1, t2;
619 bool Cflag = false, qflag = false, vflag = false;
620 bool Pflag = false, sflag = false, lflag = false, bflag = false;
621 int c, cnt;
622 char *buf;
623 int64_t offset;
624 int64_t count;
625 /* Some compilers get confused and warn if this is not initialized. */
626 int64_t total = 0;
627 int pattern = 0;
628 int64_t pattern_offset = 0, pattern_count = 0;
629
630 while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != -1) {
631 switch (c) {
632 case 'b':
633 bflag = true;
634 break;
635 case 'C':
636 Cflag = true;
637 break;
638 case 'l':
639 lflag = true;
640 pattern_count = cvtnum(optarg);
641 if (pattern_count < 0) {
642 print_cvtnum_err(pattern_count, optarg);
643 return 0;
644 }
645 break;
646 case 'p':
647 /* Ignored for backwards compatibility */
648 break;
649 case 'P':
650 Pflag = true;
651 pattern = parse_pattern(optarg);
652 if (pattern < 0) {
653 return 0;
654 }
655 break;
656 case 'q':
657 qflag = true;
658 break;
659 case 's':
660 sflag = true;
661 pattern_offset = cvtnum(optarg);
662 if (pattern_offset < 0) {
663 print_cvtnum_err(pattern_offset, optarg);
664 return 0;
665 }
666 break;
667 case 'v':
668 vflag = true;
669 break;
670 default:
671 return qemuio_command_usage(&read_cmd);
672 }
673 }
674
675 if (optind != argc - 2) {
676 return qemuio_command_usage(&read_cmd);
677 }
678
679 offset = cvtnum(argv[optind]);
680 if (offset < 0) {
681 print_cvtnum_err(offset, argv[optind]);
682 return 0;
683 }
684
685 optind++;
686 count = cvtnum(argv[optind]);
687 if (count < 0) {
688 print_cvtnum_err(count, argv[optind]);
689 return 0;
690 } else if (count > BDRV_REQUEST_MAX_BYTES) {
691 printf("length cannot exceed %" PRIu64 ", given %s\n",
692 (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
693 return 0;
694 }
695
696 if (!Pflag && (lflag || sflag)) {
697 return qemuio_command_usage(&read_cmd);
698 }
699
700 if (!lflag) {
701 pattern_count = count - pattern_offset;
702 }
703
704 if ((pattern_count < 0) || (pattern_count + pattern_offset > count)) {
705 printf("pattern verification range exceeds end of read data\n");
706 return 0;
707 }
708
709 if (bflag) {
710 if (offset & 0x1ff) {
711 printf("offset %" PRId64 " is not sector aligned\n",
712 offset);
713 return 0;
714 }
715 if (count & 0x1ff) {
716 printf("count %"PRId64" is not sector aligned\n",
717 count);
718 return 0;
719 }
720 }
721
722 buf = qemu_io_alloc(blk, count, 0xab);
723
724 gettimeofday(&t1, NULL);
725 if (bflag) {
726 cnt = do_load_vmstate(blk, buf, offset, count, &total);
727 } else {
728 cnt = do_pread(blk, buf, offset, count, &total);
729 }
730 gettimeofday(&t2, NULL);
731
732 if (cnt < 0) {
733 printf("read failed: %s\n", strerror(-cnt));
734 goto out;
735 }
736
737 if (Pflag) {
738 void *cmp_buf = g_malloc(pattern_count);
739 memset(cmp_buf, pattern, pattern_count);
740 if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {
741 printf("Pattern verification failed at offset %"
742 PRId64 ", %"PRId64" bytes\n",
743 offset + pattern_offset, pattern_count);
744 }
745 g_free(cmp_buf);
746 }
747
748 if (qflag) {
749 goto out;
750 }
751
752 if (vflag) {
753 dump_buffer(buf, offset, count);
754 }
755
756 /* Finally, report back -- -C gives a parsable format */
757 t2 = tsub(t2, t1);
758 print_report("read", &t2, offset, count, total, cnt, Cflag);
759
760 out:
761 qemu_io_free(buf);
762
763 return 0;
764 }
765
766 static void readv_help(void)
767 {
768 printf(
769 "\n"
770 " reads a range of bytes from the given offset into multiple buffers\n"
771 "\n"
772 " Example:\n"
773 " 'readv -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
774 "\n"
775 " Reads a segment of the currently open file, optionally dumping it to the\n"
776 " standard output stream (with -v option) for subsequent inspection.\n"
777 " Uses multiple iovec buffers if more than one byte range is specified.\n"
778 " -C, -- report statistics in a machine parsable format\n"
779 " -P, -- use a pattern to verify read data\n"
780 " -v, -- dump buffer to standard output\n"
781 " -q, -- quiet mode, do not show I/O statistics\n"
782 "\n");
783 }
784
785 static int readv_f(BlockBackend *blk, int argc, char **argv);
786
787 static const cmdinfo_t readv_cmd = {
788 .name = "readv",
789 .cfunc = readv_f,
790 .argmin = 2,
791 .argmax = -1,
792 .args = "[-Cqv] [-P pattern] off len [len..]",
793 .oneline = "reads a number of bytes at a specified offset",
794 .help = readv_help,
795 };
796
797 static int readv_f(BlockBackend *blk, int argc, char **argv)
798 {
799 struct timeval t1, t2;
800 bool Cflag = false, qflag = false, vflag = false;
801 int c, cnt;
802 char *buf;
803 int64_t offset;
804 /* Some compilers get confused and warn if this is not initialized. */
805 int total = 0;
806 int nr_iov;
807 QEMUIOVector qiov;
808 int pattern = 0;
809 bool Pflag = false;
810
811 while ((c = getopt(argc, argv, "CP:qv")) != -1) {
812 switch (c) {
813 case 'C':
814 Cflag = true;
815 break;
816 case 'P':
817 Pflag = true;
818 pattern = parse_pattern(optarg);
819 if (pattern < 0) {
820 return 0;
821 }
822 break;
823 case 'q':
824 qflag = true;
825 break;
826 case 'v':
827 vflag = true;
828 break;
829 default:
830 return qemuio_command_usage(&readv_cmd);
831 }
832 }
833
834 if (optind > argc - 2) {
835 return qemuio_command_usage(&readv_cmd);
836 }
837
838
839 offset = cvtnum(argv[optind]);
840 if (offset < 0) {
841 print_cvtnum_err(offset, argv[optind]);
842 return 0;
843 }
844 optind++;
845
846 nr_iov = argc - optind;
847 buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, 0xab);
848 if (buf == NULL) {
849 return 0;
850 }
851
852 gettimeofday(&t1, NULL);
853 cnt = do_aio_readv(blk, &qiov, offset, &total);
854 gettimeofday(&t2, NULL);
855
856 if (cnt < 0) {
857 printf("readv failed: %s\n", strerror(-cnt));
858 goto out;
859 }
860
861 if (Pflag) {
862 void *cmp_buf = g_malloc(qiov.size);
863 memset(cmp_buf, pattern, qiov.size);
864 if (memcmp(buf, cmp_buf, qiov.size)) {
865 printf("Pattern verification failed at offset %"
866 PRId64 ", %zd bytes\n", offset, qiov.size);
867 }
868 g_free(cmp_buf);
869 }
870
871 if (qflag) {
872 goto out;
873 }
874
875 if (vflag) {
876 dump_buffer(buf, offset, qiov.size);
877 }
878
879 /* Finally, report back -- -C gives a parsable format */
880 t2 = tsub(t2, t1);
881 print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
882
883 out:
884 qemu_iovec_destroy(&qiov);
885 qemu_io_free(buf);
886 return 0;
887 }
888
889 static void write_help(void)
890 {
891 printf(
892 "\n"
893 " writes a range of bytes from the given offset\n"
894 "\n"
895 " Example:\n"
896 " 'write 512 1k' - writes 1 kilobyte at 512 bytes into the open file\n"
897 "\n"
898 " Writes into a segment of the currently open file, using a buffer\n"
899 " filled with a set pattern (0xcdcdcdcd).\n"
900 " -b, -- write to the VM state rather than the virtual disk\n"
901 " -c, -- write compressed data with blk_write_compressed\n"
902 " -f, -- use Force Unit Access semantics\n"
903 " -p, -- ignored for backwards compatibility\n"
904 " -P, -- use different pattern to fill file\n"
905 " -C, -- report statistics in a machine parsable format\n"
906 " -q, -- quiet mode, do not show I/O statistics\n"
907 " -u, -- with -z, allow unmapping\n"
908 " -z, -- write zeroes using blk_co_pwrite_zeroes\n"
909 "\n");
910 }
911
912 static int write_f(BlockBackend *blk, int argc, char **argv);
913
914 static const cmdinfo_t write_cmd = {
915 .name = "write",
916 .altname = "w",
917 .cfunc = write_f,
918 .argmin = 2,
919 .argmax = -1,
920 .args = "[-bcCfquz] [-P pattern] off len",
921 .oneline = "writes a number of bytes at a specified offset",
922 .help = write_help,
923 };
924
925 static int write_f(BlockBackend *blk, int argc, char **argv)
926 {
927 struct timeval t1, t2;
928 bool Cflag = false, qflag = false, bflag = false;
929 bool Pflag = false, zflag = false, cflag = false;
930 int flags = 0;
931 int c, cnt;
932 char *buf = NULL;
933 int64_t offset;
934 int64_t count;
935 /* Some compilers get confused and warn if this is not initialized. */
936 int64_t total = 0;
937 int pattern = 0xcd;
938
939 while ((c = getopt(argc, argv, "bcCfpP:quz")) != -1) {
940 switch (c) {
941 case 'b':
942 bflag = true;
943 break;
944 case 'c':
945 cflag = true;
946 break;
947 case 'C':
948 Cflag = true;
949 break;
950 case 'f':
951 flags |= BDRV_REQ_FUA;
952 break;
953 case 'p':
954 /* Ignored for backwards compatibility */
955 break;
956 case 'P':
957 Pflag = true;
958 pattern = parse_pattern(optarg);
959 if (pattern < 0) {
960 return 0;
961 }
962 break;
963 case 'q':
964 qflag = true;
965 break;
966 case 'u':
967 flags |= BDRV_REQ_MAY_UNMAP;
968 break;
969 case 'z':
970 zflag = true;
971 break;
972 default:
973 return qemuio_command_usage(&write_cmd);
974 }
975 }
976
977 if (optind != argc - 2) {
978 return qemuio_command_usage(&write_cmd);
979 }
980
981 if (bflag && zflag) {
982 printf("-b and -z cannot be specified at the same time\n");
983 return 0;
984 }
985
986 if ((flags & BDRV_REQ_FUA) && (bflag || cflag)) {
987 printf("-f and -b or -c cannot be specified at the same time\n");
988 return 0;
989 }
990
991 if ((flags & BDRV_REQ_MAY_UNMAP) && !zflag) {
992 printf("-u requires -z to be specified\n");
993 return 0;
994 }
995
996 if (zflag && Pflag) {
997 printf("-z and -P cannot be specified at the same time\n");
998 return 0;
999 }
1000
1001 offset = cvtnum(argv[optind]);
1002 if (offset < 0) {
1003 print_cvtnum_err(offset, argv[optind]);
1004 return 0;
1005 }
1006
1007 optind++;
1008 count = cvtnum(argv[optind]);
1009 if (count < 0) {
1010 print_cvtnum_err(count, argv[optind]);
1011 return 0;
1012 } else if (count > BDRV_REQUEST_MAX_BYTES) {
1013 printf("length cannot exceed %" PRIu64 ", given %s\n",
1014 (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
1015 return 0;
1016 }
1017
1018 if (bflag || cflag) {
1019 if (offset & 0x1ff) {
1020 printf("offset %" PRId64 " is not sector aligned\n",
1021 offset);
1022 return 0;
1023 }
1024
1025 if (count & 0x1ff) {
1026 printf("count %"PRId64" is not sector aligned\n",
1027 count);
1028 return 0;
1029 }
1030 }
1031
1032 if (!zflag) {
1033 buf = qemu_io_alloc(blk, count, pattern);
1034 }
1035
1036 gettimeofday(&t1, NULL);
1037 if (bflag) {
1038 cnt = do_save_vmstate(blk, buf, offset, count, &total);
1039 } else if (zflag) {
1040 cnt = do_co_pwrite_zeroes(blk, offset, count, flags, &total);
1041 } else if (cflag) {
1042 cnt = do_write_compressed(blk, buf, offset, count, &total);
1043 } else {
1044 cnt = do_pwrite(blk, buf, offset, count, flags, &total);
1045 }
1046 gettimeofday(&t2, NULL);
1047
1048 if (cnt < 0) {
1049 printf("write failed: %s\n", strerror(-cnt));
1050 goto out;
1051 }
1052
1053 if (qflag) {
1054 goto out;
1055 }
1056
1057 /* Finally, report back -- -C gives a parsable format */
1058 t2 = tsub(t2, t1);
1059 print_report("wrote", &t2, offset, count, total, cnt, Cflag);
1060
1061 out:
1062 if (!zflag) {
1063 qemu_io_free(buf);
1064 }
1065
1066 return 0;
1067 }
1068
1069 static void
1070 writev_help(void)
1071 {
1072 printf(
1073 "\n"
1074 " writes a range of bytes from the given offset source from multiple buffers\n"
1075 "\n"
1076 " Example:\n"
1077 " 'writev 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
1078 "\n"
1079 " Writes into a segment of the currently open file, using a buffer\n"
1080 " filled with a set pattern (0xcdcdcdcd).\n"
1081 " -P, -- use different pattern to fill file\n"
1082 " -C, -- report statistics in a machine parsable format\n"
1083 " -f, -- use Force Unit Access semantics\n"
1084 " -q, -- quiet mode, do not show I/O statistics\n"
1085 "\n");
1086 }
1087
1088 static int writev_f(BlockBackend *blk, int argc, char **argv);
1089
1090 static const cmdinfo_t writev_cmd = {
1091 .name = "writev",
1092 .cfunc = writev_f,
1093 .argmin = 2,
1094 .argmax = -1,
1095 .args = "[-Cfq] [-P pattern] off len [len..]",
1096 .oneline = "writes a number of bytes at a specified offset",
1097 .help = writev_help,
1098 };
1099
1100 static int writev_f(BlockBackend *blk, int argc, char **argv)
1101 {
1102 struct timeval t1, t2;
1103 bool Cflag = false, qflag = false;
1104 int flags = 0;
1105 int c, cnt;
1106 char *buf;
1107 int64_t offset;
1108 /* Some compilers get confused and warn if this is not initialized. */
1109 int total = 0;
1110 int nr_iov;
1111 int pattern = 0xcd;
1112 QEMUIOVector qiov;
1113
1114 while ((c = getopt(argc, argv, "CfqP:")) != -1) {
1115 switch (c) {
1116 case 'C':
1117 Cflag = true;
1118 break;
1119 case 'f':
1120 flags |= BDRV_REQ_FUA;
1121 break;
1122 case 'q':
1123 qflag = true;
1124 break;
1125 case 'P':
1126 pattern = parse_pattern(optarg);
1127 if (pattern < 0) {
1128 return 0;
1129 }
1130 break;
1131 default:
1132 return qemuio_command_usage(&writev_cmd);
1133 }
1134 }
1135
1136 if (optind > argc - 2) {
1137 return qemuio_command_usage(&writev_cmd);
1138 }
1139
1140 offset = cvtnum(argv[optind]);
1141 if (offset < 0) {
1142 print_cvtnum_err(offset, argv[optind]);
1143 return 0;
1144 }
1145 optind++;
1146
1147 nr_iov = argc - optind;
1148 buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern);
1149 if (buf == NULL) {
1150 return 0;
1151 }
1152
1153 gettimeofday(&t1, NULL);
1154 cnt = do_aio_writev(blk, &qiov, offset, flags, &total);
1155 gettimeofday(&t2, NULL);
1156
1157 if (cnt < 0) {
1158 printf("writev failed: %s\n", strerror(-cnt));
1159 goto out;
1160 }
1161
1162 if (qflag) {
1163 goto out;
1164 }
1165
1166 /* Finally, report back -- -C gives a parsable format */
1167 t2 = tsub(t2, t1);
1168 print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);
1169 out:
1170 qemu_iovec_destroy(&qiov);
1171 qemu_io_free(buf);
1172 return 0;
1173 }
1174
1175 struct aio_ctx {
1176 BlockBackend *blk;
1177 QEMUIOVector qiov;
1178 int64_t offset;
1179 char *buf;
1180 bool qflag;
1181 bool vflag;
1182 bool Cflag;
1183 bool Pflag;
1184 bool zflag;
1185 BlockAcctCookie acct;
1186 int pattern;
1187 struct timeval t1;
1188 };
1189
1190 static void aio_write_done(void *opaque, int ret)
1191 {
1192 struct aio_ctx *ctx = opaque;
1193 struct timeval t2;
1194
1195 gettimeofday(&t2, NULL);
1196
1197
1198 if (ret < 0) {
1199 printf("aio_write failed: %s\n", strerror(-ret));
1200 block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
1201 goto out;
1202 }
1203
1204 block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
1205
1206 if (ctx->qflag) {
1207 goto out;
1208 }
1209
1210 /* Finally, report back -- -C gives a parsable format */
1211 t2 = tsub(t2, ctx->t1);
1212 print_report("wrote", &t2, ctx->offset, ctx->qiov.size,
1213 ctx->qiov.size, 1, ctx->Cflag);
1214 out:
1215 if (!ctx->zflag) {
1216 qemu_io_free(ctx->buf);
1217 qemu_iovec_destroy(&ctx->qiov);
1218 }
1219 g_free(ctx);
1220 }
1221
1222 static void aio_read_done(void *opaque, int ret)
1223 {
1224 struct aio_ctx *ctx = opaque;
1225 struct timeval t2;
1226
1227 gettimeofday(&t2, NULL);
1228
1229 if (ret < 0) {
1230 printf("readv failed: %s\n", strerror(-ret));
1231 block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
1232 goto out;
1233 }
1234
1235 if (ctx->Pflag) {
1236 void *cmp_buf = g_malloc(ctx->qiov.size);
1237
1238 memset(cmp_buf, ctx->pattern, ctx->qiov.size);
1239 if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {
1240 printf("Pattern verification failed at offset %"
1241 PRId64 ", %zd bytes\n", ctx->offset, ctx->qiov.size);
1242 }
1243 g_free(cmp_buf);
1244 }
1245
1246 block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
1247
1248 if (ctx->qflag) {
1249 goto out;
1250 }
1251
1252 if (ctx->vflag) {
1253 dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);
1254 }
1255
1256 /* Finally, report back -- -C gives a parsable format */
1257 t2 = tsub(t2, ctx->t1);
1258 print_report("read", &t2, ctx->offset, ctx->qiov.size,
1259 ctx->qiov.size, 1, ctx->Cflag);
1260 out:
1261 qemu_io_free(ctx->buf);
1262 qemu_iovec_destroy(&ctx->qiov);
1263 g_free(ctx);
1264 }
1265
1266 static void aio_read_help(void)
1267 {
1268 printf(
1269 "\n"
1270 " asynchronously reads a range of bytes from the given offset\n"
1271 "\n"
1272 " Example:\n"
1273 " 'aio_read -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
1274 "\n"
1275 " Reads a segment of the currently open file, optionally dumping it to the\n"
1276 " standard output stream (with -v option) for subsequent inspection.\n"
1277 " The read is performed asynchronously and the aio_flush command must be\n"
1278 " used to ensure all outstanding aio requests have been completed.\n"
1279 " -C, -- report statistics in a machine parsable format\n"
1280 " -P, -- use a pattern to verify read data\n"
1281 " -i, -- treat request as invalid, for exercising stats\n"
1282 " -v, -- dump buffer to standard output\n"
1283 " -q, -- quiet mode, do not show I/O statistics\n"
1284 "\n");
1285 }
1286
1287 static int aio_read_f(BlockBackend *blk, int argc, char **argv);
1288
1289 static const cmdinfo_t aio_read_cmd = {
1290 .name = "aio_read",
1291 .cfunc = aio_read_f,
1292 .argmin = 2,
1293 .argmax = -1,
1294 .args = "[-Ciqv] [-P pattern] off len [len..]",
1295 .oneline = "asynchronously reads a number of bytes",
1296 .help = aio_read_help,
1297 };
1298
1299 static int aio_read_f(BlockBackend *blk, int argc, char **argv)
1300 {
1301 int nr_iov, c;
1302 struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
1303
1304 ctx->blk = blk;
1305 while ((c = getopt(argc, argv, "CP:iqv")) != -1) {
1306 switch (c) {
1307 case 'C':
1308 ctx->Cflag = true;
1309 break;
1310 case 'P':
1311 ctx->Pflag = true;
1312 ctx->pattern = parse_pattern(optarg);
1313 if (ctx->pattern < 0) {
1314 g_free(ctx);
1315 return 0;
1316 }
1317 break;
1318 case 'i':
1319 printf("injecting invalid read request\n");
1320 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
1321 g_free(ctx);
1322 return 0;
1323 case 'q':
1324 ctx->qflag = true;
1325 break;
1326 case 'v':
1327 ctx->vflag = true;
1328 break;
1329 default:
1330 g_free(ctx);
1331 return qemuio_command_usage(&aio_read_cmd);
1332 }
1333 }
1334
1335 if (optind > argc - 2) {
1336 g_free(ctx);
1337 return qemuio_command_usage(&aio_read_cmd);
1338 }
1339
1340 ctx->offset = cvtnum(argv[optind]);
1341 if (ctx->offset < 0) {
1342 print_cvtnum_err(ctx->offset, argv[optind]);
1343 g_free(ctx);
1344 return 0;
1345 }
1346 optind++;
1347
1348 nr_iov = argc - optind;
1349 ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, 0xab);
1350 if (ctx->buf == NULL) {
1351 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
1352 g_free(ctx);
1353 return 0;
1354 }
1355
1356 gettimeofday(&ctx->t1, NULL);
1357 block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
1358 BLOCK_ACCT_READ);
1359 blk_aio_preadv(blk, ctx->offset, &ctx->qiov, 0, aio_read_done, ctx);
1360 return 0;
1361 }
1362
1363 static void aio_write_help(void)
1364 {
1365 printf(
1366 "\n"
1367 " asynchronously writes a range of bytes from the given offset source\n"
1368 " from multiple buffers\n"
1369 "\n"
1370 " Example:\n"
1371 " 'aio_write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
1372 "\n"
1373 " Writes into a segment of the currently open file, using a buffer\n"
1374 " filled with a set pattern (0xcdcdcdcd).\n"
1375 " The write is performed asynchronously and the aio_flush command must be\n"
1376 " used to ensure all outstanding aio requests have been completed.\n"
1377 " -P, -- use different pattern to fill file\n"
1378 " -C, -- report statistics in a machine parsable format\n"
1379 " -f, -- use Force Unit Access semantics\n"
1380 " -i, -- treat request as invalid, for exercising stats\n"
1381 " -q, -- quiet mode, do not show I/O statistics\n"
1382 " -u, -- with -z, allow unmapping\n"
1383 " -z, -- write zeroes using blk_aio_pwrite_zeroes\n"
1384 "\n");
1385 }
1386
1387 static int aio_write_f(BlockBackend *blk, int argc, char **argv);
1388
1389 static const cmdinfo_t aio_write_cmd = {
1390 .name = "aio_write",
1391 .cfunc = aio_write_f,
1392 .argmin = 2,
1393 .argmax = -1,
1394 .args = "[-Cfiquz] [-P pattern] off len [len..]",
1395 .oneline = "asynchronously writes a number of bytes",
1396 .help = aio_write_help,
1397 };
1398
1399 static int aio_write_f(BlockBackend *blk, int argc, char **argv)
1400 {
1401 int nr_iov, c;
1402 int pattern = 0xcd;
1403 struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
1404 int flags = 0;
1405
1406 ctx->blk = blk;
1407 while ((c = getopt(argc, argv, "CfiqP:uz")) != -1) {
1408 switch (c) {
1409 case 'C':
1410 ctx->Cflag = true;
1411 break;
1412 case 'f':
1413 flags |= BDRV_REQ_FUA;
1414 break;
1415 case 'q':
1416 ctx->qflag = true;
1417 break;
1418 case 'u':
1419 flags |= BDRV_REQ_MAY_UNMAP;
1420 break;
1421 case 'P':
1422 pattern = parse_pattern(optarg);
1423 if (pattern < 0) {
1424 g_free(ctx);
1425 return 0;
1426 }
1427 break;
1428 case 'i':
1429 printf("injecting invalid write request\n");
1430 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
1431 g_free(ctx);
1432 return 0;
1433 case 'z':
1434 ctx->zflag = true;
1435 break;
1436 default:
1437 g_free(ctx);
1438 return qemuio_command_usage(&aio_write_cmd);
1439 }
1440 }
1441
1442 if (optind > argc - 2) {
1443 g_free(ctx);
1444 return qemuio_command_usage(&aio_write_cmd);
1445 }
1446
1447 if (ctx->zflag && optind != argc - 2) {
1448 printf("-z supports only a single length parameter\n");
1449 g_free(ctx);
1450 return 0;
1451 }
1452
1453 if ((flags & BDRV_REQ_MAY_UNMAP) && !ctx->zflag) {
1454 printf("-u requires -z to be specified\n");
1455 g_free(ctx);
1456 return 0;
1457 }
1458
1459 if (ctx->zflag && ctx->Pflag) {
1460 printf("-z and -P cannot be specified at the same time\n");
1461 g_free(ctx);
1462 return 0;
1463 }
1464
1465 ctx->offset = cvtnum(argv[optind]);
1466 if (ctx->offset < 0) {
1467 print_cvtnum_err(ctx->offset, argv[optind]);
1468 g_free(ctx);
1469 return 0;
1470 }
1471 optind++;
1472
1473 if (ctx->zflag) {
1474 int64_t count = cvtnum(argv[optind]);
1475 if (count < 0) {
1476 print_cvtnum_err(count, argv[optind]);
1477 g_free(ctx);
1478 return 0;
1479 }
1480
1481 ctx->qiov.size = count;
1482 blk_aio_pwrite_zeroes(blk, ctx->offset, count, flags, aio_write_done,
1483 ctx);
1484 } else {
1485 nr_iov = argc - optind;
1486 ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov,
1487 pattern);
1488 if (ctx->buf == NULL) {
1489 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
1490 g_free(ctx);
1491 return 0;
1492 }
1493
1494 gettimeofday(&ctx->t1, NULL);
1495 block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
1496 BLOCK_ACCT_WRITE);
1497
1498 blk_aio_pwritev(blk, ctx->offset, &ctx->qiov, flags, aio_write_done,
1499 ctx);
1500 }
1501 return 0;
1502 }
1503
1504 static int aio_flush_f(BlockBackend *blk, int argc, char **argv)
1505 {
1506 BlockAcctCookie cookie;
1507 block_acct_start(blk_get_stats(blk), &cookie, 0, BLOCK_ACCT_FLUSH);
1508 blk_drain_all();
1509 block_acct_done(blk_get_stats(blk), &cookie);
1510 return 0;
1511 }
1512
1513 static const cmdinfo_t aio_flush_cmd = {
1514 .name = "aio_flush",
1515 .cfunc = aio_flush_f,
1516 .oneline = "completes all outstanding aio requests"
1517 };
1518
1519 static int flush_f(BlockBackend *blk, int argc, char **argv)
1520 {
1521 blk_flush(blk);
1522 return 0;
1523 }
1524
1525 static const cmdinfo_t flush_cmd = {
1526 .name = "flush",
1527 .altname = "f",
1528 .cfunc = flush_f,
1529 .oneline = "flush all in-core file state to disk",
1530 };
1531
1532 static int truncate_f(BlockBackend *blk, int argc, char **argv)
1533 {
1534 int64_t offset;
1535 int ret;
1536
1537 offset = cvtnum(argv[1]);
1538 if (offset < 0) {
1539 print_cvtnum_err(offset, argv[1]);
1540 return 0;
1541 }
1542
1543 ret = blk_truncate(blk, offset);
1544 if (ret < 0) {
1545 printf("truncate: %s\n", strerror(-ret));
1546 return 0;
1547 }
1548
1549 return 0;
1550 }
1551
1552 static const cmdinfo_t truncate_cmd = {
1553 .name = "truncate",
1554 .altname = "t",
1555 .cfunc = truncate_f,
1556 .argmin = 1,
1557 .argmax = 1,
1558 .args = "off",
1559 .oneline = "truncates the current file at the given offset",
1560 };
1561
1562 static int length_f(BlockBackend *blk, int argc, char **argv)
1563 {
1564 int64_t size;
1565 char s1[64];
1566
1567 size = blk_getlength(blk);
1568 if (size < 0) {
1569 printf("getlength: %s\n", strerror(-size));
1570 return 0;
1571 }
1572
1573 cvtstr(size, s1, sizeof(s1));
1574 printf("%s\n", s1);
1575 return 0;
1576 }
1577
1578
1579 static const cmdinfo_t length_cmd = {
1580 .name = "length",
1581 .altname = "l",
1582 .cfunc = length_f,
1583 .oneline = "gets the length of the current file",
1584 };
1585
1586
1587 static int info_f(BlockBackend *blk, int argc, char **argv)
1588 {
1589 BlockDriverState *bs = blk_bs(blk);
1590 BlockDriverInfo bdi;
1591 ImageInfoSpecific *spec_info;
1592 char s1[64], s2[64];
1593 int ret;
1594
1595 if (bs->drv && bs->drv->format_name) {
1596 printf("format name: %s\n", bs->drv->format_name);
1597 }
1598 if (bs->drv && bs->drv->protocol_name) {
1599 printf("format name: %s\n", bs->drv->protocol_name);
1600 }
1601
1602 ret = bdrv_get_info(bs, &bdi);
1603 if (ret) {
1604 return 0;
1605 }
1606
1607 cvtstr(bdi.cluster_size, s1, sizeof(s1));
1608 cvtstr(bdi.vm_state_offset, s2, sizeof(s2));
1609
1610 printf("cluster size: %s\n", s1);
1611 printf("vm state offset: %s\n", s2);
1612
1613 spec_info = bdrv_get_specific_info(bs);
1614 if (spec_info) {
1615 printf("Format specific information:\n");
1616 bdrv_image_info_specific_dump(fprintf, stdout, spec_info);
1617 qapi_free_ImageInfoSpecific(spec_info);
1618 }
1619
1620 return 0;
1621 }
1622
1623
1624
1625 static const cmdinfo_t info_cmd = {
1626 .name = "info",
1627 .altname = "i",
1628 .cfunc = info_f,
1629 .oneline = "prints information about the current file",
1630 };
1631
1632 static void discard_help(void)
1633 {
1634 printf(
1635 "\n"
1636 " discards a range of bytes from the given offset\n"
1637 "\n"
1638 " Example:\n"
1639 " 'discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n"
1640 "\n"
1641 " Discards a segment of the currently open file.\n"
1642 " -C, -- report statistics in a machine parsable format\n"
1643 " -q, -- quiet mode, do not show I/O statistics\n"
1644 "\n");
1645 }
1646
1647 static int discard_f(BlockBackend *blk, int argc, char **argv);
1648
1649 static const cmdinfo_t discard_cmd = {
1650 .name = "discard",
1651 .altname = "d",
1652 .cfunc = discard_f,
1653 .argmin = 2,
1654 .argmax = -1,
1655 .args = "[-Cq] off len",
1656 .oneline = "discards a number of bytes at a specified offset",
1657 .help = discard_help,
1658 };
1659
1660 static int discard_f(BlockBackend *blk, int argc, char **argv)
1661 {
1662 struct timeval t1, t2;
1663 bool Cflag = false, qflag = false;
1664 int c, ret;
1665 int64_t offset, count;
1666
1667 while ((c = getopt(argc, argv, "Cq")) != -1) {
1668 switch (c) {
1669 case 'C':
1670 Cflag = true;
1671 break;
1672 case 'q':
1673 qflag = true;
1674 break;
1675 default:
1676 return qemuio_command_usage(&discard_cmd);
1677 }
1678 }
1679
1680 if (optind != argc - 2) {
1681 return qemuio_command_usage(&discard_cmd);
1682 }
1683
1684 offset = cvtnum(argv[optind]);
1685 if (offset < 0) {
1686 print_cvtnum_err(offset, argv[optind]);
1687 return 0;
1688 }
1689
1690 optind++;
1691 count = cvtnum(argv[optind]);
1692 if (count < 0) {
1693 print_cvtnum_err(count, argv[optind]);
1694 return 0;
1695 } else if (count >> BDRV_SECTOR_BITS > BDRV_REQUEST_MAX_SECTORS) {
1696 printf("length cannot exceed %"PRIu64", given %s\n",
1697 (uint64_t)BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS,
1698 argv[optind]);
1699 return 0;
1700 }
1701
1702 gettimeofday(&t1, NULL);
1703 ret = blk_pdiscard(blk, offset, count);
1704 gettimeofday(&t2, NULL);
1705
1706 if (ret < 0) {
1707 printf("discard failed: %s\n", strerror(-ret));
1708 goto out;
1709 }
1710
1711 /* Finally, report back -- -C gives a parsable format */
1712 if (!qflag) {
1713 t2 = tsub(t2, t1);
1714 print_report("discard", &t2, offset, count, count, 1, Cflag);
1715 }
1716
1717 out:
1718 return 0;
1719 }
1720
1721 static int alloc_f(BlockBackend *blk, int argc, char **argv)
1722 {
1723 BlockDriverState *bs = blk_bs(blk);
1724 int64_t offset, sector_num, nb_sectors, remaining;
1725 char s1[64];
1726 int num, ret;
1727 int64_t sum_alloc;
1728
1729 offset = cvtnum(argv[1]);
1730 if (offset < 0) {
1731 print_cvtnum_err(offset, argv[1]);
1732 return 0;
1733 } else if (offset & 0x1ff) {
1734 printf("offset %" PRId64 " is not sector aligned\n",
1735 offset);
1736 return 0;
1737 }
1738
1739 if (argc == 3) {
1740 nb_sectors = cvtnum(argv[2]);
1741 if (nb_sectors < 0) {
1742 print_cvtnum_err(nb_sectors, argv[2]);
1743 return 0;
1744 } else if (nb_sectors > INT_MAX) {
1745 printf("length argument cannot exceed %d, given %s\n",
1746 INT_MAX, argv[2]);
1747 return 0;
1748 }
1749 } else {
1750 nb_sectors = 1;
1751 }
1752
1753 remaining = nb_sectors;
1754 sum_alloc = 0;
1755 sector_num = offset >> 9;
1756 while (remaining) {
1757 ret = bdrv_is_allocated(bs, sector_num, remaining, &num);
1758 if (ret < 0) {
1759 printf("is_allocated failed: %s\n", strerror(-ret));
1760 return 0;
1761 }
1762 sector_num += num;
1763 remaining -= num;
1764 if (ret) {
1765 sum_alloc += num;
1766 }
1767 if (num == 0) {
1768 nb_sectors -= remaining;
1769 remaining = 0;
1770 }
1771 }
1772
1773 cvtstr(offset, s1, sizeof(s1));
1774
1775 printf("%"PRId64"/%"PRId64" sectors allocated at offset %s\n",
1776 sum_alloc, nb_sectors, s1);
1777 return 0;
1778 }
1779
1780 static const cmdinfo_t alloc_cmd = {
1781 .name = "alloc",
1782 .altname = "a",
1783 .argmin = 1,
1784 .argmax = 2,
1785 .cfunc = alloc_f,
1786 .args = "off [sectors]",
1787 .oneline = "checks if a sector is present in the file",
1788 };
1789
1790
1791 static int map_is_allocated(BlockDriverState *bs, int64_t sector_num,
1792 int64_t nb_sectors, int64_t *pnum)
1793 {
1794 int num, num_checked;
1795 int ret, firstret;
1796
1797 num_checked = MIN(nb_sectors, INT_MAX);
1798 ret = bdrv_is_allocated(bs, sector_num, num_checked, &num);
1799 if (ret < 0) {
1800 return ret;
1801 }
1802
1803 firstret = ret;
1804 *pnum = num;
1805
1806 while (nb_sectors > 0 && ret == firstret) {
1807 sector_num += num;
1808 nb_sectors -= num;
1809
1810 num_checked = MIN(nb_sectors, INT_MAX);
1811 ret = bdrv_is_allocated(bs, sector_num, num_checked, &num);
1812 if (ret == firstret && num) {
1813 *pnum += num;
1814 } else {
1815 break;
1816 }
1817 }
1818
1819 return firstret;
1820 }
1821
1822 static int map_f(BlockBackend *blk, int argc, char **argv)
1823 {
1824 int64_t offset;
1825 int64_t nb_sectors, total_sectors;
1826 char s1[64];
1827 int64_t num;
1828 int ret;
1829 const char *retstr;
1830
1831 offset = 0;
1832 total_sectors = blk_nb_sectors(blk);
1833 if (total_sectors < 0) {
1834 error_report("Failed to query image length: %s",
1835 strerror(-total_sectors));
1836 return 0;
1837 }
1838
1839 nb_sectors = total_sectors;
1840
1841 do {
1842 ret = map_is_allocated(blk_bs(blk), offset, nb_sectors, &num);
1843 if (ret < 0) {
1844 error_report("Failed to get allocation status: %s", strerror(-ret));
1845 return 0;
1846 } else if (!num) {
1847 error_report("Unexpected end of image");
1848 return 0;
1849 }
1850
1851 retstr = ret ? " allocated" : "not allocated";
1852 cvtstr(offset << 9ULL, s1, sizeof(s1));
1853 printf("[% 24" PRId64 "] % 8" PRId64 "/% 8" PRId64 " sectors %s "
1854 "at offset %s (%d)\n",
1855 offset << 9ULL, num, nb_sectors, retstr, s1, ret);
1856
1857 offset += num;
1858 nb_sectors -= num;
1859 } while (offset < total_sectors);
1860
1861 return 0;
1862 }
1863
1864 static const cmdinfo_t map_cmd = {
1865 .name = "map",
1866 .argmin = 0,
1867 .argmax = 0,
1868 .cfunc = map_f,
1869 .args = "",
1870 .oneline = "prints the allocated areas of a file",
1871 };
1872
1873 static void reopen_help(void)
1874 {
1875 printf(
1876 "\n"
1877 " Changes the open options of an already opened image\n"
1878 "\n"
1879 " Example:\n"
1880 " 'reopen -o lazy-refcounts=on' - activates lazy refcount writeback on a qcow2 image\n"
1881 "\n"
1882 " -r, -- Reopen the image read-only\n"
1883 " -c, -- Change the cache mode to the given value\n"
1884 " -o, -- Changes block driver options (cf. 'open' command)\n"
1885 "\n");
1886 }
1887
1888 static int reopen_f(BlockBackend *blk, int argc, char **argv);
1889
1890 static QemuOptsList reopen_opts = {
1891 .name = "reopen",
1892 .merge_lists = true,
1893 .head = QTAILQ_HEAD_INITIALIZER(reopen_opts.head),
1894 .desc = {
1895 /* no elements => accept any params */
1896 { /* end of list */ }
1897 },
1898 };
1899
1900 static const cmdinfo_t reopen_cmd = {
1901 .name = "reopen",
1902 .argmin = 0,
1903 .argmax = -1,
1904 .cfunc = reopen_f,
1905 .args = "[-r] [-c cache] [-o options]",
1906 .oneline = "reopens an image with new options",
1907 .help = reopen_help,
1908 };
1909
1910 static int reopen_f(BlockBackend *blk, int argc, char **argv)
1911 {
1912 BlockDriverState *bs = blk_bs(blk);
1913 QemuOpts *qopts;
1914 QDict *opts;
1915 int c;
1916 int flags = bs->open_flags;
1917 bool writethrough = !blk_enable_write_cache(blk);
1918
1919 BlockReopenQueue *brq;
1920 Error *local_err = NULL;
1921
1922 while ((c = getopt(argc, argv, "c:o:r")) != -1) {
1923 switch (c) {
1924 case 'c':
1925 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) < 0) {
1926 error_report("Invalid cache option: %s", optarg);
1927 return 0;
1928 }
1929 break;
1930 case 'o':
1931 if (!qemu_opts_parse_noisily(&reopen_opts, optarg, 0)) {
1932 qemu_opts_reset(&reopen_opts);
1933 return 0;
1934 }
1935 break;
1936 case 'r':
1937 flags &= ~BDRV_O_RDWR;
1938 break;
1939 default:
1940 qemu_opts_reset(&reopen_opts);
1941 return qemuio_command_usage(&reopen_cmd);
1942 }
1943 }
1944
1945 if (optind != argc) {
1946 qemu_opts_reset(&reopen_opts);
1947 return qemuio_command_usage(&reopen_cmd);
1948 }
1949
1950 if (writethrough != blk_enable_write_cache(blk) &&
1951 blk_get_attached_dev(blk))
1952 {
1953 error_report("Cannot change cache.writeback: Device attached");
1954 qemu_opts_reset(&reopen_opts);
1955 return 0;
1956 }
1957
1958 qopts = qemu_opts_find(&reopen_opts, NULL);
1959 opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : NULL;
1960 qemu_opts_reset(&reopen_opts);
1961
1962 brq = bdrv_reopen_queue(NULL, bs, opts, flags);
1963 bdrv_reopen_multiple(bdrv_get_aio_context(bs), brq, &local_err);
1964 if (local_err) {
1965 error_report_err(local_err);
1966 } else {
1967 blk_set_enable_write_cache(blk, !writethrough);
1968 }
1969
1970 return 0;
1971 }
1972
1973 static int break_f(BlockBackend *blk, int argc, char **argv)
1974 {
1975 int ret;
1976
1977 ret = bdrv_debug_breakpoint(blk_bs(blk), argv[1], argv[2]);
1978 if (ret < 0) {
1979 printf("Could not set breakpoint: %s\n", strerror(-ret));
1980 }
1981
1982 return 0;
1983 }
1984
1985 static int remove_break_f(BlockBackend *blk, int argc, char **argv)
1986 {
1987 int ret;
1988
1989 ret = bdrv_debug_remove_breakpoint(blk_bs(blk), argv[1]);
1990 if (ret < 0) {
1991 printf("Could not remove breakpoint %s: %s\n", argv[1], strerror(-ret));
1992 }
1993
1994 return 0;
1995 }
1996
1997 static const cmdinfo_t break_cmd = {
1998 .name = "break",
1999 .argmin = 2,
2000 .argmax = 2,
2001 .cfunc = break_f,
2002 .args = "event tag",
2003 .oneline = "sets a breakpoint on event and tags the stopped "
2004 "request as tag",
2005 };
2006
2007 static const cmdinfo_t remove_break_cmd = {
2008 .name = "remove_break",
2009 .argmin = 1,
2010 .argmax = 1,
2011 .cfunc = remove_break_f,
2012 .args = "tag",
2013 .oneline = "remove a breakpoint by tag",
2014 };
2015
2016 static int resume_f(BlockBackend *blk, int argc, char **argv)
2017 {
2018 int ret;
2019
2020 ret = bdrv_debug_resume(blk_bs(blk), argv[1]);
2021 if (ret < 0) {
2022 printf("Could not resume request: %s\n", strerror(-ret));
2023 }
2024
2025 return 0;
2026 }
2027
2028 static const cmdinfo_t resume_cmd = {
2029 .name = "resume",
2030 .argmin = 1,
2031 .argmax = 1,
2032 .cfunc = resume_f,
2033 .args = "tag",
2034 .oneline = "resumes the request tagged as tag",
2035 };
2036
2037 static int wait_break_f(BlockBackend *blk, int argc, char **argv)
2038 {
2039 while (!bdrv_debug_is_suspended(blk_bs(blk), argv[1])) {
2040 aio_poll(blk_get_aio_context(blk), true);
2041 }
2042
2043 return 0;
2044 }
2045
2046 static const cmdinfo_t wait_break_cmd = {
2047 .name = "wait_break",
2048 .argmin = 1,
2049 .argmax = 1,
2050 .cfunc = wait_break_f,
2051 .args = "tag",
2052 .oneline = "waits for the suspension of a request",
2053 };
2054
2055 static int abort_f(BlockBackend *blk, int argc, char **argv)
2056 {
2057 abort();
2058 }
2059
2060 static const cmdinfo_t abort_cmd = {
2061 .name = "abort",
2062 .cfunc = abort_f,
2063 .flags = CMD_NOFILE_OK,
2064 .oneline = "simulate a program crash using abort(3)",
2065 };
2066
2067 static void sigraise_help(void)
2068 {
2069 printf(
2070 "\n"
2071 " raises the given signal\n"
2072 "\n"
2073 " Example:\n"
2074 " 'sigraise %i' - raises SIGTERM\n"
2075 "\n"
2076 " Invokes raise(signal), where \"signal\" is the mandatory integer argument\n"
2077 " given to sigraise.\n"
2078 "\n", SIGTERM);
2079 }
2080
2081 static int sigraise_f(BlockBackend *blk, int argc, char **argv);
2082
2083 static const cmdinfo_t sigraise_cmd = {
2084 .name = "sigraise",
2085 .cfunc = sigraise_f,
2086 .argmin = 1,
2087 .argmax = 1,
2088 .flags = CMD_NOFILE_OK,
2089 .args = "signal",
2090 .oneline = "raises a signal",
2091 .help = sigraise_help,
2092 };
2093
2094 static int sigraise_f(BlockBackend *blk, int argc, char **argv)
2095 {
2096 int64_t sig = cvtnum(argv[1]);
2097 if (sig < 0) {
2098 print_cvtnum_err(sig, argv[1]);
2099 return 0;
2100 } else if (sig > NSIG) {
2101 printf("signal argument '%s' is too large to be a valid signal\n",
2102 argv[1]);
2103 return 0;
2104 }
2105
2106 /* Using raise() to kill this process does not necessarily flush all open
2107 * streams. At least stdout and stderr (although the latter should be
2108 * non-buffered anyway) should be flushed, though. */
2109 fflush(stdout);
2110 fflush(stderr);
2111
2112 raise(sig);
2113 return 0;
2114 }
2115
2116 static void sleep_cb(void *opaque)
2117 {
2118 bool *expired = opaque;
2119 *expired = true;
2120 }
2121
2122 static int sleep_f(BlockBackend *blk, int argc, char **argv)
2123 {
2124 char *endptr;
2125 long ms;
2126 struct QEMUTimer *timer;
2127 bool expired = false;
2128
2129 ms = strtol(argv[1], &endptr, 0);
2130 if (ms < 0 || *endptr != '\0') {
2131 printf("%s is not a valid number\n", argv[1]);
2132 return 0;
2133 }
2134
2135 timer = timer_new_ns(QEMU_CLOCK_HOST, sleep_cb, &expired);
2136 timer_mod(timer, qemu_clock_get_ns(QEMU_CLOCK_HOST) + SCALE_MS * ms);
2137
2138 while (!expired) {
2139 main_loop_wait(false);
2140 }
2141
2142 timer_free(timer);
2143
2144 return 0;
2145 }
2146
2147 static const cmdinfo_t sleep_cmd = {
2148 .name = "sleep",
2149 .argmin = 1,
2150 .argmax = 1,
2151 .cfunc = sleep_f,
2152 .flags = CMD_NOFILE_OK,
2153 .oneline = "waits for the given value in milliseconds",
2154 };
2155
2156 static void help_oneline(const char *cmd, const cmdinfo_t *ct)
2157 {
2158 if (cmd) {
2159 printf("%s ", cmd);
2160 } else {
2161 printf("%s ", ct->name);
2162 if (ct->altname) {
2163 printf("(or %s) ", ct->altname);
2164 }
2165 }
2166
2167 if (ct->args) {
2168 printf("%s ", ct->args);
2169 }
2170 printf("-- %s\n", ct->oneline);
2171 }
2172
2173 static void help_onecmd(const char *cmd, const cmdinfo_t *ct)
2174 {
2175 help_oneline(cmd, ct);
2176 if (ct->help) {
2177 ct->help();
2178 }
2179 }
2180
2181 static void help_all(void)
2182 {
2183 const cmdinfo_t *ct;
2184
2185 for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
2186 help_oneline(ct->name, ct);
2187 }
2188 printf("\nUse 'help commandname' for extended help.\n");
2189 }
2190
2191 static int help_f(BlockBackend *blk, int argc, char **argv)
2192 {
2193 const cmdinfo_t *ct;
2194
2195 if (argc == 1) {
2196 help_all();
2197 return 0;
2198 }
2199
2200 ct = find_command(argv[1]);
2201 if (ct == NULL) {
2202 printf("command %s not found\n", argv[1]);
2203 return 0;
2204 }
2205
2206 help_onecmd(argv[1], ct);
2207 return 0;
2208 }
2209
2210 static const cmdinfo_t help_cmd = {
2211 .name = "help",
2212 .altname = "?",
2213 .cfunc = help_f,
2214 .argmin = 0,
2215 .argmax = 1,
2216 .flags = CMD_FLAG_GLOBAL,
2217 .args = "[command]",
2218 .oneline = "help for one or all commands",
2219 };
2220
2221 bool qemuio_command(BlockBackend *blk, const char *cmd)
2222 {
2223 AioContext *ctx;
2224 char *input;
2225 const cmdinfo_t *ct;
2226 char **v;
2227 int c;
2228 bool done = false;
2229
2230 input = g_strdup(cmd);
2231 v = breakline(input, &c);
2232 if (c) {
2233 ct = find_command(v[0]);
2234 if (ct) {
2235 ctx = blk ? blk_get_aio_context(blk) : qemu_get_aio_context();
2236 aio_context_acquire(ctx);
2237 done = command(blk, ct, c, v);
2238 aio_context_release(ctx);
2239 } else {
2240 fprintf(stderr, "command \"%s\" not found\n", v[0]);
2241 }
2242 }
2243 g_free(input);
2244 g_free(v);
2245
2246 return done;
2247 }
2248
2249 static void __attribute((constructor)) init_qemuio_commands(void)
2250 {
2251 /* initialize commands */
2252 qemuio_add_command(&help_cmd);
2253 qemuio_add_command(&read_cmd);
2254 qemuio_add_command(&readv_cmd);
2255 qemuio_add_command(&write_cmd);
2256 qemuio_add_command(&writev_cmd);
2257 qemuio_add_command(&aio_read_cmd);
2258 qemuio_add_command(&aio_write_cmd);
2259 qemuio_add_command(&aio_flush_cmd);
2260 qemuio_add_command(&flush_cmd);
2261 qemuio_add_command(&truncate_cmd);
2262 qemuio_add_command(&length_cmd);
2263 qemuio_add_command(&info_cmd);
2264 qemuio_add_command(&discard_cmd);
2265 qemuio_add_command(&alloc_cmd);
2266 qemuio_add_command(&map_cmd);
2267 qemuio_add_command(&reopen_cmd);
2268 qemuio_add_command(&break_cmd);
2269 qemuio_add_command(&remove_break_cmd);
2270 qemuio_add_command(&resume_cmd);
2271 qemuio_add_command(&wait_break_cmd);
2272 qemuio_add_command(&abort_cmd);
2273 qemuio_add_command(&sleep_cmd);
2274 qemuio_add_command(&sigraise_cmd);
2275 }