Statistics
| Branch: | Revision:

root / qemu-img.c @ f67503e5

History | View | Annotate | Download (78.5 kB)

1
/*
2
 * QEMU disk image utility
3
 *
4
 * Copyright (c) 2003-2008 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "qapi-visit.h"
25
#include "qapi/qmp-output-visitor.h"
26
#include "qapi/qmp/qjson.h"
27
#include "qemu-common.h"
28
#include "qemu/option.h"
29
#include "qemu/error-report.h"
30
#include "qemu/osdep.h"
31
#include "sysemu/sysemu.h"
32
#include "block/block_int.h"
33
#include "block/qapi.h"
34
#include <getopt.h>
35
#include <stdio.h>
36
#include <stdarg.h>
37

    
38
#ifdef _WIN32
39
#include <windows.h>
40
#endif
41

    
42
typedef struct img_cmd_t {
43
    const char *name;
44
    int (*handler)(int argc, char **argv);
45
} img_cmd_t;
46

    
47
enum {
48
    OPTION_OUTPUT = 256,
49
    OPTION_BACKING_CHAIN = 257,
50
};
51

    
52
typedef enum OutputFormat {
53
    OFORMAT_JSON,
54
    OFORMAT_HUMAN,
55
} OutputFormat;
56

    
57
/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
58
#define BDRV_O_FLAGS BDRV_O_CACHE_WB
59
#define BDRV_DEFAULT_CACHE "writeback"
60

    
61
static void format_print(void *opaque, const char *name)
62
{
63
    printf(" %s", name);
64
}
65

    
66
/* Please keep in synch with qemu-img.texi */
67
static void help(void)
68
{
69
    const char *help_msg =
70
           "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
71
           "usage: qemu-img command [command options]\n"
72
           "QEMU disk image utility\n"
73
           "\n"
74
           "Command syntax:\n"
75
#define DEF(option, callback, arg_string)        \
76
           "  " arg_string "\n"
77
#include "qemu-img-cmds.h"
78
#undef DEF
79
#undef GEN_DOCS
80
           "\n"
81
           "Command parameters:\n"
82
           "  'filename' is a disk image filename\n"
83
           "  'fmt' is the disk image format. It is guessed automatically in most cases\n"
84
           "  'cache' is the cache mode used to write the output disk image, the valid\n"
85
           "    options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
86
           "    'directsync' and 'unsafe' (default for convert)\n"
87
           "  'size' is the disk image size in bytes. Optional suffixes\n"
88
           "    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
89
           "    'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P)  are\n"
90
           "    supported. 'b' is ignored.\n"
91
           "  'output_filename' is the destination disk image filename\n"
92
           "  'output_fmt' is the destination format\n"
93
           "  'options' is a comma separated list of format specific options in a\n"
94
           "    name=value format. Use -o ? for an overview of the options supported by the\n"
95
           "    used format\n"
96
           "  'snapshot_param' is param used for internal snapshot, format\n"
97
           "    is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
98
           "    '[ID_OR_NAME]'\n"
99
           "  'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
100
           "    instead\n"
101
           "  '-c' indicates that target image must be compressed (qcow format only)\n"
102
           "  '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
103
           "       match exactly. The image doesn't need a working backing file before\n"
104
           "       rebasing in this case (useful for renaming the backing file)\n"
105
           "  '-h' with or without a command shows this help and lists the supported formats\n"
106
           "  '-p' show progress of command (only certain commands)\n"
107
           "  '-q' use Quiet mode - do not print any output (except errors)\n"
108
           "  '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
109
           "       contain only zeros for qemu-img to create a sparse image during\n"
110
           "       conversion. If the number of bytes is 0, the source will not be scanned for\n"
111
           "       unallocated or zero sectors, and the destination image will always be\n"
112
           "       fully allocated\n"
113
           "  '--output' takes the format in which the output must be done (human or json)\n"
114
           "  '-n' skips the target volume creation (useful if the volume is created\n"
115
           "       prior to running qemu-img)\n"
116
           "\n"
117
           "Parameters to check subcommand:\n"
118
           "  '-r' tries to repair any inconsistencies that are found during the check.\n"
119
           "       '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
120
           "       kinds of errors, with a higher risk of choosing the wrong fix or\n"
121
           "       hiding corruption that has already occurred.\n"
122
           "\n"
123
           "Parameters to snapshot subcommand:\n"
124
           "  'snapshot' is the name of the snapshot to create, apply or delete\n"
125
           "  '-a' applies a snapshot (revert disk to saved state)\n"
126
           "  '-c' creates a snapshot\n"
127
           "  '-d' deletes a snapshot\n"
128
           "  '-l' lists all snapshots in the given image\n"
129
           "\n"
130
           "Parameters to compare subcommand:\n"
131
           "  '-f' first image format\n"
132
           "  '-F' second image format\n"
133
           "  '-s' run in Strict mode - fail on different image size or sector allocation\n";
134

    
135
    printf("%s\nSupported formats:", help_msg);
136
    bdrv_iterate_format(format_print, NULL);
137
    printf("\n");
138
    exit(1);
139
}
140

    
141
static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
142
{
143
    int ret = 0;
144
    if (!quiet) {
145
        va_list args;
146
        va_start(args, fmt);
147
        ret = vprintf(fmt, args);
148
        va_end(args);
149
    }
150
    return ret;
151
}
152

    
153
#if defined(WIN32)
154
/* XXX: put correct support for win32 */
155
static int read_password(char *buf, int buf_size)
156
{
157
    int c, i;
158
    printf("Password: ");
159
    fflush(stdout);
160
    i = 0;
161
    for(;;) {
162
        c = getchar();
163
        if (c == '\n')
164
            break;
165
        if (i < (buf_size - 1))
166
            buf[i++] = c;
167
    }
168
    buf[i] = '\0';
169
    return 0;
170
}
171

    
172
#else
173

    
174
#include <termios.h>
175

    
176
static struct termios oldtty;
177

    
178
static void term_exit(void)
179
{
180
    tcsetattr (0, TCSANOW, &oldtty);
181
}
182

    
183
static void term_init(void)
184
{
185
    struct termios tty;
186

    
187
    tcgetattr (0, &tty);
188
    oldtty = tty;
189

    
190
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
191
                          |INLCR|IGNCR|ICRNL|IXON);
192
    tty.c_oflag |= OPOST;
193
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
194
    tty.c_cflag &= ~(CSIZE|PARENB);
195
    tty.c_cflag |= CS8;
196
    tty.c_cc[VMIN] = 1;
197
    tty.c_cc[VTIME] = 0;
198

    
199
    tcsetattr (0, TCSANOW, &tty);
200

    
201
    atexit(term_exit);
202
}
203

    
204
static int read_password(char *buf, int buf_size)
205
{
206
    uint8_t ch;
207
    int i, ret;
208

    
209
    printf("password: ");
210
    fflush(stdout);
211
    term_init();
212
    i = 0;
213
    for(;;) {
214
        ret = read(0, &ch, 1);
215
        if (ret == -1) {
216
            if (errno == EAGAIN || errno == EINTR) {
217
                continue;
218
            } else {
219
                ret = -1;
220
                break;
221
            }
222
        } else if (ret == 0) {
223
            ret = -1;
224
            break;
225
        } else {
226
            if (ch == '\r') {
227
                ret = 0;
228
                break;
229
            }
230
            if (i < (buf_size - 1))
231
                buf[i++] = ch;
232
        }
233
    }
234
    term_exit();
235
    buf[i] = '\0';
236
    printf("\n");
237
    return ret;
238
}
239
#endif
240

    
241
static int print_block_option_help(const char *filename, const char *fmt)
242
{
243
    BlockDriver *drv, *proto_drv;
244
    QEMUOptionParameter *create_options = NULL;
245

    
246
    /* Find driver and parse its options */
247
    drv = bdrv_find_format(fmt);
248
    if (!drv) {
249
        error_report("Unknown file format '%s'", fmt);
250
        return 1;
251
    }
252

    
253
    proto_drv = bdrv_find_protocol(filename, true);
254
    if (!proto_drv) {
255
        error_report("Unknown protocol '%s'", filename);
256
        return 1;
257
    }
258

    
259
    create_options = append_option_parameters(create_options,
260
                                              drv->create_options);
261
    create_options = append_option_parameters(create_options,
262
                                              proto_drv->create_options);
263
    print_option_help(create_options);
264
    free_option_parameters(create_options);
265
    return 0;
266
}
267

    
268
static BlockDriverState *bdrv_new_open(const char *filename,
269
                                       const char *fmt,
270
                                       int flags,
271
                                       bool require_io,
272
                                       bool quiet)
273
{
274
    BlockDriverState *bs;
275
    BlockDriver *drv;
276
    char password[256];
277
    Error *local_err = NULL;
278
    int ret;
279

    
280
    bs = bdrv_new("image");
281

    
282
    if (fmt) {
283
        drv = bdrv_find_format(fmt);
284
        if (!drv) {
285
            error_report("Unknown file format '%s'", fmt);
286
            goto fail;
287
        }
288
    } else {
289
        drv = NULL;
290
    }
291

    
292
    ret = bdrv_open(&bs, filename, NULL, flags, drv, &local_err);
293
    if (ret < 0) {
294
        error_report("Could not open '%s': %s", filename,
295
                     error_get_pretty(local_err));
296
        error_free(local_err);
297
        goto fail;
298
    }
299

    
300
    if (bdrv_is_encrypted(bs) && require_io) {
301
        qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
302
        if (read_password(password, sizeof(password)) < 0) {
303
            error_report("No password given");
304
            goto fail;
305
        }
306
        if (bdrv_set_key(bs, password) < 0) {
307
            error_report("invalid password");
308
            goto fail;
309
        }
310
    }
311
    return bs;
312
fail:
313
    bdrv_unref(bs);
314
    return NULL;
315
}
316

    
317
static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
318
                                 const char *base_filename,
319
                                 const char *base_fmt)
320
{
321
    if (base_filename) {
322
        if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
323
            error_report("Backing file not supported for file format '%s'",
324
                         fmt);
325
            return -1;
326
        }
327
    }
328
    if (base_fmt) {
329
        if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
330
            error_report("Backing file format not supported for file "
331
                         "format '%s'", fmt);
332
            return -1;
333
        }
334
    }
335
    return 0;
