]> Git Repo - qemu.git/blob - qemu-io.c
qemu-io: Handle cvtnum() errors in 'alloc'
[qemu.git] / qemu-io.c
1 /*
2  * Command line utility to exercise the QEMU I/O path.
3  *
4  * Copyright (C) 2009 Red Hat, Inc.
5  * Copyright (c) 2003-2005 Silicon Graphics, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or later.
8  * See the COPYING file in the top-level directory.
9  */
10 #include <sys/time.h>
11 #include <sys/types.h>
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <getopt.h>
15 #include <libgen.h>
16
17 #include "qemu-common.h"
18 #include "qemu/main-loop.h"
19 #include "block/block_int.h"
20 #include "cmd.h"
21 #include "trace/control.h"
22
23 #define VERSION "0.0.1"
24
25 #define CMD_NOFILE_OK   0x01
26
27 char *progname;
28 static BlockDriverState *bs;
29
30 static int misalign;
31
32 static int64_t cvtnum(const char *s)
33 {
34     char *end;
35     return strtosz_suffix(s, &end, STRTOSZ_DEFSUFFIX_B);
36 }
37
38 /*
39  * Parse the pattern argument to various sub-commands.
40  *
41  * Because the pattern is used as an argument to memset it must evaluate
42  * to an unsigned integer that fits into a single byte.
43  */
44 static int parse_pattern(const char *arg)
45 {
46     char *endptr = NULL;
47     long pattern;
48
49     pattern = strtol(arg, &endptr, 0);
50     if (pattern < 0 || pattern > UCHAR_MAX || *endptr != '\0') {
51         printf("%s is not a valid pattern byte\n", arg);
52         return -1;
53     }
54
55     return pattern;
56 }
57
58 /*
59  * Memory allocation helpers.
60  *
61  * Make sure memory is aligned by default, or purposefully misaligned if
62  * that is specified on the command line.
63  */
64
65 #define MISALIGN_OFFSET     16
66 static void *qemu_io_alloc(size_t len, int pattern)
67 {
68     void *buf;
69
70     if (misalign) {
71         len += MISALIGN_OFFSET;
72     }
73     buf = qemu_blockalign(bs, len);
74     memset(buf, pattern, len);
75     if (misalign) {
76         buf += MISALIGN_OFFSET;
77     }
78     return buf;
79 }
80
81 static void qemu_io_free(void *p)
82 {
83     if (misalign) {
84         p -= MISALIGN_OFFSET;
85     }
86     qemu_vfree(p);
87 }
88
89 static void dump_buffer(const void *buffer, int64_t offset, int len)
90 {
91     int i, j;
92     const uint8_t *p;
93
94     for (i = 0, p = buffer; i < len; i += 16) {
95         const uint8_t *s = p;
96
97         printf("%08" PRIx64 ":  ", offset + i);
98         for (j = 0; j < 16 && i + j < len; j++, p++) {
99             printf("%02x ", *p);
100         }
101         printf(" ");
102         for (j = 0; j < 16 && i + j < len; j++, s++) {
103             if (isalnum(*s)) {
104                 printf("%c", *s);
105             } else {
106                 printf(".");
107             }
108         }
109         printf("\n");
110     }
111 }
112
113 static void print_report(const char *op, struct timeval *t, int64_t offset,
114                          int count, int total, int cnt, int Cflag)
115 {
116     char s1[64], s2[64], ts[64];
117
118     timestr(t, ts, sizeof(ts), Cflag ? VERBOSE_FIXED_TIME : 0);
119     if (!Cflag) {
120         cvtstr((double)total, s1, sizeof(s1));
121         cvtstr(tdiv((double)total, *t), s2, sizeof(s2));
122         printf("%s %d/%d bytes at offset %" PRId64 "\n",
123                op, total, count, offset);
124         printf("%s, %d ops; %s (%s/sec and %.4f ops/sec)\n",
125                s1, cnt, ts, s2, tdiv((double)cnt, *t));
126     } else {/* bytes,ops,time,bytes/sec,ops/sec */
127         printf("%d,%d,%s,%.3f,%.3f\n",
128             total, cnt, ts,
129             tdiv((double)total, *t),
130             tdiv((double)cnt, *t));
131     }
132 }
133
134 /*
135  * Parse multiple length statements for vectored I/O, and construct an I/O
136  * vector matching it.
137  */
138 static void *
139 create_iovec(QEMUIOVector *qiov, char **argv, int nr_iov, int pattern)
140 {
141     size_t *sizes = g_new0(size_t, nr_iov);
142     size_t count = 0;
143     void *buf = NULL;
144     void *p;
145     int i;
146
147     for (i = 0; i < nr_iov; i++) {
148         char *arg = argv[i];
149         int64_t len;
150
151         len = cvtnum(arg);
152         if (len < 0) {
153             printf("non-numeric length argument -- %s\n", arg);
154             goto fail;
155         }
156
157         /* should be SIZE_T_MAX, but that doesn't exist */
158         if (len > INT_MAX) {
159             printf("too large length argument -- %s\n", arg);
160             goto fail;
161         }
162
163         if (len & 0x1ff) {
164             printf("length argument %" PRId64
165                    " is not sector aligned\n", len);
166             goto fail;
167         }
168
169         sizes[i] = len;
170         count += len;
171     }
172
173     qemu_iovec_init(qiov, nr_iov);
174
175     buf = p = qemu_io_alloc(count, pattern);
176
177     for (i = 0; i < nr_iov; i++) {
178         qemu_iovec_add(qiov, p, sizes[i]);
179         p += sizes[i];
180     }
181
182 fail:
183     g_free(sizes);
184     return buf;
185 }
186
187 static int do_read(char *buf, int64_t offset, int count, int *total)
188 {
189     int ret;
190
191     ret = bdrv_read(bs, offset >> 9, (uint8_t *)buf, count >> 9);
192     if (ret < 0) {
193         return ret;
194     }
195     *total = count;
196     return 1;
197 }
198
199 static int do_write(char *buf, int64_t offset, int count, int *total)
200 {
201     int ret;
202
203     ret = bdrv_write(bs, offset >> 9, (uint8_t *)buf, count >> 9);
204     if (ret < 0) {
205         return ret;
206     }
207     *total = count;
208     return 1;
209 }
210
211 static int do_pread(char *buf, int64_t offset, int count, int *total)
212 {
213     *total = bdrv_pread(bs, offset, (uint8_t *)buf, count);
214     if (*total < 0) {
215         return *total;
216     }
217     return 1;
218 }
219
220 static int do_pwrite(char *buf, int64_t offset, int count, int *total)
221 {
222     *total = bdrv_pwrite(bs, offset, (uint8_t *)buf, count);
223     if (*total < 0) {
224         return *total;
225     }
226     return 1;
227 }
228
229 typedef struct {
230     int64_t offset;
231     int count;
232     int *total;
233     int ret;
234     bool done;
235 } CoWriteZeroes;
236
237 static void coroutine_fn co_write_zeroes_entry(void *opaque)
238 {
239     CoWriteZeroes *data = opaque;
240
241     data->ret = bdrv_co_write_zeroes(bs, data->offset / BDRV_SECTOR_SIZE,
242                                      data->count / BDRV_SECTOR_SIZE);
243     data->done = true;
244     if (data->ret < 0) {
245         *data->total = data->ret;
246         return;
247     }
248
249     *data->total = data->count;
250 }
251
252 static int do_co_write_zeroes(int64_t offset, int count, int *total)
253 {
254     Coroutine *co;
255     CoWriteZeroes data = {
256         .offset = offset,
257         .count  = count,
258         .total  = total,
259         .done   = false,
260     };
261
262     co = qemu_coroutine_create(co_write_zeroes_entry);
263     qemu_coroutine_enter(co, &data);
264     while (!data.done) {
265         qemu_aio_wait();
266     }
267     if (data.ret < 0) {
268         return data.ret;
269     } else {
270         return 1;
271     }
272 }
273
274 static int do_write_compressed(char *buf, int64_t offset, int count, int *total)
275 {
276     int ret;
277
278     ret = bdrv_write_compressed(bs, offset >> 9, (uint8_t *)buf, count >> 9);
279     if (ret < 0) {
280         return ret;
281     }
282     *total = count;
283     return 1;
284 }
285
286 static int do_load_vmstate(char *buf, int64_t offset, int count, int *total)
287 {
288     *total = bdrv_load_vmstate(bs, (uint8_t *)buf, offset, count);
289     if (*total < 0) {
290         return *total;
291     }
292     return 1;
293 }
294
295 static int do_save_vmstate(char *buf, int64_t offset, int count, int *total)
296 {
297     *total = bdrv_save_vmstate(bs, (uint8_t *)buf, offset, count);
298     if (*total < 0) {
299         return *total;
300     }
301     return 1;
302 }
303
304 #define NOT_DONE 0x7fffffff
305 static void aio_rw_done(void *opaque, int ret)
306 {
307     *(int *)opaque = ret;
308 }
309
310 static int do_aio_readv(QEMUIOVector *qiov, int64_t offset, int *total)
311 {
312     int async_ret = NOT_DONE;
313
314     bdrv_aio_readv(bs, offset >> 9, qiov, qiov->size >> 9,
315                    aio_rw_done, &async_ret);
316     while (async_ret == NOT_DONE) {
317         main_loop_wait(false);
318     }
319
320     *total = qiov->size;
321     return async_ret < 0 ? async_ret : 1;
322 }
323
324 static int do_aio_writev(QEMUIOVector *qiov, int64_t offset, int *total)
325 {
326     int async_ret = NOT_DONE;
327
328     bdrv_aio_writev(bs, offset >> 9, qiov, qiov->size >> 9,
329                     aio_rw_done, &async_ret);
330     while (async_ret == NOT_DONE) {
331         main_loop_wait(false);
332     }
333
334     *total = qiov->size;
335     return async_ret < 0 ? async_ret : 1;
336 }
337
338 struct multiwrite_async_ret {
339     int num_done;
340     int error;
341 };
342
343 static void multiwrite_cb(void *opaque, int ret)
344 {
345     struct multiwrite_async_ret *async_ret = opaque;
346
347     async_ret->num_done++;
348     if (ret < 0) {
349         async_ret->error = ret;
350     }
351 }
352
353 static int do_aio_multiwrite(BlockRequest* reqs, int num_reqs, int *total)
354 {
355     int i, ret;
356     struct multiwrite_async_ret async_ret = {
357         .num_done = 0,
358         .error = 0,
359     };
360
361     *total = 0;
362     for (i = 0; i < num_reqs; i++) {
363         reqs[i].cb = multiwrite_cb;
364         reqs[i].opaque = &async_ret;
365         *total += reqs[i].qiov->size;
366     }
367
368     ret = bdrv_aio_multiwrite(bs, reqs, num_reqs);
369     if (ret < 0) {
370         return ret;
371     }
372
373     while (async_ret.num_done < num_reqs) {
374         main_loop_wait(false);
375     }
376
377     return async_ret.error < 0 ? async_ret.error : 1;
378 }
379
380 static void read_help(void)
381 {
382     printf(
383 "\n"
384 " reads a range of bytes from the given offset\n"
385 "\n"
386 " Example:\n"
387 " 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n"
388 "\n"
389 " Reads a segment of the currently open file, optionally dumping it to the\n"
390 " standard output stream (with -v option) for subsequent inspection.\n"
391 " -b, -- read from the VM state rather than the virtual disk\n"
392 " -C, -- report statistics in a machine parsable format\n"
393 " -l, -- length for pattern verification (only with -P)\n"
394 " -p, -- use bdrv_pread to read the file\n"
395 " -P, -- use a pattern to verify read data\n"
396 " -q, -- quiet mode, do not show I/O statistics\n"
397 " -s, -- start offset for pattern verification (only with -P)\n"
398 " -v, -- dump buffer to standard output\n"
399 "\n");
400 }
401
402 static int read_f(int argc, char **argv);
403
404 static const cmdinfo_t read_cmd = {
405     .name       = "read",
406     .altname    = "r",
407     .cfunc      = read_f,
408     .argmin     = 2,
409     .argmax     = -1,
410     .args       = "[-abCpqv] [-P pattern [-s off] [-l len]] off len",
411     .oneline    = "reads a number of bytes at a specified offset",
412     .help       = read_help,
413 };
414
415 static int read_f(int argc, char **argv)
416 {
417     struct timeval t1, t2;
418     int Cflag = 0, pflag = 0, qflag = 0, vflag = 0;
419     int Pflag = 0, sflag = 0, lflag = 0, bflag = 0;
420     int c, cnt;
421     char *buf;
422     int64_t offset;
423     int count;
424     /* Some compilers get confused and warn if this is not initialized.  */
425     int total = 0;
426     int pattern = 0, pattern_offset = 0, pattern_count = 0;
427
428     while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != EOF) {
429         switch (c) {
430         case 'b':
431             bflag = 1;
432             break;
433         case 'C':
434             Cflag = 1;
435             break;
436         case 'l':
437             lflag = 1;
438             pattern_count = cvtnum(optarg);
439             if (pattern_count < 0) {
440                 printf("non-numeric length argument -- %s\n", optarg);
441                 return 0;
442             }
443             break;
444         case 'p':
445             pflag = 1;
446             break;
447         case 'P':
448             Pflag = 1;
449             pattern = parse_pattern(optarg);
450             if (pattern < 0) {
451                 return 0;
452             }
453             break;
454         case 'q':
455             qflag = 1;
456             break;
457         case 's':
458             sflag = 1;
459             pattern_offset = cvtnum(optarg);
460             if (pattern_offset < 0) {
461                 printf("non-numeric length argument -- %s\n", optarg);
462                 return 0;
463             }
464             break;
465         case 'v':
466             vflag = 1;
467             break;
468         default:
469             return command_usage(&read_cmd);
470         }
471     }
472
473     if (optind != argc - 2) {
474         return command_usage(&read_cmd);
475     }
476
477     if (bflag && pflag) {
478         printf("-b and -p cannot be specified at the same time\n");
479         return 0;
480     }
481
482     offset = cvtnum(argv[optind]);
483     if (offset < 0) {
484         printf("non-numeric length argument -- %s\n", argv[optind]);
485         return 0;
486     }
487
488     optind++;
489     count = cvtnum(argv[optind]);
490     if (count < 0) {
491         printf("non-numeric length argument -- %s\n", argv[optind]);
492         return 0;
493     }
494
495     if (!Pflag && (lflag || sflag)) {
496         return command_usage(&read_cmd);
497     }
498
499     if (!lflag) {
500         pattern_count = count - pattern_offset;
501     }
502
503     if ((pattern_count < 0) || (pattern_count + pattern_offset > count))  {
504         printf("pattern verification range exceeds end of read data\n");
505         return 0;
506     }
507
508     if (!pflag) {
509         if (offset & 0x1ff) {
510             printf("offset %" PRId64 " is not sector aligned\n",
511                    offset);
512             return 0;
513         }
514         if (count & 0x1ff) {
515             printf("count %d is not sector aligned\n",
516                    count);
517             return 0;
518         }
519     }
520
521     buf = qemu_io_alloc(count, 0xab);
522
523     gettimeofday(&t1, NULL);
524     if (pflag) {
525         cnt = do_pread(buf, offset, count, &total);
526     } else if (bflag) {
527         cnt = do_load_vmstate(buf, offset, count, &total);
528     } else {
529         cnt = do_read(buf, offset, count, &total);
530     }
531     gettimeofday(&t2, NULL);
532
533     if (cnt < 0) {
534         printf("read failed: %s\n", strerror(-cnt));
535         goto out;
536     }
537
538     if (Pflag) {
539         void *cmp_buf = g_malloc(pattern_count);
540         memset(cmp_buf, pattern, pattern_count);
541         if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {
542             printf("Pattern verification failed at offset %"
543                    PRId64 ", %d bytes\n",
544                    offset + pattern_offset, pattern_count);
545         }
546         g_free(cmp_buf);
547     }
548
549     if (qflag) {
550         goto out;
551     }
552
553     if (vflag) {
554         dump_buffer(buf, offset, count);
555     }
556
557     /* Finally, report back -- -C gives a parsable format */
558     t2 = tsub(t2, t1);
559     print_report("read", &t2, offset, count, total, cnt, Cflag);
560
561 out:
562     qemu_io_free(buf);
563
564     return 0;
565 }
566
567 static void readv_help(void)
568 {
569     printf(
570 "\n"
571 " reads a range of bytes from the given offset into multiple buffers\n"
572 "\n"
573 " Example:\n"
574 " 'readv -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
575 "\n"
576 " Reads a segment of the currently open file, optionally dumping it to the\n"
577 " standard output stream (with -v option) for subsequent inspection.\n"
578 " Uses multiple iovec buffers if more than one byte range is specified.\n"
579 " -C, -- report statistics in a machine parsable format\n"
580 " -P, -- use a pattern to verify read data\n"
581 " -v, -- dump buffer to standard output\n"
582 " -q, -- quiet mode, do not show I/O statistics\n"
583 "\n");
584 }
585
586 static int readv_f(int argc, char **argv);
587
588 static const cmdinfo_t readv_cmd = {
589     .name       = "readv",
590     .cfunc      = readv_f,
591     .argmin     = 2,
592     .argmax     = -1,
593     .args       = "[-Cqv] [-P pattern ] off len [len..]",
594     .oneline    = "reads a number of bytes at a specified offset",
595     .help       = readv_help,
596 };
597
598 static int readv_f(int argc, char **argv)
599 {
600     struct timeval t1, t2;
601     int Cflag = 0, qflag = 0, vflag = 0;
602     int c, cnt;
603     char *buf;
604     int64_t offset;
605     /* Some compilers get confused and warn if this is not initialized.  */
606     int total = 0;
607     int nr_iov;
608     QEMUIOVector qiov;
609     int pattern = 0;
610     int Pflag = 0;
611
612     while ((c = getopt(argc, argv, "CP:qv")) != EOF) {
613         switch (c) {
614         case 'C':
615             Cflag = 1;
616             break;
617         case 'P':
618             Pflag = 1;
619             pattern = parse_pattern(optarg);
620             if (pattern < 0) {
621                 return 0;
622             }
623             break;
624         case 'q':
625             qflag = 1;
626             break;
627         case 'v':
628             vflag = 1;
629             break;
630         default:
631             return command_usage(&readv_cmd);
632         }
633     }
634
635     if (optind > argc - 2) {
636         return command_usage(&readv_cmd);
637     }
638
639
640     offset = cvtnum(argv[optind]);
641     if (offset < 0) {
642         printf("non-numeric length argument -- %s\n", argv[optind]);
643         return 0;
644     }
645     optind++;
646
647     if (offset & 0x1ff) {
648         printf("offset %" PRId64 " is not sector aligned\n",
649                offset);
650         return 0;
651     }
652
653     nr_iov = argc - optind;
654     buf = create_iovec(&qiov, &argv[optind], nr_iov, 0xab);
655     if (buf == NULL) {
656         return 0;
657     }
658
659     gettimeofday(&t1, NULL);
660     cnt = do_aio_readv(&qiov, offset, &total);
661     gettimeofday(&t2, NULL);
662
663     if (cnt < 0) {
664         printf("readv failed: %s\n", strerror(-cnt));
665         goto out;
666     }
667
668     if (Pflag) {
669         void *cmp_buf = g_malloc(qiov.size);
670         memset(cmp_buf, pattern, qiov.size);
671         if (memcmp(buf, cmp_buf, qiov.size)) {
672             printf("Pattern verification failed at offset %"
673                    PRId64 ", %zd bytes\n", offset, qiov.size);
674         }
675         g_free(cmp_buf);
676     }
677
678     if (qflag) {
679         goto out;
680     }
681
682     if (vflag) {
683         dump_buffer(buf, offset, qiov.size);
684     }
685
686     /* Finally, report back -- -C gives a parsable format */
687     t2 = tsub(t2, t1);
688     print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
689
690 out:
691     qemu_iovec_destroy(&qiov);
692     qemu_io_free(buf);
693     return 0;
694 }
695
696 static void write_help(void)
697 {
698     printf(
699 "\n"
700 " writes a range of bytes from the given offset\n"
701 "\n"
702 " Example:\n"
703 " 'write 512 1k' - writes 1 kilobyte at 512 bytes into the open file\n"
704 "\n"
705 " Writes into a segment of the currently open file, using a buffer\n"
706 " filled with a set pattern (0xcdcdcdcd).\n"
707 " -b, -- write to the VM state rather than the virtual disk\n"
708 " -c, -- write compressed data with bdrv_write_compressed\n"
709 " -p, -- use bdrv_pwrite to write the file\n"
710 " -P, -- use different pattern to fill file\n"
711 " -C, -- report statistics in a machine parsable format\n"
712 " -q, -- quiet mode, do not show I/O statistics\n"
713 " -z, -- write zeroes using bdrv_co_write_zeroes\n"
714 "\n");
715 }
716
717 static int write_f(int argc, char **argv);
718
719 static const cmdinfo_t write_cmd = {
720     .name       = "write",
721     .altname    = "w",
722     .cfunc      = write_f,
723     .argmin     = 2,
724     .argmax     = -1,
725     .args       = "[-bcCpqz] [-P pattern ] off len",
726     .oneline    = "writes a number of bytes at a specified offset",
727     .help       = write_help,
728 };
729
730 static int write_f(int argc, char **argv)
731 {
732     struct timeval t1, t2;
733     int Cflag = 0, pflag = 0, qflag = 0, bflag = 0, Pflag = 0, zflag = 0;
734     int cflag = 0;
735     int c, cnt;
736     char *buf = NULL;
737     int64_t offset;
738     int count;
739     /* Some compilers get confused and warn if this is not initialized.  */
740     int total = 0;
741     int pattern = 0xcd;
742
743     while ((c = getopt(argc, argv, "bcCpP:qz")) != EOF) {
744         switch (c) {
745         case 'b':
746             bflag = 1;
747             break;
748         case 'c':
749             cflag = 1;
750             break;
751         case 'C':
752             Cflag = 1;
753             break;
754         case 'p':
755             pflag = 1;
756             break;
757         case 'P':
758             Pflag = 1;
759             pattern = parse_pattern(optarg);
760             if (pattern < 0) {
761                 return 0;
762             }
763             break;
764         case 'q':
765             qflag = 1;
766             break;
767         case 'z':
768             zflag = 1;
769             break;
770         default:
771             return command_usage(&write_cmd);
772         }
773     }
774
775     if (optind != argc - 2) {
776         return command_usage(&write_cmd);
777     }
778
779     if (bflag + pflag + zflag > 1) {
780         printf("-b, -p, or -z cannot be specified at the same time\n");
781         return 0;
782     }
783
784     if (zflag && Pflag) {
785         printf("-z and -P cannot be specified at the same time\n");
786         return 0;
787     }
788
789     offset = cvtnum(argv[optind]);
790     if (offset < 0) {
791         printf("non-numeric length argument -- %s\n", argv[optind]);
792         return 0;
793     }
794
795     optind++;
796     count = cvtnum(argv[optind]);
797     if (count < 0) {
798         printf("non-numeric length argument -- %s\n", argv[optind]);
799         return 0;
800     }
801
802     if (!pflag) {
803         if (offset & 0x1ff) {
804             printf("offset %" PRId64 " is not sector aligned\n",
805                    offset);
806             return 0;
807         }
808
809         if (count & 0x1ff) {
810             printf("count %d is not sector aligned\n",
811                    count);
812             return 0;
813         }
814     }
815
816     if (!zflag) {
817         buf = qemu_io_alloc(count, pattern);
818     }
819
820     gettimeofday(&t1, NULL);
821     if (pflag) {
822         cnt = do_pwrite(buf, offset, count, &total);
823     } else if (bflag) {
824         cnt = do_save_vmstate(buf, offset, count, &total);
825     } else if (zflag) {
826         cnt = do_co_write_zeroes(offset, count, &total);
827     } else if (cflag) {
828         cnt = do_write_compressed(buf, offset, count, &total);
829     } else {
830         cnt = do_write(buf, offset, count, &total);
831     }
832     gettimeofday(&t2, NULL);
833
834     if (cnt < 0) {
835         printf("write failed: %s\n", strerror(-cnt));
836         goto out;
837     }
838
839     if (qflag) {
840         goto out;
841     }
842
843     /* Finally, report back -- -C gives a parsable format */
844     t2 = tsub(t2, t1);
845     print_report("wrote", &t2, offset, count, total, cnt, Cflag);
846
847 out:
848     if (!zflag) {
849         qemu_io_free(buf);
850     }
851
852     return 0;
853 }
854
855 static void
856 writev_help(void)
857 {
858     printf(
859 "\n"
860 " writes a range of bytes from the given offset source from multiple buffers\n"
861 "\n"
862 " Example:\n"
863 " 'write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
864 "\n"
865 " Writes into a segment of the currently open file, using a buffer\n"
866 " filled with a set pattern (0xcdcdcdcd).\n"
867 " -P, -- use different pattern to fill file\n"
868 " -C, -- report statistics in a machine parsable format\n"
869 " -q, -- quiet mode, do not show I/O statistics\n"
870 "\n");
871 }
872
873 static int writev_f(int argc, char **argv);
874
875 static const cmdinfo_t writev_cmd = {
876     .name       = "writev",
877     .cfunc      = writev_f,
878     .argmin     = 2,
879     .argmax     = -1,
880     .args       = "[-Cq] [-P pattern ] off len [len..]",
881     .oneline    = "writes a number of bytes at a specified offset",
882     .help       = writev_help,
883 };
884
885 static int writev_f(int argc, char **argv)
886 {
887     struct timeval t1, t2;
888     int Cflag = 0, qflag = 0;
889     int c, cnt;
890     char *buf;
891     int64_t offset;
892     /* Some compilers get confused and warn if this is not initialized.  */
893     int total = 0;
894     int nr_iov;
895     int pattern = 0xcd;
896     QEMUIOVector qiov;
897
898     while ((c = getopt(argc, argv, "CqP:")) != EOF) {
899         switch (c) {
900         case 'C':
901             Cflag = 1;
902             break;
903         case 'q':
904             qflag = 1;
905             break;
906         case 'P':
907             pattern = parse_pattern(optarg);
908             if (pattern < 0) {
909                 return 0;
910             }
911             break;
912         default:
913             return command_usage(&writev_cmd);
914         }
915     }
916
917     if (optind > argc - 2) {
918         return command_usage(&writev_cmd);
919     }
920
921     offset = cvtnum(argv[optind]);
922     if (offset < 0) {
923         printf("non-numeric length argument -- %s\n", argv[optind]);
924         return 0;
925     }
926     optind++;
927
928     if (offset & 0x1ff) {
929         printf("offset %" PRId64 " is not sector aligned\n",
930                offset);
931         return 0;
932     }
933
934     nr_iov = argc - optind;
935     buf = create_iovec(&qiov, &argv[optind], nr_iov, pattern);
936     if (buf == NULL) {
937         return 0;
938     }
939
940     gettimeofday(&t1, NULL);
941     cnt = do_aio_writev(&qiov, offset, &total);
942     gettimeofday(&t2, NULL);
943
944     if (cnt < 0) {
945         printf("writev failed: %s\n", strerror(-cnt));
946         goto out;
947     }
948
949     if (qflag) {
950         goto out;
951     }
952
953     /* Finally, report back -- -C gives a parsable format */
954     t2 = tsub(t2, t1);
955     print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);
956 out:
957     qemu_iovec_destroy(&qiov);
958     qemu_io_free(buf);
959     return 0;
960 }
961
962 static void multiwrite_help(void)
963 {
964     printf(
965 "\n"
966 " writes a range of bytes from the given offset source from multiple buffers,\n"
967 " in a batch of requests that may be merged by qemu\n"
968 "\n"
969 " Example:\n"
970 " 'multiwrite 512 1k 1k ; 4k 1k'\n"
971 "  writes 2 kB at 512 bytes and 1 kB at 4 kB into the open file\n"
972 "\n"
973 " Writes into a segment of the currently open file, using a buffer\n"
974 " filled with a set pattern (0xcdcdcdcd). The pattern byte is increased\n"
975 " by one for each request contained in the multiwrite command.\n"
976 " -P, -- use different pattern to fill file\n"
977 " -C, -- report statistics in a machine parsable format\n"
978 " -q, -- quiet mode, do not show I/O statistics\n"
979 "\n");
980 }
981
982 static int multiwrite_f(int argc, char **argv);
983
984 static const cmdinfo_t multiwrite_cmd = {
985     .name       = "multiwrite",
986     .cfunc      = multiwrite_f,
987     .argmin     = 2,
988     .argmax     = -1,
989     .args       = "[-Cq] [-P pattern ] off len [len..] [; off len [len..]..]",
990     .oneline    = "issues multiple write requests at once",
991     .help       = multiwrite_help,
992 };
993
994 static int multiwrite_f(int argc, char **argv)
995 {
996     struct timeval t1, t2;
997     int Cflag = 0, qflag = 0;
998     int c, cnt;
999     char **buf;
1000     int64_t offset, first_offset = 0;
1001     /* Some compilers get confused and warn if this is not initialized.  */
1002     int total = 0;
1003     int nr_iov;
1004     int nr_reqs;
1005     int pattern = 0xcd;
1006     QEMUIOVector *qiovs;
1007     int i;
1008     BlockRequest *reqs;
1009
1010     while ((c = getopt(argc, argv, "CqP:")) != EOF) {
1011         switch (c) {
1012         case 'C':
1013             Cflag = 1;
1014             break;
1015         case 'q':
1016             qflag = 1;
1017             break;
1018         case 'P':
1019             pattern = parse_pattern(optarg);
1020             if (pattern < 0) {
1021                 return 0;
1022             }
1023             break;
1024         default:
1025             return command_usage(&writev_cmd);
1026         }
1027     }
1028
1029     if (optind > argc - 2) {
1030         return command_usage(&writev_cmd);
1031     }
1032
1033     nr_reqs = 1;
1034     for (i = optind; i < argc; i++) {
1035         if (!strcmp(argv[i], ";")) {
1036             nr_reqs++;
1037         }
1038     }
1039
1040     reqs = g_malloc0(nr_reqs * sizeof(*reqs));
1041     buf = g_malloc0(nr_reqs * sizeof(*buf));
1042     qiovs = g_malloc(nr_reqs * sizeof(*qiovs));
1043
1044     for (i = 0; i < nr_reqs && optind < argc; i++) {
1045         int j;
1046
1047         /* Read the offset of the request */
1048         offset = cvtnum(argv[optind]);
1049         if (offset < 0) {
1050             printf("non-numeric offset argument -- %s\n", argv[optind]);
1051             goto out;
1052         }
1053         optind++;
1054
1055         if (offset & 0x1ff) {
1056             printf("offset %lld is not sector aligned\n",
1057                    (long long)offset);
1058             goto out;
1059         }
1060
1061         if (i == 0) {
1062             first_offset = offset;
1063         }
1064
1065         /* Read lengths for qiov entries */
1066         for (j = optind; j < argc; j++) {
1067             if (!strcmp(argv[j], ";")) {
1068                 break;
1069             }
1070         }
1071
1072         nr_iov = j - optind;
1073
1074         /* Build request */
1075         buf[i] = create_iovec(&qiovs[i], &argv[optind], nr_iov, pattern);
1076         if (buf[i] == NULL) {
1077             goto out;
1078         }
1079
1080         reqs[i].qiov = &qiovs[i];
1081         reqs[i].sector = offset >> 9;
1082         reqs[i].nb_sectors = reqs[i].qiov->size >> 9;
1083
1084         optind = j + 1;
1085
1086         pattern++;
1087     }
1088
1089     /* If there were empty requests at the end, ignore them */
1090     nr_reqs = i;
1091
1092     gettimeofday(&t1, NULL);
1093     cnt = do_aio_multiwrite(reqs, nr_reqs, &total);
1094     gettimeofday(&t2, NULL);
1095
1096     if (cnt < 0) {
1097         printf("aio_multiwrite failed: %s\n", strerror(-cnt));
1098         goto out;
1099     }
1100
1101     if (qflag) {
1102         goto out;
1103     }
1104
1105     /* Finally, report back -- -C gives a parsable format */
1106     t2 = tsub(t2, t1);
1107     print_report("wrote", &t2, first_offset, total, total, cnt, Cflag);
1108 out:
1109     for (i = 0; i < nr_reqs; i++) {
1110         qemu_io_free(buf[i]);
1111         if (reqs[i].qiov != NULL) {
1112             qemu_iovec_destroy(&qiovs[i]);
1113         }
1114     }
1115     g_free(buf);
1116     g_free(reqs);
1117     g_free(qiovs);
1118     return 0;
1119 }
1120
1121 struct aio_ctx {
1122     QEMUIOVector qiov;
1123     int64_t offset;
1124     char *buf;
1125     int qflag;
1126     int vflag;
1127     int Cflag;
1128     int Pflag;
1129     int pattern;
1130     struct timeval t1;
1131 };
1132
1133 static void aio_write_done(void *opaque, int ret)
1134 {
1135     struct aio_ctx *ctx = opaque;
1136     struct timeval t2;
1137
1138     gettimeofday(&t2, NULL);
1139
1140
1141     if (ret < 0) {
1142         printf("aio_write failed: %s\n", strerror(-ret));
1143         goto out;
1144     }
1145
1146     if (ctx->qflag) {
1147         goto out;
1148     }
1149
1150     /* Finally, report back -- -C gives a parsable format */
1151     t2 = tsub(t2, ctx->t1);
1152     print_report("wrote", &t2, ctx->offset, ctx->qiov.size,
1153                  ctx->qiov.size, 1, ctx->Cflag);
1154 out:
1155     qemu_io_free(ctx->buf);
1156     qemu_iovec_destroy(&ctx->qiov);
1157     g_free(ctx);
1158 }
1159
1160 static void aio_read_done(void *opaque, int ret)
1161 {
1162     struct aio_ctx *ctx = opaque;
1163     struct timeval t2;
1164
1165     gettimeofday(&t2, NULL);
1166
1167     if (ret < 0) {
1168         printf("readv failed: %s\n", strerror(-ret));
1169         goto out;
1170     }
1171
1172     if (ctx->Pflag) {
1173         void *cmp_buf = g_malloc(ctx->qiov.size);
1174
1175         memset(cmp_buf, ctx->pattern, ctx->qiov.size);
1176         if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {
1177             printf("Pattern verification failed at offset %"
1178                    PRId64 ", %zd bytes\n", ctx->offset, ctx->qiov.size);
1179         }
1180         g_free(cmp_buf);
1181     }
1182
1183     if (ctx->qflag) {
1184         goto out;
1185     }
1186
1187     if (ctx->vflag) {
1188         dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);
1189     }
1190
1191     /* Finally, report back -- -C gives a parsable format */
1192     t2 = tsub(t2, ctx->t1);
1193     print_report("read", &t2, ctx->offset, ctx->qiov.size,
1194                  ctx->qiov.size, 1, ctx->Cflag);
1195 out:
1196     qemu_io_free(ctx->buf);
1197     qemu_iovec_destroy(&ctx->qiov);
1198     g_free(ctx);
1199 }
1200
1201 static void aio_read_help(void)
1202 {
1203     printf(
1204 "\n"
1205 " asynchronously reads a range of bytes from the given offset\n"
1206 "\n"
1207 " Example:\n"
1208 " 'aio_read -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
1209 "\n"
1210 " Reads a segment of the currently open file, optionally dumping it to the\n"
1211 " standard output stream (with -v option) for subsequent inspection.\n"
1212 " The read is performed asynchronously and the aio_flush command must be\n"
1213 " used to ensure all outstanding aio requests have been completed.\n"
1214 " -C, -- report statistics in a machine parsable format\n"
1215 " -P, -- use a pattern to verify read data\n"
1216 " -v, -- dump buffer to standard output\n"
1217 " -q, -- quiet mode, do not show I/O statistics\n"
1218 "\n");
1219 }
1220
1221 static int aio_read_f(int argc, char **argv);
1222
1223 static const cmdinfo_t aio_read_cmd = {
1224     .name       = "aio_read",
1225     .cfunc      = aio_read_f,
1226     .argmin     = 2,
1227     .argmax     = -1,
1228     .args       = "[-Cqv] [-P pattern ] off len [len..]",
1229     .oneline    = "asynchronously reads a number of bytes",
1230     .help       = aio_read_help,
1231 };
1232
1233 static int aio_read_f(int argc, char **argv)
1234 {
1235     int nr_iov, c;
1236     struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
1237
1238     while ((c = getopt(argc, argv, "CP:qv")) != EOF) {
1239         switch (c) {
1240         case 'C':
1241             ctx->Cflag = 1;
1242             break;
1243         case 'P':
1244             ctx->Pflag = 1;
1245             ctx->pattern = parse_pattern(optarg);
1246             if (ctx->pattern < 0) {
1247                 g_free(ctx);
1248                 return 0;
1249             }
1250             break;
1251         case 'q':
1252             ctx->qflag = 1;
1253             break;
1254         case 'v':
1255             ctx->vflag = 1;
1256             break;
1257         default:
1258             g_free(ctx);
1259             return command_usage(&aio_read_cmd);
1260         }
1261     }
1262
1263     if (optind > argc - 2) {
1264         g_free(ctx);
1265         return command_usage(&aio_read_cmd);
1266     }
1267
1268     ctx->offset = cvtnum(argv[optind]);
1269     if (ctx->offset < 0) {
1270         printf("non-numeric length argument -- %s\n", argv[optind]);
1271         g_free(ctx);
1272         return 0;
1273     }
1274     optind++;
1275
1276     if (ctx->offset & 0x1ff) {
1277         printf("offset %" PRId64 " is not sector aligned\n",
1278                ctx->offset);
1279         g_free(ctx);
1280         return 0;
1281     }
1282
1283     nr_iov = argc - optind;
1284     ctx->buf = create_iovec(&ctx->qiov, &argv[optind], nr_iov, 0xab);
1285     if (ctx->buf == NULL) {
1286         g_free(ctx);
1287         return 0;
1288     }
1289
1290     gettimeofday(&ctx->t1, NULL);
1291     bdrv_aio_readv(bs, ctx->offset >> 9, &ctx->qiov,
1292                    ctx->qiov.size >> 9, aio_read_done, ctx);
1293     return 0;
1294 }
1295
1296 static void aio_write_help(void)
1297 {
1298     printf(
1299 "\n"
1300 " asynchronously writes a range of bytes from the given offset source\n"
1301 " from multiple buffers\n"
1302 "\n"
1303 " Example:\n"
1304 " 'aio_write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
1305 "\n"
1306 " Writes into a segment of the currently open file, using a buffer\n"
1307 " filled with a set pattern (0xcdcdcdcd).\n"
1308 " The write is performed asynchronously and the aio_flush command must be\n"
1309 " used to ensure all outstanding aio requests have been completed.\n"
1310 " -P, -- use different pattern to fill file\n"
1311 " -C, -- report statistics in a machine parsable format\n"
1312 " -q, -- quiet mode, do not show I/O statistics\n"
1313 "\n");
1314 }
1315
1316 static int aio_write_f(int argc, char **argv);
1317
1318 static const cmdinfo_t aio_write_cmd = {
1319     .name       = "aio_write",
1320     .cfunc      = aio_write_f,
1321     .argmin     = 2,
1322     .argmax     = -1,
1323     .args       = "[-Cq] [-P pattern ] off len [len..]",
1324     .oneline    = "asynchronously writes a number of bytes",
1325     .help       = aio_write_help,
1326 };
1327
1328 static int aio_write_f(int argc, char **argv)
1329 {
1330     int nr_iov, c;
1331     int pattern = 0xcd;
1332     struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
1333
1334     while ((c = getopt(argc, argv, "CqP:")) != EOF) {
1335         switch (c) {
1336         case 'C':
1337             ctx->Cflag = 1;
1338             break;
1339         case 'q':
1340             ctx->qflag = 1;
1341             break;
1342         case 'P':
1343             pattern = parse_pattern(optarg);
1344             if (pattern < 0) {
1345                 g_free(ctx);
1346                 return 0;
1347             }
1348             break;
1349         default:
1350             g_free(ctx);
1351             return command_usage(&aio_write_cmd);
1352         }
1353     }
1354
1355     if (optind > argc - 2) {
1356         g_free(ctx);
1357         return command_usage(&aio_write_cmd);
1358     }
1359
1360     ctx->offset = cvtnum(argv[optind]);
1361     if (ctx->offset < 0) {
1362         printf("non-numeric length argument -- %s\n", argv[optind]);
1363         g_free(ctx);
1364         return 0;
1365     }
1366     optind++;
1367
1368     if (ctx->offset & 0x1ff) {
1369         printf("offset %" PRId64 " is not sector aligned\n",
1370                ctx->offset);
1371         g_free(ctx);
1372         return 0;
1373     }
1374
1375     nr_iov = argc - optind;
1376     ctx->buf = create_iovec(&ctx->qiov, &argv[optind], nr_iov, pattern);
1377     if (ctx->buf == NULL) {
1378         g_free(ctx);
1379         return 0;
1380     }
1381
1382     gettimeofday(&ctx->t1, NULL);
1383     bdrv_aio_writev(bs, ctx->offset >> 9, &ctx->qiov,
1384                     ctx->qiov.size >> 9, aio_write_done, ctx);
1385     return 0;
1386 }
1387
1388 static int aio_flush_f(int argc, char **argv)
1389 {
1390     bdrv_drain_all();
1391     return 0;
1392 }
1393
1394 static const cmdinfo_t aio_flush_cmd = {
1395     .name       = "aio_flush",
1396     .cfunc      = aio_flush_f,
1397     .oneline    = "completes all outstanding aio requests"
1398 };
1399
1400 static int flush_f(int argc, char **argv)
1401 {
1402     bdrv_flush(bs);
1403     return 0;
1404 }
1405
1406 static const cmdinfo_t flush_cmd = {
1407     .name       = "flush",
1408     .altname    = "f",
1409     .cfunc      = flush_f,
1410     .oneline    = "flush all in-core file state to disk",
1411 };
1412
1413 static int truncate_f(int argc, char **argv)
1414 {
1415     int64_t offset;
1416     int ret;
1417
1418     offset = cvtnum(argv[1]);
1419     if (offset < 0) {
1420         printf("non-numeric truncate argument -- %s\n", argv[1]);
1421         return 0;
1422     }
1423
1424     ret = bdrv_truncate(bs, offset);
1425     if (ret < 0) {
1426         printf("truncate: %s\n", strerror(-ret));
1427         return 0;
1428     }
1429
1430     return 0;
1431 }
1432
1433 static const cmdinfo_t truncate_cmd = {
1434     .name       = "truncate",
1435     .altname    = "t",
1436     .cfunc      = truncate_f,
1437     .argmin     = 1,
1438     .argmax     = 1,
1439     .args       = "off",
1440     .oneline    = "truncates the current file at the given offset",
1441 };
1442
1443 static int length_f(int argc, char **argv)
1444 {
1445     int64_t size;
1446     char s1[64];
1447
1448     size = bdrv_getlength(bs);
1449     if (size < 0) {
1450         printf("getlength: %s\n", strerror(-size));
1451         return 0;
1452     }
1453
1454     cvtstr(size, s1, sizeof(s1));
1455     printf("%s\n", s1);
1456     return 0;
1457 }
1458
1459
1460 static const cmdinfo_t length_cmd = {
1461     .name   = "length",
1462     .altname    = "l",
1463     .cfunc      = length_f,
1464     .oneline    = "gets the length of the current file",
1465 };
1466
1467
1468 static int info_f(int argc, char **argv)
1469 {
1470     BlockDriverInfo bdi;
1471     char s1[64], s2[64];
1472     int ret;
1473
1474     if (bs->drv && bs->drv->format_name) {
1475         printf("format name: %s\n", bs->drv->format_name);
1476     }
1477     if (bs->drv && bs->drv->protocol_name) {
1478         printf("format name: %s\n", bs->drv->protocol_name);
1479     }
1480
1481     ret = bdrv_get_info(bs, &bdi);
1482     if (ret) {
1483         return 0;
1484     }
1485
1486     cvtstr(bdi.cluster_size, s1, sizeof(s1));
1487     cvtstr(bdi.vm_state_offset, s2, sizeof(s2));
1488
1489     printf("cluster size: %s\n", s1);
1490     printf("vm state offset: %s\n", s2);
1491
1492     return 0;
1493 }
1494
1495
1496
1497 static const cmdinfo_t info_cmd = {
1498     .name       = "info",
1499     .altname    = "i",
1500     .cfunc      = info_f,
1501     .oneline    = "prints information about the current file",
1502 };
1503
1504 static void discard_help(void)
1505 {
1506     printf(
1507 "\n"
1508 " discards a range of bytes from the given offset\n"
1509 "\n"
1510 " Example:\n"
1511 " 'discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n"
1512 "\n"
1513 " Discards a segment of the currently open file.\n"
1514 " -C, -- report statistics in a machine parsable format\n"
1515 " -q, -- quiet mode, do not show I/O statistics\n"
1516 "\n");
1517 }
1518
1519 static int discard_f(int argc, char **argv);
1520
1521 static const cmdinfo_t discard_cmd = {
1522     .name       = "discard",
1523     .altname    = "d",
1524     .cfunc      = discard_f,
1525     .argmin     = 2,
1526     .argmax     = -1,
1527     .args       = "[-Cq] off len",
1528     .oneline    = "discards a number of bytes at a specified offset",
1529     .help       = discard_help,
1530 };
1531
1532 static int discard_f(int argc, char **argv)
1533 {
1534     struct timeval t1, t2;
1535     int Cflag = 0, qflag = 0;
1536     int c, ret;
1537     int64_t offset;
1538     int count;
1539
1540     while ((c = getopt(argc, argv, "Cq")) != EOF) {
1541         switch (c) {
1542         case 'C':
1543             Cflag = 1;
1544             break;
1545         case 'q':
1546             qflag = 1;
1547             break;
1548         default:
1549             return command_usage(&discard_cmd);
1550         }
1551     }
1552
1553     if (optind != argc - 2) {
1554         return command_usage(&discard_cmd);
1555     }
1556
1557     offset = cvtnum(argv[optind]);
1558     if (offset < 0) {
1559         printf("non-numeric length argument -- %s\n", argv[optind]);
1560         return 0;
1561     }
1562
1563     optind++;
1564     count = cvtnum(argv[optind]);
1565     if (count < 0) {
1566         printf("non-numeric length argument -- %s\n", argv[optind]);
1567         return 0;
1568     }
1569
1570     gettimeofday(&t1, NULL);
1571     ret = bdrv_discard(bs, offset >> BDRV_SECTOR_BITS,
1572                        count >> BDRV_SECTOR_BITS);
1573     gettimeofday(&t2, NULL);
1574
1575     if (ret < 0) {
1576         printf("discard failed: %s\n", strerror(-ret));
1577         goto out;
1578     }
1579
1580     /* Finally, report back -- -C gives a parsable format */
1581     if (!qflag) {
1582         t2 = tsub(t2, t1);
1583         print_report("discard", &t2, offset, count, count, 1, Cflag);
1584     }
1585
1586 out:
1587     return 0;
1588 }
1589
1590 static int alloc_f(int argc, char **argv)
1591 {
1592     int64_t offset, sector_num;
1593     int nb_sectors, remaining;
1594     char s1[64];
1595     int num, sum_alloc;
1596     int ret;
1597
1598     offset = cvtnum(argv[1]);
1599     if (offset < 0) {
1600         printf("non-numeric offset argument -- %s\n", argv[1]);
1601         return 0;
1602     } else if (offset & 0x1ff) {
1603         printf("offset %" PRId64 " is not sector aligned\n",
1604                offset);
1605         return 0;
1606     }
1607
1608     if (argc == 3) {
1609         nb_sectors = cvtnum(argv[2]);
1610         if (nb_sectors < 0) {
1611             printf("non-numeric length argument -- %s\n", argv[2]);
1612             return 0;
1613         }
1614     } else {
1615         nb_sectors = 1;
1616     }
1617
1618     remaining = nb_sectors;
1619     sum_alloc = 0;
1620     sector_num = offset >> 9;
1621     while (remaining) {
1622         ret = bdrv_is_allocated(bs, sector_num, remaining, &num);
1623         sector_num += num;
1624         remaining -= num;
1625         if (ret) {
1626             sum_alloc += num;
1627         }
1628         if (num == 0) {
1629             nb_sectors -= remaining;
1630             remaining = 0;
1631         }
1632     }
1633
1634     cvtstr(offset, s1, sizeof(s1));
1635
1636     printf("%d/%d sectors allocated at offset %s\n",
1637            sum_alloc, nb_sectors, s1);
1638     return 0;
1639 }
1640
1641 static const cmdinfo_t alloc_cmd = {
1642     .name       = "alloc",
1643     .altname    = "a",
1644     .argmin     = 1,
1645     .argmax     = 2,
1646     .cfunc      = alloc_f,
1647     .args       = "off [sectors]",
1648     .oneline    = "checks if a sector is present in the file",
1649 };
1650
1651
1652 static int map_is_allocated(int64_t sector_num, int64_t nb_sectors, int64_t *pnum)
1653 {
1654     int num, num_checked;
1655     int ret, firstret;
1656
1657     num_checked = MIN(nb_sectors, INT_MAX);
1658     ret = bdrv_is_allocated(bs, sector_num, num_checked, &num);
1659     if (ret < 0) {
1660         return ret;
1661     }
1662
1663     firstret = ret;
1664     *pnum = num;
1665
1666     while (nb_sectors > 0 && ret == firstret) {
1667         sector_num += num;
1668         nb_sectors -= num;
1669
1670         num_checked = MIN(nb_sectors, INT_MAX);
1671         ret = bdrv_is_allocated(bs, sector_num, num_checked, &num);
1672         if (ret == firstret) {
1673             *pnum += num;
1674         } else {
1675             break;
1676         }
1677     }
1678
1679     return firstret;
1680 }
1681
1682 static int map_f(int argc, char **argv)
1683 {
1684     int64_t offset;
1685     int64_t nb_sectors;
1686     char s1[64];
1687     int64_t num;
1688     int ret;
1689     const char *retstr;
1690
1691     offset = 0;
1692     nb_sectors = bs->total_sectors;
1693
1694     do {
1695         ret = map_is_allocated(offset, nb_sectors, &num);
1696         if (ret < 0) {
1697             error_report("Failed to get allocation status: %s", strerror(-ret));
1698             return 0;
1699         }
1700
1701         retstr = ret ? "    allocated" : "not allocated";
1702         cvtstr(offset << 9ULL, s1, sizeof(s1));
1703         printf("[% 24" PRId64 "] % 8" PRId64 "/% 8" PRId64 " sectors %s "
1704                "at offset %s (%d)\n",
1705                offset << 9ULL, num, nb_sectors, retstr, s1, ret);
1706
1707         offset += num;
1708         nb_sectors -= num;
1709     } while (offset < bs->total_sectors);
1710
1711     return 0;
1712 }
1713
1714 static const cmdinfo_t map_cmd = {
1715        .name           = "map",
1716        .argmin         = 0,
1717        .argmax         = 0,
1718        .cfunc          = map_f,
1719        .args           = "",
1720        .oneline        = "prints the allocated areas of a file",
1721 };
1722
1723 static int break_f(int argc, char **argv)
1724 {
1725     int ret;
1726
1727     ret = bdrv_debug_breakpoint(bs, argv[1], argv[2]);
1728     if (ret < 0) {
1729         printf("Could not set breakpoint: %s\n", strerror(-ret));
1730     }
1731
1732     return 0;
1733 }
1734
1735 static const cmdinfo_t break_cmd = {
1736        .name           = "break",
1737        .argmin         = 2,
1738        .argmax         = 2,
1739        .cfunc          = break_f,
1740        .args           = "event tag",
1741        .oneline        = "sets a breakpoint on event and tags the stopped "
1742                          "request as tag",
1743 };
1744
1745 static int resume_f(int argc, char **argv)
1746 {
1747     int ret;
1748
1749     ret = bdrv_debug_resume(bs, argv[1]);
1750     if (ret < 0) {
1751         printf("Could not resume request: %s\n", strerror(-ret));
1752     }
1753
1754     return 0;
1755 }
1756
1757 static const cmdinfo_t resume_cmd = {
1758        .name           = "resume",
1759        .argmin         = 1,
1760        .argmax         = 1,
1761        .cfunc          = resume_f,
1762        .args           = "tag",
1763        .oneline        = "resumes the request tagged as tag",
1764 };
1765
1766 static int wait_break_f(int argc, char **argv)
1767 {
1768     while (!bdrv_debug_is_suspended(bs, argv[1])) {
1769         qemu_aio_wait();
1770     }
1771
1772     return 0;
1773 }
1774
1775 static const cmdinfo_t wait_break_cmd = {
1776        .name           = "wait_break",
1777        .argmin         = 1,
1778        .argmax         = 1,
1779        .cfunc          = wait_break_f,
1780        .args           = "tag",
1781        .oneline        = "waits for the suspension of a request",
1782 };
1783
1784 static int abort_f(int argc, char **argv)
1785 {
1786     abort();
1787 }
1788
1789 static const cmdinfo_t abort_cmd = {
1790        .name           = "abort",
1791        .cfunc          = abort_f,
1792        .flags          = CMD_NOFILE_OK,
1793        .oneline        = "simulate a program crash using abort(3)",
1794 };
1795
1796 static int close_f(int argc, char **argv)
1797 {
1798     bdrv_delete(bs);
1799     bs = NULL;
1800     return 0;
1801 }
1802
1803 static const cmdinfo_t close_cmd = {
1804     .name       = "close",
1805     .altname    = "c",
1806     .cfunc      = close_f,
1807     .oneline    = "close the current open file",
1808 };
1809
1810 static int openfile(char *name, int flags, int growable)
1811 {
1812     if (bs) {
1813         fprintf(stderr, "file open already, try 'help close'\n");
1814         return 1;
1815     }
1816
1817     if (growable) {
1818         if (bdrv_file_open(&bs, name, NULL, flags)) {
1819             fprintf(stderr, "%s: can't open device %s\n", progname, name);
1820             return 1;
1821         }
1822     } else {
1823         bs = bdrv_new("hda");
1824
1825         if (bdrv_open(bs, name, NULL, flags, NULL) < 0) {
1826             fprintf(stderr, "%s: can't open device %s\n", progname, name);
1827             bdrv_delete(bs);
1828             bs = NULL;
1829             return 1;
1830         }
1831     }
1832
1833     return 0;
1834 }
1835
1836 static void open_help(void)
1837 {
1838     printf(
1839 "\n"
1840 " opens a new file in the requested mode\n"
1841 "\n"
1842 " Example:\n"
1843 " 'open -Cn /tmp/data' - creates/opens data file read-write and uncached\n"
1844 "\n"
1845 " Opens a file for subsequent use by all of the other qemu-io commands.\n"
1846 " -r, -- open file read-only\n"
1847 " -s, -- use snapshot file\n"
1848 " -n, -- disable host cache\n"
1849 " -g, -- allow file to grow (only applies to protocols)"
1850 "\n");
1851 }
1852
1853 static int open_f(int argc, char **argv);
1854
1855 static const cmdinfo_t open_cmd = {
1856     .name       = "open",
1857     .altname    = "o",
1858     .cfunc      = open_f,
1859     .argmin     = 1,
1860     .argmax     = -1,
1861     .flags      = CMD_NOFILE_OK,
1862     .args       = "[-Crsn] [path]",
1863     .oneline    = "open the file specified by path",
1864     .help       = open_help,
1865 };
1866
1867 static int open_f(int argc, char **argv)
1868 {
1869     int flags = 0;
1870     int readonly = 0;
1871     int growable = 0;
1872     int c;
1873
1874     while ((c = getopt(argc, argv, "snrg")) != EOF) {
1875         switch (c) {
1876         case 's':
1877             flags |= BDRV_O_SNAPSHOT;
1878             break;
1879         case 'n':
1880             flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
1881             break;
1882         case 'r':
1883             readonly = 1;
1884             break;
1885         case 'g':
1886             growable = 1;
1887             break;
1888         default:
1889             return command_usage(&open_cmd);
1890         }
1891     }
1892
1893     if (!readonly) {
1894         flags |= BDRV_O_RDWR;
1895     }
1896
1897     if (optind != argc - 1) {
1898         return command_usage(&open_cmd);
1899     }
1900
1901     return openfile(argv[optind], flags, growable);
1902 }
1903
1904 static int init_check_command(const cmdinfo_t *ct)
1905 {
1906     if (ct->flags & CMD_FLAG_GLOBAL) {
1907         return 1;
1908     }
1909     if (!(ct->flags & CMD_NOFILE_OK) && !bs) {
1910         fprintf(stderr, "no file open, try 'help open'\n");
1911         return 0;
1912     }
1913     return 1;
1914 }
1915
1916 static void usage(const char *name)
1917 {
1918     printf(
1919 "Usage: %s [-h] [-V] [-rsnm] [-c cmd] ... [file]\n"
1920 "QEMU Disk exerciser\n"
1921 "\n"
1922 "  -c, --cmd            command to execute\n"
1923 "  -r, --read-only      export read-only\n"
1924 "  -s, --snapshot       use snapshot file\n"
1925 "  -n, --nocache        disable host cache\n"
1926 "  -g, --growable       allow file to grow (only applies to protocols)\n"
1927 "  -m, --misalign       misalign allocations for O_DIRECT\n"
1928 "  -k, --native-aio     use kernel AIO implementation (on Linux only)\n"
1929 "  -t, --cache=MODE     use the given cache mode for the image\n"
1930 "  -T, --trace FILE     enable trace events listed in the given file\n"
1931 "  -h, --help           display this help and exit\n"
1932 "  -V, --version        output version information and exit\n"
1933 "\n",
1934     name);
1935 }
1936
1937
1938 int main(int argc, char **argv)
1939 {
1940     int readonly = 0;
1941     int growable = 0;
1942     const char *sopt = "hVc:d:rsnmgkt:T:";
1943     const struct option lopt[] = {
1944         { "help", 0, NULL, 'h' },
1945         { "version", 0, NULL, 'V' },
1946         { "offset", 1, NULL, 'o' },
1947         { "cmd", 1, NULL, 'c' },
1948         { "read-only", 0, NULL, 'r' },
1949         { "snapshot", 0, NULL, 's' },
1950         { "nocache", 0, NULL, 'n' },
1951         { "misalign", 0, NULL, 'm' },
1952         { "growable", 0, NULL, 'g' },
1953         { "native-aio", 0, NULL, 'k' },
1954         { "discard", 1, NULL, 'd' },
1955         { "cache", 1, NULL, 't' },
1956         { "trace", 1, NULL, 'T' },
1957         { NULL, 0, NULL, 0 }
1958     };
1959     int c;
1960     int opt_index = 0;
1961     int flags = BDRV_O_UNMAP;
1962
1963     progname = basename(argv[0]);
1964
1965     while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
1966         switch (c) {
1967         case 's':
1968             flags |= BDRV_O_SNAPSHOT;
1969             break;
1970         case 'n':
1971             flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
1972             break;
1973         case 'd':
1974             if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
1975                 error_report("Invalid discard option: %s", optarg);
1976                 exit(1);
1977             }
1978             break;
1979         case 'c':
1980             add_user_command(optarg);
1981             break;
1982         case 'r':
1983             readonly = 1;
1984             break;
1985         case 'm':
1986             misalign = 1;
1987             break;
1988         case 'g':
1989             growable = 1;
1990             break;
1991         case 'k':
1992             flags |= BDRV_O_NATIVE_AIO;
1993             break;
1994         case 't':
1995             if (bdrv_parse_cache_flags(optarg, &flags) < 0) {
1996                 error_report("Invalid cache option: %s", optarg);
1997                 exit(1);
1998             }
1999             break;
2000         case 'T':
2001             if (!trace_backend_init(optarg, NULL)) {
2002                 exit(1); /* error message will have been printed */
2003             }
2004             break;
2005         case 'V':
2006             printf("%s version %s\n", progname, VERSION);
2007             exit(0);
2008         case 'h':
2009             usage(progname);
2010             exit(0);
2011         default:
2012             usage(progname);
2013             exit(1);
2014         }
2015     }
2016
2017     if ((argc - optind) > 1) {
2018         usage(progname);
2019         exit(1);
2020     }
2021
2022     qemu_init_main_loop();
2023     bdrv_init();
2024
2025     /* initialize commands */
2026     quit_init();
2027     help_init();
2028     add_command(&open_cmd);
2029     add_command(&close_cmd);
2030     add_command(&read_cmd);
2031     add_command(&readv_cmd);
2032     add_command(&write_cmd);
2033     add_command(&writev_cmd);
2034     add_command(&multiwrite_cmd);
2035     add_command(&aio_read_cmd);
2036     add_command(&aio_write_cmd);
2037     add_command(&aio_flush_cmd);
2038     add_command(&flush_cmd);
2039     add_command(&truncate_cmd);
2040     add_command(&length_cmd);
2041     add_command(&info_cmd);
2042     add_command(&discard_cmd);
2043     add_command(&alloc_cmd);
2044     add_command(&map_cmd);
2045     add_command(&break_cmd);
2046     add_command(&resume_cmd);
2047     add_command(&wait_break_cmd);
2048     add_command(&abort_cmd);
2049
2050     add_check_command(init_check_command);
2051
2052     /* open the device */
2053     if (!readonly) {
2054         flags |= BDRV_O_RDWR;
2055     }
2056
2057     if ((argc - optind) == 1) {
2058         openfile(argv[optind], flags, growable);
2059     }
2060     command_loop();
2061
2062     /*
2063      * Make sure all outstanding requests complete before the program exits.
2064      */
2065     bdrv_drain_all();
2066
2067     if (bs) {
2068         bdrv_delete(bs);
2069     }
2070     return 0;
2071 }
This page took 0.13726 seconds and 4 git commands to generate.