336
}
337

    
338
static int img_create(int argc, char **argv)
339
{
340
    int c;
341
    uint64_t img_size = -1;
342
    const char *fmt = "raw";
343
    const char *base_fmt = NULL;
344
    const char *filename;
345
    const char *base_filename = NULL;
346
    char *options = NULL;
347
    Error *local_err = NULL;
348
    bool quiet = false;
349

    
350
    for(;;) {
351
        c = getopt(argc, argv, "F:b:f:he6o:q");
352
        if (c == -1) {
353
            break;
354
        }
355
        switch(c) {
356
        case '?':
357
        case 'h':
358
            help();
359
            break;
360
        case 'F':
361
            base_fmt = optarg;
362
            break;
363
        case 'b':
364
            base_filename = optarg;
365
            break;
366
        case 'f':
367
            fmt = optarg;
368
            break;
369
        case 'e':
370
            error_report("option -e is deprecated, please use \'-o "
371
                  "encryption\' instead!");
372
            return 1;
373
        case '6':
374
            error_report("option -6 is deprecated, please use \'-o "
375
                  "compat6\' instead!");
376
            return 1;
377
        case 'o':
378
            options = optarg;
379
            break;
380
        case 'q':
381
            quiet = true;
382
            break;
383
        }
384
    }
385

    
386
    /* Get the filename */
387
    if (optind >= argc) {
388
        help();
389
    }
390
    filename = argv[optind++];
391

    
392
    /* Get image size, if specified */
393
    if (optind < argc) {
394
        int64_t sval;
395
        char *end;
396
        sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
397
        if (sval < 0 || *end) {
398
            if (sval == -ERANGE) {
399
                error_report("Image size must be less than 8 EiB!");
400
            } else {
401
                error_report("Invalid image size specified! You may use k, M, "
402
                      "G, T, P or E suffixes for ");
403
                error_report("kilobytes, megabytes, gigabytes, terabytes, "
404
                             "petabytes and exabytes.");
405
            }
406
            return 1;
407
        }
408
        img_size = (uint64_t)sval;
409
    }
410
    if (optind != argc) {
411
        help();
412
    }
413

    
414
    if (options && is_help_option(options)) {
415
        return print_block_option_help(filename, fmt);
416
    }
417

    
418
    bdrv_img_create(filename, fmt, base_filename, base_fmt,
419
                    options, img_size, BDRV_O_FLAGS, &local_err, quiet);
420
    if (local_err) {
421
        error_report("%s: %s", filename, error_get_pretty(local_err));
422
        error_free(local_err);
423
        return 1;
424
    }
425

    
426
    return 0;
427
}
428

    
429
static void dump_json_image_check(ImageCheck *check, bool quiet)
430
{
431
    Error *errp = NULL;
432
    QString *str;
433
    QmpOutputVisitor *ov = qmp_output_visitor_new();
434
    QObject *obj;
435
    visit_type_ImageCheck(qmp_output_get_visitor(ov),
436
                          &check, NULL, &errp);
437
    obj = qmp_output_get_qobject(ov);
438
    str = qobject_to_json_pretty(obj);
439
    assert(str != NULL);
440
    qprintf(quiet, "%s\n", qstring_get_str(str));
441
    qobject_decref(obj);
442
    qmp_output_visitor_cleanup(ov);
443
    QDECREF(str);
444
}
445

    
446
static void dump_human_image_check(ImageCheck *check, bool quiet)
447
{
448
    if (!(check->corruptions || check->leaks || check->check_errors)) {
449
        qprintf(quiet, "No errors were found on the image.\n");
450
    } else {
451
        if (check->corruptions) {
452
            qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
453
                    "Data may be corrupted, or further writes to the image "
454
                    "may corrupt it.\n",
455
                    check->corruptions);
456
        }
457

    
458
        if (check->leaks) {
459
            qprintf(quiet,
460
                    "\n%" PRId64 " leaked clusters were found on the image.\n"
461
                    "This means waste of disk space, but no harm to data.\n",
462
                    check->leaks);
463
        }
464

    
465
        if (check->check_errors) {
466
            qprintf(quiet,
467
                    "\n%" PRId64
468
                    " internal errors have occurred during the check.\n",
469
                    check->check_errors);
470
        }
471
    }
472

    
473
    if (check->total_clusters != 0 && check->allocated_clusters != 0) {
474
        qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
475
                "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
476
                check->allocated_clusters, check->total_clusters,
477
                check->allocated_clusters * 100.0 / check->total_clusters,
478
                check->fragmented_clusters * 100.0 / check->allocated_clusters,
479
                check->compressed_clusters * 100.0 /
480
                check->allocated_clusters);
481
    }
482

    
483
    if (check->image_end_offset) {
484
        qprintf(quiet,
485
                "Image end offset: %" PRId64 "\n", check->image_end_offset);
486
    }
487
}
488

    
489
static int collect_image_check(BlockDriverState *bs,
490
                   ImageCheck *check,
491
                   const char *filename,
492
                   const char *fmt,
493
                   int fix)
494
{
495
    int ret;
496
    BdrvCheckResult result;
497

    
498
    ret = bdrv_check(bs, &result, fix);
499
    if (ret < 0) {
500
        return ret;
501
    }
502

    
503
    check->filename                 = g_strdup(filename);
504
    check->format                   = g_strdup(bdrv_get_format_name(bs));
505
    check->check_errors             = result.check_errors;
506
    check->corruptions              = result.corruptions;
507
    check->has_corruptions          = result.corruptions != 0;
508
    check->leaks                    = result.leaks;
509
    check->has_leaks                = result.leaks != 0;
510
    check->corruptions_fixed        = result.corruptions_fixed;
511
    check->has_corruptions_fixed    = result.corruptions != 0;
512
    check->leaks_fixed              = result.leaks_fixed;
513
    check->has_leaks_fixed          = result.leaks != 0;
514
    check->image_end_offset         = result.image_end_offset;
515
    check->has_image_end_offset     = result.image_end_offset != 0;
516
    check->total_clusters           = result.bfi.total_clusters;
517
    check->has_total_clusters       = result.bfi.total_clusters != 0;
518
    check->allocated_clusters       = result.bfi.allocated_clusters;
519
    check->has_allocated_clusters   = result.bfi.allocated_clusters != 0;
520
    check->fragmented_clusters      = result.bfi.fragmented_clusters;
521
    check->has_fragmented_clusters  = result.bfi.fragmented_clusters != 0;
522
    check->compressed_clusters      = result.bfi.compressed_clusters;
523
    check->has_compressed_clusters  = result.bfi.compressed_clusters != 0;
524

    
525
    return 0;
526
}
527

    
528
/*
529
 * Checks an image for consistency. Exit codes:
530
 *
531
 * 0 - Check completed, image is good
532
 * 1 - Check not completed because of internal errors
533
 * 2 - Check completed, image is corrupted
534
 * 3 - Check completed, image has leaked clusters, but is good otherwise
535
 */
536
static int img_check(int argc, char **argv)
537
{
538
    int c, ret;
539
    OutputFormat output_format = OFORMAT_HUMAN;
540
    const char *filename, *fmt, *output;
541
    BlockDriverState *bs;
542
    int fix = 0;
543
    int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
544
    ImageCheck *check;
545
    bool quiet = false;
546

    
547
    fmt = NULL;
548
    output = NULL;
549
    for(;;) {
550
        int option_index = 0;
551
        static const struct option long_options[] = {
552
            {"help", no_argument, 0, 'h'},
553
            {"format", required_argument, 0, 'f'},
554
            {"repair", no_argument, 0, 'r'},
555
            {"output", required_argument, 0, OPTION_OUTPUT},
556
            {0, 0, 0, 0}
557
        };
558
        c = getopt_long(argc, argv, "f:hr:q",
559
                        long_options, &option_index);
560
        if (c == -1) {
561
            break;
562
        }
563
        switch(c) {
564
        case '?':
565
        case 'h':
566
            help();
567
            break;
568
        case 'f':
569
            fmt = optarg;
570
            break;
571
        case 'r':
572
            flags |= BDRV_O_RDWR;
573

    
574
            if (!strcmp(optarg, "leaks")) {
575
                fix = BDRV_FIX_LEAKS;
576
            } else if (!strcmp(optarg, "all")) {
577
                fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
578
            } else {
579
                help();
580
            }
581
            break;
582
        case OPTION_OUTPUT:
583
            output = optarg;
584
            break;
585
        case 'q':
586
            quiet = true;
587
            break;
588
        }
589
    }
590
    if (optind != argc - 1) {
591
        help();
592
    }
593
    filename = argv[optind++];
594

    
595
    if (output && !strcmp(output, "json")) {
596
        output_format = OFORMAT_JSON;
597
    } else if (output && !strcmp(output, "human")) {
598
        output_format = OFORMAT_HUMAN;
599
    } else if (output) {
600
        error_report("--output must be used with human or json as argument.");
601
        return 1;
602
    }
603

    
604
    bs = bdrv_new_open(filename, fmt, flags, true, quiet);
605
    if (!bs) {
606
        return 1;
607
    }
608

    
609
    check = g_new0(ImageCheck, 1);
610
    ret = collect_image_check(bs, check, filename, fmt, fix);
611

    
612
    if (ret == -ENOTSUP) {
613
        if (output_format == OFORMAT_HUMAN) {
614
            error_report("This image format does not support checks");
615
        }
616
        ret = 63;
617
        goto fail;
618
    }
619

    
620
    if (check->corruptions_fixed || check->leaks_fixed) {
621
        int corruptions_fixed, leaks_fixed;
622

    
623
        leaks_fixed         = check->leaks_fixed;
624
        corruptions_fixed   = check->corruptions_fixed;
625

    
626
        if (output_format == OFORMAT_HUMAN) {
627
            qprintf(quiet,
628
                    "The following inconsistencies were found and repaired:\n\n"
629
                    "    %" PRId64 " leaked clusters\n"
630
                    "    %" PRId64 " corruptions\n\n"
631
                    "Double checking the fixed image now...\n",
632
                    check->leaks_fixed,
633
                    check->corruptions_fixed);
634
        }
635

    
636
        ret = collect_image_check(bs, check, filename, fmt, 0);
637

    
638
        check->leaks_fixed          = leaks_fixed;
639
        check->corruptions_fixed    = corruptions_fixed;
640
    }
641

    
642
    switch (output_format) {
643
    case OFORMAT_HUMAN:
644
        dump_human_image_check(check, quiet);
645
        break;
646
    case OFORMAT_JSON:
647
        dump_json_image_check(check, quiet);
648
        break;
649
    }
650

    
651
    if (ret || check->check_errors) {
652
        ret = 1;
653
        goto fail;
654
    }
655

    
656
    if (check->corruptions) {
657
        ret = 2;
658
    } else if (check->leaks) {
659
        ret = 3;
660
    } else {
661
        ret = 0;
662
    }
663

    
664
fail:
665
    qapi_free_ImageCheck(check);
666
    bdrv_unref(bs);
667

    
668
    return ret;
669
}
670

    
671
static int img_commit(int argc, char **argv)
672
{
673
    int c, ret, flags;
674
    const char *filename, *fmt, *cache;
675
    BlockDriverState *bs;
676
    bool quiet = false;
677

    
678
    fmt = NULL;
679
    cache = BDRV_DEFAULT_CACHE;
680
    for(;;) {
681
        c = getopt(argc, argv, "f:ht:q");
682
        if (c == -1) {
683
            break;
684
        }
685
        switch(c) {
686
        case '?':
687
        case 'h':
688
            help();
689
            break;
690
        case 'f':
691
            fmt = optarg;
692
            break;
693
        case 't':
694
            cache = optarg;
695
            break;
696
        case 'q':
697
            quiet = true;
698
            break;
699
        }
700
    }
701
    if (optind != argc - 1) {
702
        help();
703
    }
704
    filename = argv[optind++];
705

    
706
    flags = BDRV_O_RDWR;
707
    ret = bdrv_parse_cache_flags(cache, &flags);
708
    if (ret < 0) {
709
        error_report("Invalid cache option: %s", cache);
710
        return -1;
711
    }
712

    
713
    bs = bdrv_new_open(filename, fmt, flags, true, quiet);
714
    if (!bs) {
715
        return 1;
716
    }
717
    ret = bdrv_commit(bs);
718
    switch(ret) {
719
    case 0:
720
        qprintf(quiet, "Image committed.\n");
721
        break;
722
    case -ENOENT:
723
        error_report("No disk inserted");
724
        break;
725
    case -EACCES:
726
        error_report("Image is read-only");
727
        break;
728
    case -ENOTSUP:
729
        error_report("Image is already committed");
730
        break;
731
    default:
732
        error_report("Error while committing image");
733
        break;
734
    }
735

    
736
    bdrv_unref(bs);
737
    if (ret) {
738
        return 1;
739
    }
740
    return 0;
741
}
742

    
743
/*
744
 * Returns true iff the first sector pointed to by 'buf' contains at least
745
 * a non-NUL byte.
746
 *
747
 * 'pnum' is set to the number of sectors (including and immediately following
748
 * the first one) that are known to be in the same allocated/unallocated state.
749
 */
750
static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
751
{
752
    bool is_zero;
753
    int i;
754

    
755
    if (n <= 0) {
756
        *pnum = 0;
757
        return 0;
758
    }
759
    is_zero = buffer_is_zero(buf, 512);
760
    for(i = 1; i < n; i++) {
761
        buf += 512;
762
        if (is_zero != buffer_is_zero(buf, 512)) {
763
            break;
764
        }
765
    }
766
    *pnum = i;
767
    return !is_zero;
768
}
769

    
770
/*
771
 * Like is_allocated_sectors, but if the buffer starts with a used sector,
772
 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
773
 * breaking up write requests for only small sparse areas.
774
 */
775
static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
776
    int min)
777
{
778
    int ret;
779
    int num_checked, num_used;
780

    
781
    if (n < min) {
782
        min = n;
783
    }
784

    
785
    ret = is_allocated_sectors(buf, n, pnum);
786
    if (!ret) {
787
        return ret;
788
    }
789

    
790
    num_used = *pnum;
791
    buf += BDRV_SECTOR_SIZE * *pnum;
792
    n -= *pnum;
793
    num_checked = num_used;
794

    
795
    while (n > 0) {
796
        ret = is_allocated_sectors(buf, n, pnum);
797

    
798
        buf += BDRV_SECTOR_SIZE * *pnum;
799
        n -= *pnum;
800
        num_checked += *pnum;
801
        if (ret) {
802
            num_used = num_checked;
803
        } else if (*pnum >= min) {
804
            break;
805
        }
806
    }
807

    
808
    *pnum = num_used;
809
    return 1;
810
}
811

    
812
/*
813
 * Compares two buffers sector by sector. Returns 0 if the first sector of both
814
 * buffers matches, non-zero otherwise.
815
 *
816
 * pnum is set to the number of sectors (including and immediately following
817
 * the first one) that are known to have the same comparison result
818
 */
819
static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
820
    int *pnum)
821
{
822
    int res, i;
823

    
824
    if (n <= 0) {
825
        *pnum = 0;
826
        return 0;
827
    }
828

    
829
    res = !!memcmp(buf1, buf2, 512);
830
    for(i = 1; i < n; i++) {
831
        buf1 += 512;
832
        buf2 += 512;
833

    
834
        if (!!memcmp(buf1, buf2, 512) != res) {
835
            break;
836
        }
837
    }
838

    
839
    *pnum = i;
840
    return res;
841
}
842

    
843
#define IO_BUF_SIZE (2 * 1024 * 1024)
844

    
845
static int64_t sectors_to_bytes(int64_t sectors)
846
{
847
    return sectors << BDRV_SECTOR_BITS;
848
}
849

    
850
static int64_t sectors_to_process(int64_t total, int64_t from)
851
{
852
    return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
853
}
854

    
855
/*
856
 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
857
 *
858
 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
859
 * data and negative value on error.
860
 *
861
 * @param bs:  Driver used for accessing file
862
 * @param sect_num: Number of first sector to check
863
 * @param sect_count: Number of sectors to check
864
 * @param filename: Name of disk file we are checking (logging purpose)
865
 * @param buffer: Allocated buffer for storing read data
866
 * @param quiet: Flag for quiet mode
867
 */
868
static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
869
                               int sect_count, const char *filename,
870
                               uint8_t *buffer, bool quiet)
871
{
872
    int pnum, ret = 0;
873
    ret = bdrv_read(bs, sect_num, buffer, sect_count);
874
    if (ret < 0) {
875
        error_report("Error while reading offset %" PRId64 " of %s: %s",
876
                     sectors_to_bytes(sect_num), filename, strerror(-ret));
877
        return ret;
878
    }
879
    ret = is_allocated_sectors(buffer, sect_count, &pnum);
880
    if (ret || pnum != sect_count) {
881
        qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
882
                sectors_to_bytes(ret ? sect_num : sect_num + pnum));
883
        return 1;
884
    }
885

    
886
    return 0;
887
}
888

    
889
/*
890
 * Compares two images. Exit codes:
891
 *
892
 * 0 - Images are identical
893
 * 1 - Images differ
894
 * >1 - Error occurred
895
 */
896
static int img_compare(int argc, char **argv)
897
{
898
    const char *fmt1 = NULL, *fmt2 = NULL, *filename1, *filename2;
899
    BlockDriverState *bs1, *bs2;
900
    int64_t total_sectors1, total_sectors2;
901
    uint8_t *buf1 = NULL, *buf2 = NULL;
902
    int pnum1, pnum2;
903
    int allocated1, allocated2;
904
    int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
905
    bool progress = false, quiet = false, strict = false;
906
    int64_t total_sectors;
907
    int64_t sector_num = 0;
908
    int64_t nb_sectors;
909
    int c, pnum;
910
    uint64_t bs_sectors;
911
    uint64_t progress_base;
912

    
913
    for (;;) {
914
        c = getopt(argc, argv, "hpf:F:sq");
915
        if (c == -1) {
916
            break;
917
        }
918
        switch (c) {
919
        case '?':
920
        case 'h':
921
            help();
922
            break;
923
        case 'f':
924
            fmt1 = optarg;
925
            break;
926
        case 'F':
927
            fmt2 = optarg;
928
            break;
929
        case 'p':
930
            progress = true;
931
            break;
932
        case 'q':
933
            quiet = true;
934
            break;
935
        case 's':
936
            strict = true;
937
            break;
938
        }
939
    }
940

    
941
    /* Progress is not shown in Quiet mode */
942
    if (quiet) {
943
        progress = false;
944
    }
945

    
946

    
947
    if (optind != argc - 2) {
948
        help();
949
    }
950
    filename1 = argv[optind++];
951
    filename2 = argv[optind++];
952

    
953
    /* Initialize before goto out */
954
    qemu_progress_init(progress, 2.0);
955

    
956
    bs1 = bdrv_new_open(filename1, fmt1, BDRV_O_FLAGS, true, quiet);
957
    if (!bs1) {
958
        error_report("Can't open file %s", filename1);
959
        ret = 2;
960
        goto out3;
961
    }
962

    
963
    bs2 = bdrv_new_open(filename2, fmt2, BDRV_O_FLAGS, true, quiet);
964
    if (!bs2) {
965
        error_report("Can't open file %s", filename2);
966
        ret = 2;
967
        goto out2;
968
    }
969

    
970
    buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
971
    buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
972
    bdrv_get_geometry(bs1, &bs_sectors);
973
    total_sectors1 = bs_sectors;
974
    bdrv_get_geometry(bs2, &bs_sectors);
975
    total_sectors2 = bs_sectors;
976
    total_sectors = MIN(total_sectors1, total_sectors2);
977
    progress_base = MAX(total_sectors1, total_sectors2);
978

    
979
    qemu_progress_print(0, 100);
980

    
981
    if (strict && total_sectors1 != total_sectors2) {
982
        ret = 1;
983
        qprintf(quiet, "Strict mode: Image size mismatch!\n");
984
        goto out;
985
    }
986

    
987
    for (;;) {
988
        nb_sectors = sectors_to_process(total_sectors, sector_num);
989
        if (nb_sectors <= 0) {
990
            break;
991
        }
992
        allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
993
                                             &pnum1);
994
        if (allocated1 < 0) {
995
            ret = 3;
996
            error_report("Sector allocation test failed for %s", filename1);
997
            goto out;
998
        }
999

    
1000
        allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1001
                                             &pnum2);
1002
        if (allocated2 < 0) {
1003
            ret = 3;
1004
            error_report("Sector allocation test failed for %s", filename2);
1005
            goto out;
1006
        }
1007
        nb_sectors = MIN(pnum1, pnum2);
1008

    
1009
        if (allocated1 == allocated2) {
1010
            if (allocated1) {
1011
                ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1012
                if (ret < 0) {
1013
                    error_report("Error while reading offset %" PRId64 " of %s:"
1014
                                 " %s", sectors_to_bytes(sector_num), filename1,
1015
                                 strerror(-ret));
1016
                    ret = 4;
1017
                    goto out;
1018
                }
1019
                ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1020
                if (ret < 0) {
1021
                    error_report("Error while reading offset %" PRId64
1022
                                 " of %s: %s", sectors_to_bytes(sector_num),
1023
                                 filename2, strerror(-ret));
1024
                    ret = 4;
1025
                    goto out;
1026
                }
1027
                ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1028
                if (ret || pnum != nb_sectors) {
1029
                    qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1030
                            sectors_to_bytes(
1031
                                ret ? sector_num : sector_num + pnum));
1032
                    ret = 1;
1033
                    goto out;
1034
                }
1035
            }
1036
        } else {
1037
            if (strict) {
1038
                ret = 1;
1039
                qprintf(quiet, "Strict mode: Offset %" PRId64
1040
                        " allocation mismatch!\n",
1041
                        sectors_to_bytes(sector_num));
1042
                goto out;
1043
            }
1044

    
1045
            if (allocated1) {
1046
                ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1047
                                          filename1, buf1, quiet);
1048
            } else {
1049
                ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1050
                                          filename2, buf1, quiet);
1051
            }
1052
            if (ret) {
1053
                if (ret < 0) {
1054
                    error_report("Error while reading offset %" PRId64 ": %s",
1055
                                 sectors_to_bytes(sector_num), strerror(-ret));
1056
                    ret = 4;
1057
                }
1058
                goto out;
1059
            }
1060
        }
1061
        sector_num += nb_sectors;
1062
        qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1063
    }
1064

    
1065
    if (total_sectors1 != total_sectors2) {
1066
        BlockDriverState *bs_over;
1067
        int64_t total_sectors_over;
1068
        const char *filename_over;
1069

    
1070
        qprintf(quiet, "Warning: Image size mismatch!\n");
1071
        if (total_sectors1 > total_sectors2) {
1072
            total_sectors_over = total_sectors1;
1073
            bs_over = bs1;
1074
            filename_over = filename1;
1075
        } else {
1076
            total_sectors_over = total_sectors2;
1077
            bs_over = bs2;
1078
            filename_over = filename2;
1079
        }
1080

    
1081
        for (;;) {
1082
            nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1083
            if (nb_sectors <= 0) {
1084
                break;
1085
            }
1086
            ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1087
                                          nb_sectors, &pnum);
1088
            if (ret < 0) {
1089
                ret = 3;
1090
                error_report("Sector allocation test failed for %s",
1091
                             filename_over);
1092
                goto out;
1093

    
1094
            }
1095
            nb_sectors = pnum;
1096
            if (ret) {
1097
                ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1098
                                          filename_over, buf1, quiet);
1099
                if (ret) {
1100
                    if (ret < 0) {
1101
                        error_report("Error while reading offset %" PRId64
1102
                                     " of %s: %s", sectors_to_bytes(sector_num),
1103
                                     filename_over, strerror(-ret));
1104
                        ret = 4;
1105
                    }
1106
                    goto out;
1107
                }
1108
            }
1109
            sector_num += nb_sectors;
1110
            qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1111
        }
1112
    }
1113

    
1114
    qprintf(quiet, "Images are identical.\n");
1115
    ret = 0;
1116

    
1117
out:
1118
    bdrv_unref(bs2);
1119
    qemu_vfree(buf1);
1120
    qemu_vfree(buf2);
1121
out2:
1122
    bdrv_unref(bs1);
1123
out3:
1124
    qemu_progress_end();
1125
    return ret;
1126
}
1127

    
1128
static int img_convert(int argc, char **argv)
1129
{
1130
    int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
1131
    int64_t ret = 0;
1132
    int progress = 0, flags;
1133
    const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
1134
    BlockDriver *drv, *proto_drv;
1135
    BlockDriverState **bs = NULL, *out_bs = NULL;
1136
    int64_t total_sectors, nb_sectors, sector_num, bs_offset;
1137
    uint64_t bs_sectors;
1138
    uint8_t * buf = NULL;
1139
    size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1140
    const uint8_t *buf1;
1141
    BlockDriverInfo bdi;
1142
    QEMUOptionParameter *param = NULL, *create_options = NULL;
1143
    QEMUOptionParameter *out_baseimg_param;
1144
    char *options = NULL;
1145
    const char *snapshot_name = NULL;
1146
    int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1147
    bool quiet = false;
1148
    Error *local_err = NULL;
1149
    QemuOpts *sn_opts = NULL;
1150

    
1151
    fmt = NULL;
1152
    out_fmt = "raw";
1153
    cache = "unsafe";
1154
    out_baseimg = NULL;
1155
    compress = 0;
1156
    skip_create = 0;
1157
    for(;;) {
1158
        c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:qnl:");
1159
        if (c == -1) {
1160
            break;
1161
        }
1162
        switch(c) {
1163
        case '?':
1164
        case 'h':
1165
            help();
1166
            break;
1167
        case 'f':
1168
            fmt = optarg;
1169
            break;
1170
        case 'O':
1171
            out_fmt = optarg;
1172
            break;
1173
        case 'B':
1174
            out_baseimg = optarg;
1175
            break;
1176
        case 'c':
1177
            compress = 1;
1178
            break;
1179
        case 'e':
1180
            error_report("option -e is deprecated, please use \'-o "
1181
                  "encryption\' instead!");
1182
            return 1;
1183
        case '6':
1184
            error_report("option -6 is deprecated, please use \'-o "
1185
                  "compat6\' instead!");
1186
            return 1;
1187
        case 'o':
1188
            options = optarg;
1189
            break;
1190
        case 's':
1191
            snapshot_name = optarg;
1192
            break;
1193
        case 'l':
1194
            if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1195
                sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1196
                if (!sn_opts) {
1197
                    error_report("Failed in parsing snapshot param '%s'",
1198
                                 optarg);
1199
                    return 1;
1200
                }
1201
            } else {
1202
                snapshot_name = optarg;
1203
            }
1204
            break;
1205
        case 'S':
1206
        {
1207
            int64_t sval;
1208
            char *end;
1209
            sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1210
            if (sval < 0 || *end) {
1211
                error_report("Invalid minimum zero buffer size for sparse output specified");
1212
                return 1;
1213
            }
1214

    
1215
            min_sparse = sval / BDRV_SECTOR_SIZE;
1216
            break;
1217
        }
1218
        case 'p':
1219
            progress = 1;
1220
            break;
1221
        case 't':
1222
            cache = optarg;
1223
            break;
1224
        case 'q':
1225
            quiet = true;
1226
            break;
1227
        case 'n':
1228
            skip_create = 1;
1229
            break;
1230
        }
1231
    }
1232

    
1233
    if (quiet) {
1234
        progress = 0;
1235
    }
1236

    
1237
    bs_n = argc - optind - 1;
1238
    if (bs_n < 1) {
1239
        help();
1240
    }
1241

    
1242
    out_filename = argv[argc - 1];
1243

    
1244
    /* Initialize before goto out */
1245
    qemu_progress_init(progress, 1.0);
1246

    
1247
    if (options && is_help_option(options)) {
1248
        ret = print_block_option_help(out_filename, out_fmt);
1249
        goto out;
1250
    }
1251

    
1252
    if (bs_n > 1 && out_baseimg) {
1253
        error_report("-B makes no sense when concatenating multiple input "
1254
                     "images");
1255
        ret = -1;
1256
        goto out;
1257
    }
1258

    
1259
    qemu_progress_print(0, 100);
1260

    
1261
    bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
1262

    
1263
    total_sectors = 0;
1264
    for (bs_i = 0; bs_i < bs_n; bs_i++) {
1265
        bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
1266
                                 quiet);
1267
        if (!bs[bs_i]) {
1268
            error_report("Could not open '%s'", argv[optind + bs_i]);
1269
            ret = -1;
1270
            goto out;
1271
        }
1272
        bdrv_get_geometry(bs[bs_i], &bs_sectors);
1273
        total_sectors += bs_sectors;
1274
    }
1275

    
1276
    if (sn_opts) {
1277
        ret = bdrv_snapshot_load_tmp(bs[0],
1278
                                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1279
                                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1280
                                     &local_err);
1281
    } else if (snapshot_name != NULL) {
1282
        if (bs_n > 1) {
1283
            error_report("No support for concatenating multiple snapshot");
1284
            ret = -1;
1285
            goto out;
1286
        }
1287

    
1288
        bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1289
    }
1290
    if (local_err) {
1291
        error_report("Failed to load snapshot: %s",
1292
                     error_get_pretty(local_err));
1293
        error_free(local_err);
1294
        ret = -1;
1295
        goto out;
1296
    }
1297

    
1298
    /* Find driver and parse its options */
1299
    drv = bdrv_find_format(out_fmt);
1300
    if (!drv) {
1301
        error_report("Unknown file format '%s'", out_fmt);
1302
        ret = -1;
1303
        goto out;
1304
    }
1305

    
1306
    proto_drv = bdrv_find_protocol(out_filename, true);
1307
    if (!proto_drv) {
1308
        error_report("Unknown protocol '%s'", out_filename);
1309
        ret = -1;
1310
        goto out;
1311
    }
1312

    
1313
    create_options = append_option_parameters(create_options,
1314
                                              drv->create_options);
1315
    create_options = append_option_parameters(create_options,
1316
                                              proto_drv->create_options);
1317

    
1318
    if (options) {
1319
        param = parse_option_parameters(options, create_options, param);
1320
        if (param == NULL) {
1321
            error_report("Invalid options for file format '%s'.", out_fmt);
1322
            ret = -1;
1323
            goto out;
1324
        }
1325
    } else {
1326
        param = parse_option_parameters("", create_options, param);
1327
    }
1328

    
1329
    set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
1330
    ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
1331
    if (ret < 0) {
1332
        goto out;
1333
    }
1334

    
1335
    /* Get backing file name if -o backing_file was used */
1336
    out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
1337
    if (out_baseimg_param) {
1338
        out_baseimg = out_baseimg_param->value.s;
1339
    }
1340

    
1341
    /* Check if compression is supported */
1342
    if (compress) {
1343
        QEMUOptionParameter *encryption =
1344
            get_option_parameter(param, BLOCK_OPT_ENCRYPT);
1345
        QEMUOptionParameter *preallocation =
1346
            get_option_parameter(param, BLOCK_OPT_PREALLOC);
1347

    
1348
        if (!drv->bdrv_write_compressed) {
1349
            error_report("Compression not supported for this file format");
1350
            ret = -1;
1351
            goto out;
1352
        }
1353

    
1354
        if (encryption && encryption->value.n) {
1355
            error_report("Compression and encryption not supported at "
1356
                         "the same time");
1357
            ret = -1;
1358
            goto out;
1359
        }
1360

    
1361
        if (preallocation && preallocation->value.s
1362
            && strcmp(preallocation->value.s, "off"))
1363
        {
1364
            error_report("Compression and preallocation not supported at "
1365
                         "the same time");
1366
            ret = -1;
1367
            goto out;
1368
        }
1369
    }
1370

    
1371
    if (!skip_create) {
1372
        /* Create the new image */
1373
        ret = bdrv_create(drv, out_filename, param, &local_err);
1374
        if (ret < 0) {
1375
            error_report("%s: error while converting %s: %s",
1376
                         out_filename, out_fmt, error_get_pretty(local_err));
1377
            error_free(local_err);
1378
            goto out;
1379
        }
1380
    }
1381

    
1382
    flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
1383
    ret = bdrv_parse_cache_flags(cache, &flags);
1384
    if (ret < 0) {
1385
        error_report("Invalid cache option: %s", cache);
1386
        return -1;
1387
    }
1388

    
1389
    out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
1390
    if (!out_bs) {
1391
        ret = -1;
1392
        goto out;
1393
    }
1394

    
1395
    bs_i = 0;
1396
    bs_offset = 0;
1397
    bdrv_get_geometry(bs[0], &bs_sectors);
1398

    
1399
    /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1400
     * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1401
     * as maximum. */
1402
    bufsectors = MIN(32768,
1403
                     MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1404
                                         out_bs->bl.discard_alignment))
1405
                    );
1406

    
1407
    buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
1408

    
1409
    if (skip_create) {
1410
        int64_t output_length = bdrv_getlength(out_bs);
1411
        if (output_length < 0) {
1412
            error_report("unable to get output image length: %s\n",
1413
                         strerror(-output_length));
1414
            ret = -1;
1415
            goto out;
1416
        } else if (output_length < total_sectors << BDRV_SECTOR_BITS) {
1417
            error_report("output file is smaller than input file");
1418
            ret = -1;
1419
            goto out;
1420
        }
1421
    }
1422

    
1423
    cluster_sectors = 0;
1424
    ret = bdrv_get_info(out_bs, &bdi);
1425
    if (ret < 0) {
1426
        if (compress) {
1427
            error_report("could not get block driver info");
1428
            goto out;
1429
        }
1430
    } else {
1431
        cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1432
    }
1433

    
1434
    if (compress) {
1435
        if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
1436
            error_report("invalid cluster size");
1437
            ret = -1;
1438
            goto out;
1439
        }
1440
        sector_num = 0;
1441

    
1442
        nb_sectors = total_sectors;
1443

    
1444
        for(;;) {
1445
            int64_t bs_num;
1446
            int remainder;
1447
            uint8_t *buf2;
1448

    
1449
            nb_sectors = total_sectors - sector_num;
1450
            if (nb_sectors <= 0)
1451
                break;
1452
            if (nb_sectors >= cluster_sectors)
1453
                n = cluster_sectors;
1454
            else
1455
                n = nb_sectors;
1456

    
1457
            bs_num = sector_num - bs_offset;
1458
            assert (bs_num >= 0);
1459
            remainder = n;
1460
            buf2 = buf;
1461
            while (remainder > 0) {
1462
                int nlow;
1463
                while (bs_num == bs_sectors) {
1464
                    bs_i++;
1465
                    assert (bs_i < bs_n);
1466
                    bs_offset += bs_sectors;
1467
                    bdrv_get_geometry(bs[bs_i], &bs_sectors);
1468
                    bs_num = 0;
1469
                    /* printf("changing part: sector_num=%" PRId64 ", "
1470
                       "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1471
                       "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1472
                }
1473
                assert (bs_num < bs_sectors);
1474

    
1475
                nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1476

    
1477
                ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1478
                if (ret < 0) {
1479
                    error_report("error while reading sector %" PRId64 ": %s",
1480
                                 bs_num, strerror(-ret));
1481
                    goto out;
1482
                }
1483

    
1484
                buf2 += nlow * 512;
1485
                bs_num += nlow;
1486

    
1487
                remainder -= nlow;
1488
            }
1489
            assert (remainder == 0);
1490

    
1491
            if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1492
                ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
1493
                if (ret != 0) {
1494
                    error_report("error while compressing sector %" PRId64
1495
                                 ": %s", sector_num, strerror(-ret));
1496
                    goto out;
1497
                }
1498
            }
1499
            sector_num += n;
1500
            qemu_progress_print(100.0 * sector_num / total_sectors, 0);
1501
        }
1502
        /* signal EOF to align */
1503
        bdrv_write_compressed(out_bs, 0, NULL, 0);
1504
    } else {
1505
        int64_t sectors_to_read, sectors_read, sector_num_next_status;
1506
        bool count_allocated_sectors;
1507
        int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
1508

    
1509
        if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1510
            ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1511
            if (ret < 0) {
1512
                goto out;
1513
            }
1514
            has_zero_init = 1;
1515
        }
1516

    
1517
        sectors_to_read = total_sectors;
1518
        count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1519
restart:
1520
        sector_num = 0; // total number of sectors converted so far
1521
        sectors_read = 0;
1522
        sector_num_next_status = 0;
1523

    
1524
        for(;;) {
1525
            nb_sectors = total_sectors - sector_num;
1526
            if (nb_sectors <= 0) {
1527
                if (count_allocated_sectors) {
1528
                    sectors_to_read = sectors_read;
1529
                    count_allocated_sectors = false;
1530
                    goto restart;
1531
                }
1532
                ret = 0;
1533
                break;
1534
            }
1535

    
1536
            while (sector_num - bs_offset >= bs_sectors) {
1537
                bs_i ++;
1538
                assert (bs_i < bs_n);
1539
                bs_offset += bs_sectors;
1540
                bdrv_get_geometry(bs[bs_i], &bs_sectors);
1541
                /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1542
                  "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1543
                   sector_num, bs_i, bs_offset, bs_sectors); */
1544
            }
1545

    
1546
            if ((out_baseimg || has_zero_init) &&
1547
                sector_num >= sector_num_next_status) {
1548
                n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1549
                ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1550
                                            n, &n1);
1551
                if (ret < 0) {
1552
                    error_report("error while reading block status of sector %"
1553
                                 PRId64 ": %s", sector_num - bs_offset,
1554
                                 strerror(-ret));
1555
                    goto out;
1556
                }
1557
                /* If the output image is zero initialized, we are not working
1558
                 * on a shared base and the input is zero we can skip the next
1559
                 * n1 sectors */
1560
                if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
1561
                    sector_num += n1;
1562
                    continue;
1563
                }
1564
                /* If the output image is being created as a copy on write
1565
                 * image, assume that sectors which are unallocated in the
1566
                 * input image are present in both the output's and input's
1567
                 * base images (no need to copy them). */
1568
                if (out_baseimg) {
1569
                    if (!(ret & BDRV_BLOCK_DATA)) {
1570
                        sector_num += n1;
1571
                        continue;
1572
                    }
1573
                    /* The next 'n1' sectors are allocated in the input image.
1574
                     * Copy only those as they may be followed by unallocated
1575
                     * sectors. */
1576
                    nb_sectors = n1;
1577
                }
1578
                /* avoid redundant callouts to get_block_status */
1579
                sector_num_next_status = sector_num + n1;
1580
            }
1581

    
1582
            n = MIN(nb_sectors, bufsectors);
1583

    
1584
            /* round down request length to an aligned sector, but
1585
             * do not bother doing this on short requests. They happen
1586
             * when we found an all-zero area, and the next sector to
1587
             * write will not be sector_num + n. */
1588
            if (cluster_sectors > 0 && n >= cluster_sectors) {
1589
                int64_t next_aligned_sector = (sector_num + n);
1590
                next_aligned_sector -= next_aligned_sector % cluster_sectors;
1591
                if (sector_num + n > next_aligned_sector) {
1592
                    n = next_aligned_sector - sector_num;
1593
                }
1594
            }
1595

    
1596
            n = MIN(n, bs_sectors - (sector_num - bs_offset));
1597

    
1598
            sectors_read += n;
1599
            if (count_allocated_sectors) {
1600
                sector_num += n;
1601
                continue;
1602
            }
1603

    
1604
            n1 = n;
1605
            ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1606
            if (ret < 0) {
1607
                error_report("error while reading sector %" PRId64 ": %s",
1608
                             sector_num - bs_offset, strerror(-ret));
1609
                goto out;
1610
            }
1611
            /* NOTE: at the same time we convert, we do not write zero
1612
               sectors to have a chance to compress the image. Ideally, we
1613
               should add a specific call to have the info to go faster */
1614
            buf1 = buf;
1615
            while (n > 0) {
1616
                if (!has_zero_init ||
1617
                    is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
1618
                    ret = bdrv_write(out_bs, sector_num, buf1, n1);
1619
                    if (ret < 0) {
1620
                        error_report("error while writing sector %" PRId64
1621
                                     ": %s", sector_num, strerror(-ret));
1622
                        goto out;
1623
                    }
1624
                }
1625
                sector_num += n1;
1626
                n -= n1;
1627
                buf1 += n1 * 512;
1628
            }
1629
            qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
1630
        }
1631
    }
1632
out:
1633
    if (!ret) {
1634
        qemu_progress_print(100, 0);
1635
    }
1636
    qemu_progress_end();
1637
    free_option_parameters(create_options);
1638
    free_option_parameters(param);
1639
    qemu_vfree(buf);
1640
    if (sn_opts) {
1641
        qemu_opts_del(sn_opts);
1642
    }
1643
    if (out_bs) {
1644
        bdrv_unref(out_bs);
1645
    }
1646
    if (bs) {
1647
        for (bs_i = 0; bs_i < bs_n; bs_i++) {
1648
            if (bs[bs_i]) {
1649
                bdrv_unref(bs[bs_i]);
1650
            }
1651
        }
1652
        g_free(bs);
1653
    }
1654
    if (ret) {
1655
        return 1;
1656
    }
1657
    return 0;
1658
}
1659

    
1660

    
1661
static void dump_snapshots(BlockDriverState *bs)
1662
{
1663
    QEMUSnapshotInfo *sn_tab, *sn;
1664
    int nb_sns, i;
1665

    
1666
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1667
    if (nb_sns <= 0)
1668
        return;
1669
    printf("Snapshot list:\n");
1670
    bdrv_snapshot_dump(fprintf, stdout, NULL);
1671
    printf("\n");
1672
    for(i = 0; i < nb_sns; i++) {
1673
        sn = &sn_tab[i];
1674
        bdrv_snapshot_dump(fprintf, stdout, sn);
1675
        printf("\n");
1676
    }
1677
    g_free(sn_tab);
1678
}
1679

    
1680
static void dump_json_image_info_list(ImageInfoList *list)
1681
{
1682
    Error *errp = NULL;
1683
    QString *str;
1684
    QmpOutputVisitor *ov = qmp_output_visitor_new();
1685
    QObject *obj;
1686
    visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1687
                             &list, NULL, &errp);
1688
    obj = qmp_output_get_qobject(ov);
1689
    str = qobject_to_json_pretty(obj);
1690
    assert(str != NULL);
1691
    printf("%s\n", qstring_get_str(str));
1692
    qobject_decref(obj);
1693
    qmp_output_visitor_cleanup(ov);
1694
    QDECREF(str);
1695
}
1696

    
1697
static void dump_json_image_info(ImageInfo *info)
1698
{
1699
    Error *errp = NULL;
1700
    QString *str;
1701
    QmpOutputVisitor *ov = qmp_output_visitor_new();
1702
    QObject *obj;
1703
    visit_type_ImageInfo(qmp_output_get_visitor(ov),
1704
                         &info, NULL, &errp);
1705
    obj = qmp_output_get_qobject(ov);
1706
    str = qobject_to_json_pretty(obj);
1707
    assert(str != NULL);
1708
    printf("%s\n", qstring_get_str(str));
1709
    qobject_decref(obj);
1710
    qmp_output_visitor_cleanup(ov);
1711
    QDECREF(str);
1712
}
1713

    
1714
static void dump_human_image_info_list(ImageInfoList *list)
1715
{
1716
    ImageInfoList *elem;
1717
    bool delim = false;
1718

    
1719
    for (elem = list; elem; elem = elem->next) {
1720
        if (delim) {
1721
            printf("\n");
1722
        }
1723
        delim = true;
1724

    
1725
        bdrv_image_info_dump(fprintf, stdout, elem->value);
1726
    }
1727
}
1728

    
1729
static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1730
{
1731
    return strcmp(a, b) == 0;
1732
}
1733

    
1734
/**
1735
 * Open an image file chain and return an ImageInfoList
1736
 *
1737
 * @filename: topmost image filename
1738
 * @fmt: topmost image format (may be NULL to autodetect)
1739
 * @chain: true  - enumerate entire backing file chain
1740
 *         false - only topmost image file
1741
 *
1742
 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1743
 * image file.  If there was an error a message will have been printed to
1744
 * stderr.
1745
 */
1746
static ImageInfoList *collect_image_info_list(const char *filename,
1747
                                              const char *fmt,
1748
                                              bool chain)
1749
{
1750
    ImageInfoList *head = NULL;
1751
    ImageInfoList **last = &head;
1752
    GHashTable *filenames;
1753
    Error *err = NULL;
1754

    
1755
    filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1756

    
1757
    while (filename) {
1758
        BlockDriverState *bs;
1759
        ImageInfo *info;
1760
        ImageInfoList *elem;
1761

    
1762
        if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1763
            error_report("Backing file '%s' creates an infinite loop.",
1764
                         filename);
1765
            goto err;
1766
        }
1767
        g_hash_table_insert(filenames, (gpointer)filename, NULL);
1768

    
1769
        bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
1770
                           false, false);
1771
        if (!bs) {
1772
            goto err;
1773
        }
1774

    
1775
        bdrv_query_image_info(bs, &info, &err);
1776
        if (err) {
1777
            error_report("%s", error_get_pretty(err));
1778
            error_free(err);
1779
            goto err;
1780
        }
1781

    
1782
        elem = g_new0(ImageInfoList, 1);
1783
        elem->value = info;
1784
        *last = elem;
1785
        last = &elem->next;
1786

    
1787
        bdrv_unref(bs);
1788

    
1789
        filename = fmt = NULL;
1790
        if (chain) {
1791
            if (info->has_full_backing_filename) {
1792
                filename = info->full_backing_filename;
1793
            } else if (info->has_backing_filename) {
1794
                filename = info->backing_filename;
1795
            }
1796
            if (info->has_backing_filename_format) {
1797
                fmt = info->backing_filename_format;
1798
            }
1799
        }
1800
    }
1801
    g_hash_table_destroy(filenames);
1802
    return head;
1803

    
1804
err:
1805
    qapi_free_ImageInfoList(head);
1806
    g_hash_table_destroy(filenames);
1807
    return NULL;
1808
}
1809

    
1810
static int img_info(int argc, char **argv)
1811
{
1812
    int c;
1813
    OutputFormat output_format = OFORMAT_HUMAN;
1814
    bool chain = false;
1815
    const char *filename, *fmt, *output;
1816
    ImageInfoList *list;
1817

    
1818
    fmt = NULL;
1819
    output = NULL;
1820
    for(;;) {
1821
        int option_index = 0;
1822
        static const struct option long_options[] = {
1823
            {"help", no_argument, 0, 'h'},
1824
            {"format", required_argument, 0, 'f'},
1825
            {"output", required_argument, 0, OPTION_OUTPUT},
1826
            {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
1827
            {0, 0, 0, 0}
1828
        };
1829
        c = getopt_long(argc, argv, "f:h",
1830
                        long_options, &option_index);
1831
        if (c == -1) {
1832
            break;
1833
        }
1834
        switch(c) {
1835
        case '?':
1836
        case 'h':
1837
            help();
1838
            break;
1839
        case 'f':
1840
            fmt = optarg;
1841
            break;
1842
        case OPTION_OUTPUT:
1843
            output = optarg;
1844
            break;
1845
        case OPTION_BACKING_CHAIN:
1846
            chain = true;
1847
            break;
1848
        }
1849
    }
1850
    if (optind != argc - 1) {
1851
        help();
1852
    }
1853
    filename = argv[optind++];
1854

    
1855
    if (output && !strcmp(output, "json")) {
1856
        output_format = OFORMAT_JSON;
1857
    } else if (output && !strcmp(output, "human")) {
1858
        output_format = OFORMAT_HUMAN;
1859
    } else if (output) {
1860
        error_report("--output must be used with human or json as argument.");
1861
        return 1;
1862
    }
1863

    
1864
    list = collect_image_info_list(filename, fmt, chain);
1865
    if (!list) {
1866
        return 1;
1867
    }
1868

    
1869
    switch (output_format) {
1870
    case OFORMAT_HUMAN:
1871
        dump_human_image_info_list(list);
1872
        break;
1873
    case OFORMAT_JSON:
1874
        if (chain) {
1875
            dump_json_image_info_list(list);
1876
        } else {
1877
            dump_json_image_info(list->value);
1878
        }
1879
        break;
1880
    }
1881

    
1882
    qapi_free_ImageInfoList(list);
1883
    return 0;
1884
}
1885

    
1886

    
1887
typedef struct MapEntry {
1888
    int flags;
1889
    int depth;
1890
    int64_t start;
1891
    int64_t length;
1892
    int64_t offset;
1893
    BlockDriverState *bs;
1894
} MapEntry;
1895

    
1896
static void dump_map_entry(OutputFormat output_format, MapEntry *e,
1897
                           MapEntry *next)
1898
{
1899
    switch (output_format) {
1900
    case OFORMAT_HUMAN:
1901
        if ((e->flags & BDRV_BLOCK_DATA) &&
1902
            !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
1903
            error_report("File contains external, encrypted or compressed clusters.");
1904
            exit(1);
1905
        }
1906
        if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
1907
            printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
1908
                   e->start, e->length, e->offset, e->bs->filename);
1909
        }
1910
        /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
1911
         * Modify the flags here to allow more coalescing.
1912
         */
1913
        if (next &&
1914
            (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
1915
            next->flags &= ~BDRV_BLOCK_DATA;
1916
            next->flags |= BDRV_BLOCK_ZERO;
1917
        }
1918
        break;
1919
    case OFORMAT_JSON:
1920
        printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
1921
               " \"zero\": %s, \"data\": %s",
1922
               (e->start == 0 ? "[" : ",\n"),
1923
               e->start, e->length, e->depth,
1924
               (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
1925
               (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
1926
        if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
1927
            printf(", \"offset\": %"PRId64"", e->offset);
1928
        }
1929
        putchar('}');
1930

    
1931
        if (!next) {
1932
            printf("]\n");
1933
        }
1934
        break;
1935
    }
1936
}
1937

    
1938
static int get_block_status(BlockDriverState *bs, int64_t sector_num,
1939
                            int nb_sectors, MapEntry *e)
1940
{
1941
    int64_t ret;
1942
    int depth;
1943

    
1944
    /* As an optimization, we could cache the current range of unallocated
1945
     * clusters in each file of the chain, and avoid querying the same
1946
     * range repeatedly.
1947
     */
1948

    
1949
    depth = 0;
1950
    for (;;) {
1951
        ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
1952
        if (ret < 0) {
1953
            return ret;
1954
        }
1955
        assert(nb_sectors);
1956
        if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
1957
            break;
1958
        }
1959
        bs = bs->backing_hd;
1960
        if (bs == NULL) {
1961
            ret = 0;
1962
            break;
1963
        }
1964

    
1965
        depth++;
1966
    }
1967

    
1968
    e->start = sector_num * BDRV_SECTOR_SIZE;
1969
    e->length = nb_sectors * BDRV_SECTOR_SIZE;
1970
    e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
1971
    e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
1972
    e->depth = depth;
1973
    e->bs = bs;
1974
    return 0;
1975
}
1976

    
1977
static int img_map(int argc, char **argv)
1978
{
1979
    int c;
1980
    OutputFormat output_format = OFORMAT_HUMAN;
1981
    BlockDriverState *bs;
1982
    const char *filename, *fmt, *output;
1983
    int64_t length;
1984
    MapEntry curr = { .length = 0 }, next;
1985
    int ret = 0;
1986

    
1987
    fmt = NULL;
1988
    output = NULL;
1989
    for (;;) {
1990
        int option_index = 0;
1991
        static const struct option long_options[] = {
1992
            {"help", no_argument, 0, 'h'},
1993
            {"format", required_argument, 0, 'f'},
1994
            {"output", required_argument, 0, OPTION_OUTPUT},
1995
            {0, 0, 0, 0}
1996
        };
1997
        c = getopt_long(argc, argv, "f:h",
1998
                        long_options, &option_index);
1999
        if (c == -1) {
2000
            break;
2001
        }
2002
        switch (c) {
2003
        case '?':
2004
        case 'h':
2005
            help();
2006
            break;
2007
        case 'f':
2008
            fmt = optarg;
2009
            break;
2010
        case OPTION_OUTPUT:
2011
            output = optarg;
2012
            break;
2013
        }
2014
    }
2015
    if (optind >= argc) {
2016
        help();
2017
    }
2018
    filename = argv[optind++];
2019

    
2020
    if (output && !strcmp(output, "json")) {
2021
        output_format = OFORMAT_JSON;
2022
    } else if (output && !strcmp(output, "human")) {
2023
        output_format = OFORMAT_HUMAN;
2024
    } else if (output) {
2025
        error_report("--output must be used with human or json as argument.");
2026
        return 1;
2027
    }
2028

    
2029
    bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS, true, false);
2030
    if (!bs) {
2031
        return 1;
2032
    }
2033

    
2034
    if (output_format == OFORMAT_HUMAN) {
2035
        printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2036
    }
2037

    
2038
    length = bdrv_getlength(bs);
2039
    while (curr.start + curr.length < length) {
2040
        int64_t nsectors_left;
2041
        int64_t sector_num;
2042
        int n;
2043

    
2044
        sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2045

    
2046
        /* Probe up to 1 GiB at a time.  */
2047
        nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2048
        n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2049
        ret = get_block_status(bs, sector_num, n, &next);
2050

    
2051
        if (ret < 0) {
2052
            error_report("Could not read file metadata: %s", strerror(-ret));
2053
            goto out;
2054
        }
2055

    
2056
        if (curr.length != 0 && curr.flags == next.flags &&
2057
            curr.depth == next.depth &&
2058
            ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2059
             curr.offset + curr.length == next.offset)) {
2060
            curr.length += next.length;
2061
            continue;
2062
        }
2063

    
2064
        if (curr.length > 0) {
2065
            dump_map_entry(output_format, &curr, &next);
2066
        }
2067
        curr = next;
2068
    }
2069

    
2070
    dump_map_entry(output_format, &curr, NULL);
2071

    
2072
out:
2073
    bdrv_unref(bs);
2074
    return ret < 0;
2075
}
2076

    
2077
#define SNAPSHOT_LIST   1
2078
#define SNAPSHOT_CREATE 2
2079
#define SNAPSHOT_APPLY  3
2080
#define SNAPSHOT_DELETE 4
2081

    
2082
static int img_snapshot(int argc, char **argv)
2083
{
2084
    BlockDriverState *bs;
2085
    QEMUSnapshotInfo sn;
2086
    char *filename, *snapshot_name = NULL;
2087
    int c, ret = 0, bdrv_oflags;
2088
    int action = 0;
2089
    qemu_timeval tv;
2090
    bool quiet = false;
2091
    Error *err = NULL;
2092

    
2093
    bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
2094
    /* Parse commandline parameters */
2095
    for(;;) {
2096
        c = getopt(argc, argv, "la:c:d:hq");
2097
        if (c == -1) {
2098
            break;
2099
        }
2100
        switch(c) {
2101
        case '?':
2102
        case 'h':
2103
            help();
2104
            return 0;
2105
        case 'l':
2106
            if (action) {
2107
                help();
2108
                return 0;
2109
            }
2110
            action = SNAPSHOT_LIST;
2111
            bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2112
            break;
2113
        case 'a':
2114
            if (action) {
2115
                help();
2116
                return 0;
2117
            }
2118
            action = SNAPSHOT_APPLY;
2119
            snapshot_name = optarg;
2120
            break;
2121
        case 'c':
2122
            if (action) {
2123
                help();
2124
                return 0;
2125
            }
2126
            action = SNAPSHOT_CREATE;
2127
            snapshot_name = optarg;
2128
            break;
2129
        case 'd':
2130
            if (action) {
2131
                help();
2132
                return 0;
2133
            }
2134
            action = SNAPSHOT_DELETE;
2135
            snapshot_name = optarg;
2136
            break;
2137
        case 'q':
2138
            quiet = true;
2139
            break;
2140
        }
2141
    }
2142

    
2143
    if (optind != argc - 1) {
2144
        help();
2145
    }
2146
    filename = argv[optind++];
2147

    
2148
    /* Open the image */
2149
    bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
2150
    if (!bs) {
2151
        return 1;
2152
    }
2153

    
2154
    /* Perform the requested action */
2155
    switch(action) {
2156
    case SNAPSHOT_LIST:
2157
        dump_snapshots(bs);
2158
        break;
2159

    
2160
    case SNAPSHOT_CREATE:
2161
        memset(&sn, 0, sizeof(sn));
2162
        pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2163

    
2164
        qemu_gettimeofday(&tv);
2165
        sn.date_sec = tv.tv_sec;
2166
        sn.date_nsec = tv.tv_usec * 1000;
2167

    
2168
        ret = bdrv_snapshot_create(bs, &sn);
2169
        if (ret) {
2170
            error_report("Could not create snapshot '%s': %d (%s)",
2171
                snapshot_name, ret, strerror(-ret));
2172
        }
2173
        break;
2174

    
2175
    case SNAPSHOT_APPLY:
2176
        ret = bdrv_snapshot_goto(bs, snapshot_name);
2177
        if (ret) {
2178
            error_report("Could not apply snapshot '%s': %d (%s)",
2179
                snapshot_name, ret, strerror(-ret));
2180
        }
2181
        break;
2182

    
2183
    case SNAPSHOT_DELETE:
2184
        bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2185
        if (err) {
2186
            error_report("Could not delete snapshot '%s': (%s)",
2187
                         snapshot_name, error_get_pretty(err));
2188
            error_free(err);
2189
            ret = 1;
2190
        }
2191
        break;
2192
    }
2193

    
2194
    /* Cleanup */
2195
    bdrv_unref(bs);
2196
    if (ret) {
2197
        return 1;
2198
    }
2199
    return 0;
2200
}
2201

    
2202
static int img_rebase(int argc, char **argv)
2203
{
2204
    BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
2205
    BlockDriver *old_backing_drv, *new_backing_drv;
2206
    char *filename;
2207
    const char *fmt, *cache, *out_basefmt, *out_baseimg;
2208
    int c, flags, ret;
2209
    int unsafe = 0;
2210
    int progress = 0;
2211
    bool quiet = false;
2212
    Error *local_err = NULL;
2213

    
2214
    /* Parse commandline parameters */
2215
    fmt = NULL;
2216
    cache = BDRV_DEFAULT_CACHE;
2217
    out_baseimg = NULL;
2218
    out_basefmt = NULL;
2219
    for(;;) {
2220
        c = getopt(argc, argv, "uhf:F:b:pt:q");
2221
        if (c == -1) {
2222
            break;
2223
        }
2224
        switch(c) {
2225
        case '?':
2226
        case 'h':
2227
            help();
2228
            return 0;
2229
        case 'f':
2230
            fmt = optarg;
2231
            break;
2232
        case 'F':
2233
            out_basefmt = optarg;
2234
            break;
2235
        case 'b':
2236
            out_baseimg = optarg;
2237
            break;
2238
        case 'u':
2239
            unsafe = 1;
2240
            break;
2241
        case 'p':
2242
            progress = 1;
2243
            break;
2244
        case 't':
2245
            cache = optarg;
2246
            break;
2247
        case 'q':
2248
            quiet = true;
2249
            break;
2250
        }
2251
    }
2252

    
2253
    if (quiet) {
2254
        progress = 0;
2255
    }
2256

    
2257
    if ((optind != argc - 1) || (!unsafe && !out_baseimg)) {
2258
        help();
2259
    }
2260
    filename = argv[optind++];
2261

    
2262
    qemu_progress_init(progress, 2.0);
2263
    qemu_progress_print(0, 100);
2264

    
2265
    flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2266
    ret = bdrv_parse_cache_flags(cache, &flags);
2267
    if (ret < 0) {
2268
        error_report("Invalid cache option: %s", cache);
2269
        return -1;
2270
    }
2271

    
2272
    /*
2273
     * Open the images.
2274
     *
2275
     * Ignore the old backing file for unsafe rebase in case we want to correct
2276
     * the reference to a renamed or moved backing file.
2277
     */
2278
    bs = bdrv_new_open(filename, fmt, flags, true, quiet);
2279
    if (!bs) {
2280
        return 1;
2281
    }
2282

    
2283
    /* Find the right drivers for the backing files */
2284
    old_backing_drv = NULL;
2285
    new_backing_drv = NULL;
2286

    
2287
    if (!unsafe && bs->backing_format[0] != '\0') {
2288
        old_backing_drv = bdrv_find_format(bs->backing_format);
2289
        if (old_backing_drv == NULL) {
2290
            error_report("Invalid format name: '%s'", bs->backing_format);
2291
            ret = -1;
2292
            goto out;
2293
        }
2294
    }
2295

    
2296
    if (out_basefmt != NULL) {
2297
        new_backing_drv = bdrv_find_format(out_basefmt);
2298
        if (new_backing_drv == NULL) {
2299
            error_report("Invalid format name: '%s'", out_basefmt);
2300
            ret = -1;
2301
            goto out;
2302
        }
2303
    }
2304

    
2305
    /* For safe rebasing we need to compare old and new backing file */
2306
    if (unsafe) {
2307
        /* Make the compiler happy */
2308
        bs_old_backing = NULL;
2309
        bs_new_backing = NULL;
2310
    } else {
2311
        char backing_name[1024];
2312

    
2313
        bs_old_backing = bdrv_new("old_backing");
2314
        bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2315
        ret = bdrv_open(&bs_old_backing, backing_name, NULL, BDRV_O_FLAGS,
2316
                        old_backing_drv, &local_err);
2317
        if (ret) {
2318
            error_report("Could not open old backing file '%s': %s",
2319
                         backing_name, error_get_pretty(local_err));
2320
            error_free(local_err);
2321
            goto out;
2322
        }
2323
        if (out_baseimg[0]) {
2324
            bs_new_backing = bdrv_new("new_backing");
2325
            ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, BDRV_O_FLAGS,
2326
                        new_backing_drv, &local_err);
2327
            if (ret) {
2328
                error_report("Could not open new backing file '%s': %s",
2329
                             out_baseimg, error_get_pretty(local_err));
2330
                error_free(local_err);
2331
                goto out;
2332
            }
2333
        }
2334
    }
2335

    
2336
    /*
2337
     * Check each unallocated cluster in the COW file. If it is unallocated,
2338
     * accesses go to the backing file. We must therefore compare this cluster
2339
     * in the old and new backing file, and if they differ we need to copy it
2340
     * from the old backing file into the COW file.
2341
     *
2342
     * If qemu-img crashes during this step, no harm is done. The content of
2343
     * the image is the same as the original one at any time.
2344
     */
2345
    if (!unsafe) {
2346
        uint64_t num_sectors;
2347
        uint64_t old_backing_num_sectors;
2348
        uint64_t new_backing_num_sectors = 0;
2349
        uint64_t sector;
2350
        int n;
2351
        uint8_t * buf_old;
2352
        uint8_t * buf_new;
2353
        float local_progress = 0;
2354

    
2355
        buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2356
        buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
2357

    
2358
        bdrv_get_geometry(bs, &num_sectors);
2359
        bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
2360
        if (bs_new_backing) {
2361
            bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
2362
        }
2363

    
2364
        if (num_sectors != 0) {
2365
            local_progress = (float)100 /
2366
                (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2367
        }
2368

    
2369
        for (sector = 0; sector < num_sectors; sector += n) {
2370

    
2371
            /* How many sectors can we handle with the next read? */
2372
            if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2373
                n = (IO_BUF_SIZE / 512);
2374
            } else {
2375
                n = num_sectors - sector;
2376
            }
2377

    
2378
            /* If the cluster is allocated, we don't need to take action */
2379
            ret = bdrv_is_allocated(bs, sector, n, &n);
2380
            if (ret < 0) {
2381
                error_report("error while reading image metadata: %s",
2382
                             strerror(-ret));
2383
                goto out;
2384
            }
2385
            if (ret) {
2386
                continue;
2387
            }
2388

    
2389
            /*
2390
             * Read old and new backing file and take into consideration that
2391
             * backing files may be smaller than the COW image.
2392
             */
2393
            if (sector >= old_backing_num_sectors) {
2394
                memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2395
            } else {
2396
                if (sector + n > old_backing_num_sectors) {
2397
                    n = old_backing_num_sectors - sector;
2398
                }
2399

    
2400
                ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2401
                if (ret < 0) {
2402
                    error_report("error while reading from old backing file");
2403
                    goto out;
2404
                }
2405
            }
2406

    
2407
            if (sector >= new_backing_num_sectors || !bs_new_backing) {
2408
                memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2409
            } else {
2410
                if (sector + n > new_backing_num_sectors) {
2411
                    n = new_backing_num_sectors - sector;
2412
                }
2413

    
2414
                ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2415
                if (ret < 0) {
2416
                    error_report("error while reading from new backing file");
2417
                    goto out;
2418
                }
2419
            }
2420

    
2421
            /* If they differ, we need to write to the COW file */
2422
            uint64_t written = 0;
2423

    
2424
            while (written < n) {
2425
                int pnum;
2426

    
2427
                if (compare_sectors(buf_old + written * 512,
2428
                    buf_new + written * 512, n - written, &pnum))
2429
                {
2430
                    ret = bdrv_write(bs, sector + written,
2431
                        buf_old + written * 512, pnum);
2432
                    if (ret < 0) {
2433
                        error_report("Error while writing to COW image: %s",
2434
                            strerror(-ret));
2435
                        goto out;
2436
                    }
2437
                }
2438

    
2439
                written += pnum;
2440
            }
2441
            qemu_progress_print(local_progress, 100);
2442
        }
2443

    
2444
        qemu_vfree(buf_old);
2445
        qemu_vfree(buf_new);
2446
    }
2447

    
2448
    /*
2449
     * Change the backing file. All clusters that are different from the old
2450
     * backing file are overwritten in the COW file now, so the visible content
2451
     * doesn't change when we switch the backing file.
2452
     */
2453
    if (out_baseimg && *out_baseimg) {
2454
        ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2455
    } else {
2456
        ret = bdrv_change_backing_file(bs, NULL, NULL);
2457
    }
2458

    
2459
    if (ret == -ENOSPC) {
2460
        error_report("Could not change the backing file to '%s': No "
2461
                     "space left in the file header", out_baseimg);
2462
    } else if (ret < 0) {
2463
        error_report("Could not change the backing file to '%s': %s",
2464
            out_baseimg, strerror(-ret));
2465
    }
2466

    
2467
    qemu_progress_print(100, 0);
2468
    /*
2469
     * TODO At this point it is possible to check if any clusters that are
2470
     * allocated in the COW file are the same in the backing file. If so, they
2471
     * could be dropped from the COW file. Don't do this before switching the
2472
     * backing file, in case of a crash this would lead to corruption.
2473
     */
2474
out:
2475
    qemu_progress_end();
2476
    /* Cleanup */
2477
    if (!unsafe) {
2478
        if (bs_old_backing != NULL) {
2479
            bdrv_unref(bs_old_backing);
2480
        }
2481
        if (bs_new_backing != NULL) {
2482
            bdrv_unref(bs_new_backing);
2483
        }
2484
    }
2485

    
2486
    bdrv_unref(bs);
2487
    if (ret) {
2488
        return 1;
2489
    }
2490
    return 0;
2491
}
2492

    
2493
static int img_resize(int argc, char **argv)
2494
{
2495
    int c, ret, relative;
2496
    const char *filename, *fmt, *size;
2497
    int64_t n, total_size;
2498
    bool quiet = false;
2499
    BlockDriverState *bs = NULL;
2500
    QemuOpts *param;
2501
    static QemuOptsList resize_options = {
2502
        .name = "resize_options",
2503
        .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2504
        .desc = {
2505
            {
2506
                .name = BLOCK_OPT_SIZE,
2507
                .type = QEMU_OPT_SIZE,
2508
                .help = "Virtual disk size"
2509
            }, {
2510
                /* end of list */
2511
            }
2512
        },
2513
    };
2514

    
2515
    /* Remove size from argv manually so that negative numbers are not treated
2516
     * as options by getopt. */
2517
    if (argc < 3) {
2518
        help();
2519
        return 1;
2520
    }
2521

    
2522
    size = argv[--argc];
2523

    
2524
    /* Parse getopt arguments */
2525
    fmt = NULL;
2526
    for(;;) {
2527
        c = getopt(argc, argv, "f:hq");
2528
        if (c == -1) {
2529
            break;
2530
        }
2531
        switch(c) {
2532
        case '?':
2533
        case 'h':
2534
            help();
2535
            break;
2536
        case 'f':
2537
            fmt = optarg;
2538
            break;
2539
        case 'q':
2540
            quiet = true;
2541
            break;
2542
        }
2543
    }
2544
    if (optind != argc - 1) {
2545
        help();
2546
    }
2547
    filename = argv[optind++];
2548

    
2549
    /* Choose grow, shrink, or absolute resize mode */
2550
    switch (size[0]) {
2551
    case '+':
2552
        relative = 1;
2553
        size++;
2554
        break;
2555
    case '-':
2556
        relative = -1;
2557
        size++;
2558
        break;
2559
    default:
2560
        relative = 0;
2561
        break;
2562
    }
2563

    
2564
    /* Parse size */
2565
    param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
2566
    if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
2567
        /* Error message already printed when size parsing fails */
2568
        ret = -1;
2569
        qemu_opts_del(param);
2570
        goto out;
2571
    }
2572
    n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2573
    qemu_opts_del(param);
2574

    
2575
    bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2576
    if (!bs) {
2577
        ret = -1;
2578
        goto out;
2579
    }
2580

    
2581
    if (relative) {
2582
        total_size = bdrv_getlength(bs) + n * relative;
2583
    } else {
2584
        total_size = n;
2585
    }
2586
    if (total_size <= 0) {
2587
        error_report("New image size must be positive");
2588
        ret = -1;
2589
        goto out;
2590
    }
2591

    
2592
    ret = bdrv_truncate(bs, total_size);
2593
    switch (ret) {
2594
    case 0:
2595
        qprintf(quiet, "Image resized.\n");
2596
        break;
2597
    case -ENOTSUP:
2598
        error_report("This image does not support resize");
2599
        break;
2600
    case -EACCES:
2601
        error_report("Image is read-only");
2602
        break;
2603
    default:
2604
        error_report("Error resizing image (%d)", -ret);
2605
        break;
2606
    }
2607
out:
2608
    if (bs) {
2609
        bdrv_unref(bs);
2610
    }
2611
    if (ret) {
2612
        return 1;
2613
    }
2614
    return 0;
2615
}
2616

    
2617
static int img_amend(int argc, char **argv)
2618
{
2619
    int c, ret = 0;
2620
    char *options = NULL;
2621
    QEMUOptionParameter *create_options = NULL, *options_param = NULL;
2622
    const char *fmt = NULL, *filename;
2623
    bool quiet = false;
2624
    BlockDriverState *bs = NULL;
2625

    
2626
    for (;;) {
2627
        c = getopt(argc, argv, "hqf:o:");
2628
        if (c == -1) {
2629
            break;
2630
        }
2631

    
2632
        switch (c) {
2633
            case 'h':
2634
            case '?':
2635
                help();
2636
                break;
2637
            case 'o':
2638
                options = optarg;
2639
                break;
2640
            case 'f':
2641
                fmt = optarg;
2642
                break;
2643
            case 'q':
2644
                quiet = true;
2645
                break;
2646
        }
2647
    }
2648

    
2649
    if (optind != argc - 1) {
2650
        help();
2651
    }
2652

    
2653
    if (!options) {
2654
        help();
2655
    }
2656

    
2657
    filename = argv[argc - 1];
2658

    
2659
    bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2660
    if (!bs) {
2661
        error_report("Could not open image '%s'", filename);
2662
        ret = -1;
2663
        goto out;
2664
    }
2665

    
2666
    fmt = bs->drv->format_name;
2667

    
2668
    if (is_help_option(options)) {
2669
        ret = print_block_option_help(filename, fmt);
2670
        goto out;
2671
    }
2672

    
2673
    create_options = append_option_parameters(create_options,
2674
            bs->drv->create_options);
2675
    options_param = parse_option_parameters(options, create_options,
2676
            options_param);
2677
    if (options_param == NULL) {
2678
        error_report("Invalid options for file format '%s'", fmt);
2679
        ret = -1;
2680
        goto out;
2681
    }
2682

    
2683
    ret = bdrv_amend_options(bs, options_param);
2684
    if (ret < 0) {
2685
        error_report("Error while amending options: %s", strerror(-ret));
2686
        goto out;
2687
    }
2688

    
2689
out:
2690
    if (bs) {
2691
        bdrv_unref(bs);
2692
    }
2693
    free_option_parameters(create_options);
2694
    free_option_parameters(options_param);
2695
    if (ret) {
2696
        return 1;
2697
    }
2698
    return 0;
2699
}
2700

    
2701
static const img_cmd_t img_cmds[] = {
2702
#define DEF(option, callback, arg_string)        \
2703
    { option, callback },
2704
#include "qemu-img-cmds.h"
2705
#undef DEF
2706
#undef GEN_DOCS
2707
    { NULL, NULL, },
2708
};
2709

    
2710
int main(int argc, char **argv)
2711
{
2712
    const img_cmd_t *cmd;
2713
    const char *cmdname;
2714

    
2715
#ifdef CONFIG_POSIX
2716
    signal(SIGPIPE, SIG_IGN);
2717
#endif
2718

    
2719
    error_set_progname(argv[0]);
2720

    
2721
    qemu_init_main_loop();
2722
    bdrv_init();
2723
    if (argc < 2)
2724
        help();
2725
    cmdname = argv[1];
2726
    argc--; argv++;
2727

    
2728
    /* find the command */
2729
    for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2730
        if (!strcmp(cmdname, cmd->name)) {
2731
            return cmd->handler(argc, argv);
2732
        }
2733
    }
2734

    
2735
    /* not found */
2736
    help();
2737
    return 0;
2738
}