Coverage Report

Created: 2026-11-20 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qemu/block/qcow2-snapshot.c
Line
Count
Source
1
/*
2
 * Block driver for the QCOW version 2 format
3
 *
4
 * Copyright (c) 2004-2006 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
25
#include "qemu/osdep.h"
26
#include "system/block-backend.h"
27
#include "qapi/error.h"
28
#include "qcow2.h"
29
#include "qemu/bswap.h"
30
#include "qemu/error-report.h"
31
#include "qemu/cutils.h"
32
#include "qemu/memalign.h"
33
34
static void qcow2_free_single_snapshot(BlockDriverState *bs, int i)
35
0
{
36
0
    BDRVQcow2State *s = bs->opaque;
37
38
0
    assert(i >= 0 && i < s->nb_snapshots);
39
0
    g_free(s->snapshots[i].name);
40
0
    g_free(s->snapshots[i].id_str);
41
0
    g_free(s->snapshots[i].unknown_extra_data);
42
0
    memset(&s->snapshots[i], 0, sizeof(s->snapshots[i]));
43
0
}
44
45
void qcow2_free_snapshots(BlockDriverState *bs)
46
0
{
47
0
    BDRVQcow2State *s = bs->opaque;
48
0
    int i;
49
50
0
    for(i = 0; i < s->nb_snapshots; i++) {
51
0
        qcow2_free_single_snapshot(bs, i);
52
0
    }
53
0
    g_free(s->snapshots);
54
0
    s->snapshots = NULL;
55
0
    s->nb_snapshots = 0;
56
0
}
57
58
/*
59
 * If @repair is true, try to repair a broken snapshot table instead
60
 * of just returning an error:
61
 *
62
 * - If the snapshot table was too long, set *nb_clusters_reduced to
63
 *   the number of snapshots removed off the end.
64
 *   The caller will update the on-disk nb_snapshots accordingly;
65
 *   this leaks clusters, but is safe.
66
 *   (The on-disk information must be updated before
67
 *   qcow2_check_refcounts(), because that function relies on
68
 *   s->nb_snapshots to reflect the on-disk value.)
69
 *
70
 * - If there were snapshots with too much extra metadata, increment
71
 *   *extra_data_dropped for each.
72
 *   This requires the caller to eventually rewrite the whole snapshot
73
 *   table, which requires cluster allocation.  Therefore, this should
74
 *   be done only after qcow2_check_refcounts() made sure the refcount
75
 *   structures are valid.
76
 *   (In the meantime, the image is still valid because
77
 *   qcow2_check_refcounts() does not do anything with snapshots'
78
 *   extra data.)
79
 */
80
static coroutine_fn GRAPH_RDLOCK
81
int qcow2_do_read_snapshots(BlockDriverState *bs, bool repair,
82
                            int *nb_clusters_reduced,
83
                            int *extra_data_dropped,
84
                            Error **errp)
85
0
{
86
0
    BDRVQcow2State *s = bs->opaque;
87
0
    QCowSnapshotHeader h;
88
0
    QCowSnapshotExtraData extra;
89
0
    QCowSnapshot *sn;
90
0
    int i, id_str_size, name_size;
91
0
    int64_t offset, pre_sn_offset;
92
0
    uint64_t table_length = 0;
93
0
    int ret;
94
95
0
    if (!s->nb_snapshots) {
96
0
        s->snapshots = NULL;
97
0
        s->snapshots_size = 0;
98
0
        return 0;
99
0
    }
100
101
0
    offset = s->snapshots_offset;
102
0
    s->snapshots = g_new0(QCowSnapshot, s->nb_snapshots);
103
104
0
    for(i = 0; i < s->nb_snapshots; i++) {
105
0
        bool truncate_unknown_extra_data = false;
106
107
0
        pre_sn_offset = offset;
108
0
        table_length = ROUND_UP(table_length, 8);
109
110
        /* Read statically sized part of the snapshot header */
111
0
        offset = ROUND_UP(offset, 8);
112
0
        ret = bdrv_co_pread(bs->file, offset, sizeof(h), &h, 0);
113
0
        if (ret < 0) {
114
0
            error_setg_errno(errp, -ret, "Failed to read snapshot table");
115
0
            goto fail;
116
0
        }
117
118
0
        offset += sizeof(h);
119
0
        sn = s->snapshots + i;
120
0
        sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
121
0
        sn->l1_size = be32_to_cpu(h.l1_size);
122
0
        sn->vm_state_size = be32_to_cpu(h.vm_state_size);
123
0
        sn->date_sec = be32_to_cpu(h.date_sec);
124
0
        sn->date_nsec = be32_to_cpu(h.date_nsec);
125
0
        sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
126
0
        sn->extra_data_size = be32_to_cpu(h.extra_data_size);
127
128
0
        id_str_size = be16_to_cpu(h.id_str_size);
129
0
        name_size = be16_to_cpu(h.name_size);
130
131
0
        if (sn->extra_data_size > QCOW_MAX_SNAPSHOT_EXTRA_DATA) {
132
0
            if (!repair) {
133
0
                ret = -EFBIG;
134
0
                error_setg(errp, "Too much extra metadata in snapshot table "
135
0
                           "entry %i", i);
136
0
                error_append_hint(errp, "You can force-remove this extra "
137
0
                                  "metadata with qemu-img check -r all\n");
138
0
                goto fail;
139
0
            }
140
141
0
            fprintf(stderr, "Discarding too much extra metadata in snapshot "
142
0
                    "table entry %i (%" PRIu32 " > %u)\n",
143
0
                    i, sn->extra_data_size, QCOW_MAX_SNAPSHOT_EXTRA_DATA);
144
145
0
            (*extra_data_dropped)++;
146
0
            truncate_unknown_extra_data = true;
147
0
        }
148
149
        /* Read known extra data */
150
0
        ret = bdrv_co_pread(bs->file, offset,
151
0
                            MIN(sizeof(extra), sn->extra_data_size), &extra, 0);
152
0
        if (ret < 0) {
153
0
            error_setg_errno(errp, -ret, "Failed to read snapshot table");
154
0
            goto fail;
155
0
        }
156
0
        offset += MIN(sizeof(extra), sn->extra_data_size);
157
158
0
        if (sn->extra_data_size >= endof(QCowSnapshotExtraData,
159
0
                                         vm_state_size_large)) {
160
0
            sn->vm_state_size = be64_to_cpu(extra.vm_state_size_large);
161
0
        }
162
163
0
        if (sn->extra_data_size >= endof(QCowSnapshotExtraData, disk_size)) {
164
0
            sn->disk_size = be64_to_cpu(extra.disk_size);
165
0
        } else {
166
0
            sn->disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
167
0
        }
168
169
0
        if (sn->extra_data_size >= endof(QCowSnapshotExtraData, icount)) {
170
0
            sn->icount = be64_to_cpu(extra.icount);
171
0
        } else {
172
0
            sn->icount = -1ULL;
173
0
        }
174
175
0
        if (sn->extra_data_size > sizeof(extra)) {
176
0
            uint64_t extra_data_end;
177
0
            size_t unknown_extra_data_size;
178
179
0
            extra_data_end = offset + sn->extra_data_size - sizeof(extra);
180
181
0
            if (truncate_unknown_extra_data) {
182
0
                sn->extra_data_size = QCOW_MAX_SNAPSHOT_EXTRA_DATA;
183
0
            }
184
185
            /* Store unknown extra data */
186
0
            unknown_extra_data_size = sn->extra_data_size - sizeof(extra);
187
0
            sn->unknown_extra_data = g_malloc(unknown_extra_data_size);
188
0
            ret = bdrv_co_pread(bs->file, offset, unknown_extra_data_size,
189
0
                                sn->unknown_extra_data, 0);
190
0
            if (ret < 0) {
191
0
                error_setg_errno(errp, -ret,
192
0
                                 "Failed to read snapshot table");
193
0
                goto fail;
194
0
            }
195
0
            offset = extra_data_end;
196
0
        }
197
198
        /* Read snapshot ID */
199
0
        sn->id_str = g_malloc(id_str_size + 1);
200
0
        ret = bdrv_co_pread(bs->file, offset, id_str_size, sn->id_str, 0);
201
0
        if (ret < 0) {
202
0
            error_setg_errno(errp, -ret, "Failed to read snapshot table");
203
0
            goto fail;
204
0
        }
205
0
        offset += id_str_size;
206
0
        sn->id_str[id_str_size] = '\0';
207
208
        /* Read snapshot name */
209
0
        sn->name = g_malloc(name_size + 1);
210
0
        ret = bdrv_co_pread(bs->file, offset, name_size, sn->name, 0);
211
0
        if (ret < 0) {
212
0
            error_setg_errno(errp, -ret, "Failed to read snapshot table");
213
0
            goto fail;
214
0
        }
215
0
        offset += name_size;
216
0
        sn->name[name_size] = '\0';
217
218
        /* Note that the extra data may have been truncated */
219
0
        table_length += sizeof(h) + sn->extra_data_size + id_str_size +
220
0
                        name_size;
221
0
        if (!repair) {
222
0
            assert(table_length == offset - s->snapshots_offset);
223
0
        }
224
225
0
        if (table_length > QCOW_MAX_SNAPSHOTS_SIZE ||
226
0
            offset - s->snapshots_offset > INT_MAX)
227
0
        {
228
0
            if (!repair) {
229
0
                ret = -EFBIG;
230
0
                error_setg(errp, "Snapshot table is too big");
231
0
                error_append_hint(errp, "You can force-remove all %u "
232
0
                                  "overhanging snapshots with qemu-img check "
233
0
                                  "-r all\n", s->nb_snapshots - i);
234
0
                goto fail;
235
0
            }
236
237
0
            fprintf(stderr, "Discarding %u overhanging snapshots (snapshot "
238
0
                    "table is too big)\n", s->nb_snapshots - i);
239
240
0
            *nb_clusters_reduced += (s->nb_snapshots - i);
241
242
            /* Discard current snapshot also */
243
0
            qcow2_free_single_snapshot(bs, i);
244
245
            /*
246
             * This leaks all the rest of the snapshot table and the
247
             * snapshots' clusters, but we run in check -r all mode,
248
             * so qcow2_check_refcounts() will take care of it.
249
             */
250
0
            s->nb_snapshots = i;
251
0
            offset = pre_sn_offset;
252
0
            break;
253
0
        }
254
0
    }
255
256
0
    assert(offset - s->snapshots_offset <= INT_MAX);
257
0
    s->snapshots_size = offset - s->snapshots_offset;
258
0
    return 0;
259
260
0
fail:
261
0
    qcow2_free_snapshots(bs);
262
0
    return ret;
263
0
}
264
265
int coroutine_fn qcow2_read_snapshots(BlockDriverState *bs, Error **errp)
266
0
{
267
0
    return qcow2_do_read_snapshots(bs, false, NULL, NULL, errp);
268
0
}
269
270
/* add at the end of the file a new list of snapshots */
271
int qcow2_write_snapshots(BlockDriverState *bs)
272
0
{
273
0
    BDRVQcow2State *s = bs->opaque;
274
0
    QCowSnapshot *sn;
275
0
    QCowSnapshotHeader h;
276
0
    QCowSnapshotExtraData extra;
277
0
    int i, name_size, id_str_size, snapshots_size;
278
0
    struct {
279
0
        uint32_t nb_snapshots;
280
0
        uint64_t snapshots_offset;
281
0
    } QEMU_PACKED header_data;
282
0
    int64_t offset, snapshots_offset = 0;
283
0
    int ret;
284
285
    /* compute the size of the snapshots */
286
0
    offset = 0;
287
0
    for(i = 0; i < s->nb_snapshots; i++) {
288
0
        sn = s->snapshots + i;
289
0
        offset = ROUND_UP(offset, 8);
290
0
        offset += sizeof(h);
291
0
        offset += MAX(sizeof(extra), sn->extra_data_size);
292
0
        offset += strlen(sn->id_str);
293
0
        offset += strlen(sn->name);
294
295
0
        if (offset > QCOW_MAX_SNAPSHOTS_SIZE) {
296
0
            ret = -EFBIG;
297
0
            goto fail;
298
0
        }
299
0
    }
300
301
0
    assert(offset <= INT_MAX);
302
0
    snapshots_size = offset;
303
304
    /* Allocate space for the new snapshot list */
305
0
    snapshots_offset = qcow2_alloc_clusters(bs, snapshots_size);
306
0
    offset = snapshots_offset;
307
0
    if (offset < 0) {
308
0
        ret = offset;
309
0
        goto fail;
310
0
    }
311
0
    ret = bdrv_flush(bs);
312
0
    if (ret < 0) {
313
0
        goto fail;
314
0
    }
315
316
    /* The snapshot list position has not yet been updated, so these clusters
317
     * must indeed be completely free */
318
0
    ret = qcow2_pre_write_overlap_check(bs, 0, offset, snapshots_size, false);
319
0
    if (ret < 0) {
320
0
        goto fail;
321
0
    }
322
323
324
    /* Write all snapshots to the new list */
325
0
    for(i = 0; i < s->nb_snapshots; i++) {
326
0
        sn = s->snapshots + i;
327
0
        memset(&h, 0, sizeof(h));
328
0
        h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);
329
0
        h.l1_size = cpu_to_be32(sn->l1_size);
330
        /* If it doesn't fit in 32 bit, older implementations should treat it
331
         * as a disk-only snapshot rather than truncate the VM state */
332
0
        if (sn->vm_state_size <= 0xffffffff) {
333
0
            h.vm_state_size = cpu_to_be32(sn->vm_state_size);
334
0
        }
335
0
        h.date_sec = cpu_to_be32(sn->date_sec);
336
0
        h.date_nsec = cpu_to_be32(sn->date_nsec);
337
0
        h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);
338
0
        h.extra_data_size = cpu_to_be32(MAX(sizeof(extra),
339
0
                                            sn->extra_data_size));
340
341
0
        memset(&extra, 0, sizeof(extra));
342
0
        extra.vm_state_size_large = cpu_to_be64(sn->vm_state_size);
343
0
        extra.disk_size = cpu_to_be64(sn->disk_size);
344
0
        extra.icount = cpu_to_be64(sn->icount);
345
346
0
        id_str_size = strlen(sn->id_str);
347
0
        name_size = strlen(sn->name);
348
0
        assert(id_str_size <= UINT16_MAX && name_size <= UINT16_MAX);
349
0
        h.id_str_size = cpu_to_be16(id_str_size);
350
0
        h.name_size = cpu_to_be16(name_size);
351
0
        offset = ROUND_UP(offset, 8);
352
353
0
        ret = bdrv_pwrite(bs->file, offset, sizeof(h), &h, 0);
354
0
        if (ret < 0) {
355
0
            goto fail;
356
0
        }
357
0
        offset += sizeof(h);
358
359
0
        ret = bdrv_pwrite(bs->file, offset, sizeof(extra), &extra, 0);
360
0
        if (ret < 0) {
361
0
            goto fail;
362
0
        }
363
0
        offset += sizeof(extra);
364
365
0
        if (sn->extra_data_size > sizeof(extra)) {
366
0
            size_t unknown_extra_data_size =
367
0
                sn->extra_data_size - sizeof(extra);
368
369
            /* qcow2_read_snapshots() ensures no unbounded allocation */
370
0
            assert(unknown_extra_data_size <= BDRV_REQUEST_MAX_BYTES);
371
0
            assert(sn->unknown_extra_data);
372
373
0
            ret = bdrv_pwrite(bs->file, offset, unknown_extra_data_size,
374
0
                              sn->unknown_extra_data, 0);
375
0
            if (ret < 0) {
376
0
                goto fail;
377
0
            }
378
0
            offset += unknown_extra_data_size;
379
0
        }
380
381
0
        ret = bdrv_pwrite(bs->file, offset, id_str_size, sn->id_str, 0);
382
0
        if (ret < 0) {
383
0
            goto fail;
384
0
        }
385
0
        offset += id_str_size;
386
387
0
        ret = bdrv_pwrite(bs->file, offset, name_size, sn->name, 0);
388
0
        if (ret < 0) {
389
0
            goto fail;
390
0
        }
391
0
        offset += name_size;
392
0
    }
393
394
    /*
395
     * Update the header to point to the new snapshot table. This requires the
396
     * new table and its refcounts to be stable on disk.
397
     */
398
0
    ret = bdrv_flush(bs);
399
0
    if (ret < 0) {
400
0
        goto fail;
401
0
    }
402
403
0
    QEMU_BUILD_BUG_ON(offsetof(QCowHeader, snapshots_offset) !=
404
0
                      endof(QCowHeader, nb_snapshots));
405
406
0
    header_data.nb_snapshots        = cpu_to_be32(s->nb_snapshots);
407
0
    header_data.snapshots_offset    = cpu_to_be64(snapshots_offset);
408
409
0
    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, nb_snapshots),
410
0
                           sizeof(header_data), &header_data, 0);
411
0
    if (ret < 0) {
412
0
        goto fail;
413
0
    }
414
415
    /* free the old snapshot table */
416
0
    qcow2_free_clusters(bs, s->snapshots_offset, s->snapshots_size,
417
0
                        QCOW2_DISCARD_SNAPSHOT);
418
0
    s->snapshots_offset = snapshots_offset;
419
0
    s->snapshots_size = snapshots_size;
420
0
    return 0;
421
422
0
fail:
423
0
    if (snapshots_offset > 0) {
424
0
        qcow2_free_clusters(bs, snapshots_offset, snapshots_size,
425
0
                            QCOW2_DISCARD_ALWAYS);
426
0
    }
427
0
    return ret;
428
0
}
429
430
int coroutine_fn qcow2_check_read_snapshot_table(BlockDriverState *bs,
431
                                                 BdrvCheckResult *result,
432
                                                 BdrvCheckMode fix)
433
0
{
434
0
    BDRVQcow2State *s = bs->opaque;
435
0
    Error *local_err = NULL;
436
0
    int nb_clusters_reduced = 0;
437
0
    int extra_data_dropped = 0;
438
0
    int ret;
439
0
    struct {
440
0
        uint32_t nb_snapshots;
441
0
        uint64_t snapshots_offset;
442
0
    } QEMU_PACKED snapshot_table_pointer;
443
444
    /* qcow2_do_open() discards this information in check mode */
445
0
    ret = bdrv_co_pread(bs->file, offsetof(QCowHeader, nb_snapshots),
446
0
                        sizeof(snapshot_table_pointer), &snapshot_table_pointer,
447
0
                        0);
448
0
    if (ret < 0) {
449
0
        result->check_errors++;
450
0
        fprintf(stderr, "ERROR failed to read the snapshot table pointer from "
451
0
                "the image header: %s\n", strerror(-ret));
452
0
        return ret;
453
0
    }
454
455
0
    s->snapshots_offset = be64_to_cpu(snapshot_table_pointer.snapshots_offset);
456
0
    s->nb_snapshots = be32_to_cpu(snapshot_table_pointer.nb_snapshots);
457
458
0
    if (s->nb_snapshots > QCOW_MAX_SNAPSHOTS && (fix & BDRV_FIX_ERRORS)) {
459
0
        fprintf(stderr, "Discarding %u overhanging snapshots\n",
460
0
                s->nb_snapshots - QCOW_MAX_SNAPSHOTS);
461
462
0
        nb_clusters_reduced += s->nb_snapshots - QCOW_MAX_SNAPSHOTS;
463
0
        s->nb_snapshots = QCOW_MAX_SNAPSHOTS;
464
0
    }
465
466
0
    ret = qcow2_validate_table(bs, s->snapshots_offset, s->nb_snapshots,
467
0
                               sizeof(QCowSnapshotHeader),
468
0
                               sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
469
0
                               "snapshot table", &local_err);
470
0
    if (ret < 0) {
471
0
        result->check_errors++;
472
0
        error_reportf_err(local_err, "ERROR ");
473
474
0
        if (s->nb_snapshots > QCOW_MAX_SNAPSHOTS) {
475
0
            fprintf(stderr, "You can force-remove all %u overhanging snapshots "
476
0
                    "with qemu-img check -r all\n",
477
0
                    s->nb_snapshots - QCOW_MAX_SNAPSHOTS);
478
0
        }
479
480
        /* We did not read the snapshot table, so invalidate this information */
481
0
        s->snapshots_offset = 0;
482
0
        s->nb_snapshots = 0;
483
484
0
        return ret;
485
0
    }
486
487
0
    qemu_co_mutex_unlock(&s->lock);
488
0
    ret = qcow2_do_read_snapshots(bs, fix & BDRV_FIX_ERRORS,
489
0
                                  &nb_clusters_reduced, &extra_data_dropped,
490
0
                                  &local_err);
491
0
    qemu_co_mutex_lock(&s->lock);
492
0
    if (ret < 0) {
493
0
        result->check_errors++;
494
0
        error_reportf_err(local_err,
495
0
                          "ERROR failed to read the snapshot table: ");
496
497
        /* We did not read the snapshot table, so invalidate this information */
498
0
        s->snapshots_offset = 0;
499
0
        s->nb_snapshots = 0;
500
501
0
        return ret;
502
0
    }
503
0
    result->corruptions += nb_clusters_reduced + extra_data_dropped;
504
505
0
    if (nb_clusters_reduced) {
506
        /*
507
         * Update image header now, because:
508
         * (1) qcow2_check_refcounts() relies on s->nb_snapshots to be
509
         *     the same as what the image header says,
510
         * (2) this leaks clusters, but qcow2_check_refcounts() will
511
         *     fix that.
512
         */
513
0
        assert(fix & BDRV_FIX_ERRORS);
514
515
0
        snapshot_table_pointer.nb_snapshots = cpu_to_be32(s->nb_snapshots);
516
0
        ret = bdrv_co_pwrite_sync(bs->file, offsetof(QCowHeader, nb_snapshots),
517
0
                                  sizeof(snapshot_table_pointer.nb_snapshots),
518
0
                                  &snapshot_table_pointer.nb_snapshots, 0);
519
0
        if (ret < 0) {
520
0
            result->check_errors++;
521
0
            fprintf(stderr, "ERROR failed to update the snapshot count in the "
522
0
                    "image header: %s\n", strerror(-ret));
523
0
            return ret;
524
0
        }
525
526
0
        result->corruptions_fixed += nb_clusters_reduced;
527
0
        result->corruptions -= nb_clusters_reduced;
528
0
    }
529
530
    /*
531
     * All of v3 images' snapshot table entries need to have at least
532
     * 16 bytes of extra data.
533
     */
534
0
    if (s->qcow_version >= 3) {
535
0
        int i;
536
0
        for (i = 0; i < s->nb_snapshots; i++) {
537
0
            if (s->snapshots[i].extra_data_size <
538
0
                sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
539
0
                sizeof_field(QCowSnapshotExtraData, disk_size))
540
0
            {
541
0
                result->corruptions++;
542
0
                fprintf(stderr, "%s snapshot table entry %i is incomplete\n",
543
0
                        fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
544
0
            }
545
0
        }
546
0
    }
547
548
0
    return 0;
549
0
}
550
551
int coroutine_fn qcow2_check_fix_snapshot_table(BlockDriverState *bs,
552
                                                BdrvCheckResult *result,
553
                                                BdrvCheckMode fix)
554
0
{
555
0
    BDRVQcow2State *s = bs->opaque;
556
0
    int ret;
557
558
0
    if (result->corruptions && (fix & BDRV_FIX_ERRORS)) {
559
0
        qemu_co_mutex_unlock(&s->lock);
560
0
        ret = qcow2_write_snapshots(bs);
561
0
        qemu_co_mutex_lock(&s->lock);
562
0
        if (ret < 0) {
563
0
            result->check_errors++;
564
0
            fprintf(stderr, "ERROR failed to update snapshot table: %s\n",
565
0
                    strerror(-ret));
566
0
            return ret;
567
0
        }
568
569
0
        result->corruptions_fixed += result->corruptions;
570
0
        result->corruptions = 0;
571
0
    }
572
573
0
    return 0;
574
0
}
575
576
static void find_new_snapshot_id(BlockDriverState *bs,
577
                                 char *id_str, int id_str_size)
578
0
{
579
0
    BDRVQcow2State *s = bs->opaque;
580
0
    QCowSnapshot *sn;
581
0
    int i;
582
0
    unsigned long id, id_max = 0;
583
584
0
    for(i = 0; i < s->nb_snapshots; i++) {
585
0
        sn = s->snapshots + i;
586
0
        id = strtoul(sn->id_str, NULL, 10);
587
0
        if (id > id_max)
588
0
            id_max = id;
589
0
    }
590
0
    snprintf(id_str, id_str_size, "%lu", id_max + 1);
591
0
}
592
593
static int find_snapshot_by_id_and_name(BlockDriverState *bs,
594
                                        const char *id,
595
                                        const char *name)
596
0
{
597
0
    BDRVQcow2State *s = bs->opaque;
598
0
    int i;
599
600
0
    if (id && name) {
601
0
        for (i = 0; i < s->nb_snapshots; i++) {
602
0
            if (!strcmp(s->snapshots[i].id_str, id) &&
603
0
                !strcmp(s->snapshots[i].name, name)) {
604
0
                return i;
605
0
            }
606
0
        }
607
0
    } else if (id) {
608
0
        for (i = 0; i < s->nb_snapshots; i++) {
609
0
            if (!strcmp(s->snapshots[i].id_str, id)) {
610
0
                return i;
611
0
            }
612
0
        }
613
0
    } else if (name) {
614
0
        for (i = 0; i < s->nb_snapshots; i++) {
615
0
            if (!strcmp(s->snapshots[i].name, name)) {
616
0
                return i;
617
0
            }
618
0
        }
619
0
    }
620
621
0
    return -1;
622
0
}
623
624
static int find_snapshot_by_id_or_name(BlockDriverState *bs,
625
                                       const char *id_or_name)
626
0
{
627
0
    int ret;
628
629
0
    ret = find_snapshot_by_id_and_name(bs, id_or_name, NULL);
630
0
    if (ret >= 0) {
631
0
        return ret;
632
0
    }
633
0
    return find_snapshot_by_id_and_name(bs, NULL, id_or_name);
634
0
}
635
636
/* if no id is provided, a new one is constructed */
637
int qcow2_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
638
0
{
639
0
    BDRVQcow2State *s = bs->opaque;
640
0
    QCowSnapshot *new_snapshot_list = NULL;
641
0
    QCowSnapshot *old_snapshot_list = NULL;
642
0
    QCowSnapshot sn1, *sn = &sn1;
643
0
    int i, ret;
644
0
    uint64_t *l1_table = NULL;
645
0
    int64_t l1_table_offset;
646
647
0
    if (s->nb_snapshots >= QCOW_MAX_SNAPSHOTS) {
648
0
        return -EFBIG;
649
0
    }
650
651
0
    if (has_data_file(bs)) {
652
0
        return -ENOTSUP;
653
0
    }
654
655
0
    memset(sn, 0, sizeof(*sn));
656
657
    /* Generate an ID */
658
0
    find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));
659
660
    /* Populate sn with passed data */
661
0
    sn->id_str = g_strdup(sn_info->id_str);
662
0
    sn->name = g_strdup(sn_info->name);
663
664
0
    sn->disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
665
0
    sn->vm_state_size = sn_info->vm_state_size;
666
0
    sn->date_sec = sn_info->date_sec;
667
0
    sn->date_nsec = sn_info->date_nsec;
668
0
    sn->vm_clock_nsec = sn_info->vm_clock_nsec;
669
0
    sn->icount = sn_info->icount;
670
0
    sn->extra_data_size = sizeof(QCowSnapshotExtraData);
671
672
    /* Allocate the L1 table of the snapshot and copy the current one there. */
673
0
    l1_table_offset = qcow2_alloc_clusters(bs, s->l1_size * L1E_SIZE);
674
0
    if (l1_table_offset < 0) {
675
0
        ret = l1_table_offset;
676
0
        goto fail;
677
0
    }
678
679
0
    sn->l1_table_offset = l1_table_offset;
680
0
    sn->l1_size = s->l1_size;
681
682
0
    l1_table = g_try_new(uint64_t, s->l1_size);
683
0
    if (s->l1_size && l1_table == NULL) {
684
0
        ret = -ENOMEM;
685
0
        goto fail;
686
0
    }
687
688
0
    for(i = 0; i < s->l1_size; i++) {
689
0
        l1_table[i] = cpu_to_be64(s->l1_table[i]);
690
0
    }
691
692
0
    ret = qcow2_pre_write_overlap_check(bs, 0, sn->l1_table_offset,
693
0
                                        s->l1_size * L1E_SIZE, false);
694
0
    if (ret < 0) {
695
0
        goto fail;
696
0
    }
697
698
0
    ret = bdrv_pwrite(bs->file, sn->l1_table_offset, s->l1_size * L1E_SIZE,
699
0
                      l1_table, 0);
700
0
    if (ret < 0) {
701
0
        goto fail;
702
0
    }
703
704
0
    g_free(l1_table);
705
0
    l1_table = NULL;
706
707
    /*
708
     * Increase the refcounts of all clusters and make sure everything is
709
     * stable on disk before updating the snapshot table to contain a pointer
710
     * to the new L1 table.
711
     */
712
0
    ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);
713
0
    if (ret < 0) {
714
0
        goto fail;
715
0
    }
716
717
    /* Append the new snapshot to the snapshot list */
718
0
    new_snapshot_list = g_new(QCowSnapshot, s->nb_snapshots + 1);
719
0
    if (s->snapshots) {
720
0
        memcpy(new_snapshot_list, s->snapshots,
721
0
               s->nb_snapshots * sizeof(QCowSnapshot));
722
0
        old_snapshot_list = s->snapshots;
723
0
    }
724
0
    s->snapshots = new_snapshot_list;
725
0
    s->snapshots[s->nb_snapshots++] = *sn;
726
727
0
    ret = qcow2_write_snapshots(bs);
728
0
    if (ret < 0) {
729
0
        g_free(s->snapshots);
730
0
        s->snapshots = old_snapshot_list;
731
0
        s->nb_snapshots--;
732
0
        goto fail;
733
0
    }
734
735
0
    g_free(old_snapshot_list);
736
737
    /* The VM state isn't needed any more in the active L1 table; in fact, it
738
     * hurts by causing expensive COW for the next snapshot. */
739
0
    qcow2_cluster_discard(bs, qcow2_vm_state_offset(s),
740
0
                          ROUND_UP(sn->vm_state_size, s->cluster_size),
741
0
                          QCOW2_DISCARD_NEVER, false);
742
743
0
    return 0;
744
745
0
fail:
746
0
    g_free(sn->id_str);
747
0
    g_free(sn->name);
748
0
    g_free(l1_table);
749
750
0
    return ret;
751
0
}
752
753
/* copy the snapshot 'snapshot_name' into the current disk image */
754
int qcow2_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
755
0
{
756
0
    BDRVQcow2State *s = bs->opaque;
757
0
    QCowSnapshot *sn;
758
0
    Error *local_err = NULL;
759
0
    int i, snapshot_index;
760
0
    int cur_l1_bytes, sn_l1_bytes;
761
0
    int ret;
762
0
    uint64_t *sn_l1_table = NULL;
763
764
0
    if (has_data_file(bs)) {
765
0
        return -ENOTSUP;
766
0
    }
767
768
    /* Search the snapshot */
769
0
    snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
770
0
    if (snapshot_index < 0) {
771
0
        return -ENOENT;
772
0
    }
773
0
    sn = &s->snapshots[snapshot_index];
774
775
0
    ret = qcow2_validate_table(bs, sn->l1_table_offset, sn->l1_size,
776
0
                               L1E_SIZE, QCOW_MAX_L1_SIZE,
777
0
                               "Snapshot L1 table", &local_err);
778
0
    if (ret < 0) {
779
0
        error_report_err(local_err);
780
0
        goto fail;
781
0
    }
782
783
0
    if (sn->disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) {
784
0
        BlockBackend *blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL,
785
0
                                            &local_err);
786
0
        if (!blk) {
787
0
            error_report_err(local_err);
788
0
            ret = -ENOTSUP;
789
0
            goto fail;
790
0
        }
791
792
0
        ret = blk_truncate(blk, sn->disk_size, true, PREALLOC_MODE_OFF, 0,
793
0
                           &local_err);
794
0
        blk_unref(blk);
795
0
        if (ret < 0) {
796
0
            error_report_err(local_err);
797
0
            goto fail;
798
0
        }
799
0
    }
800
801
    /*
802
     * Make sure that the current L1 table is big enough to contain the whole
803
     * L1 table of the snapshot. If the snapshot L1 table is smaller, the
804
     * current one must be padded with zeros.
805
     */
806
0
    ret = qcow2_grow_l1_table(bs, sn->l1_size, true);
807
0
    if (ret < 0) {
808
0
        goto fail;
809
0
    }
810
811
0
    cur_l1_bytes = s->l1_size * L1E_SIZE;
812
0
    sn_l1_bytes = sn->l1_size * L1E_SIZE;
813
814
    /*
815
     * Copy the snapshot L1 table to the current L1 table.
816
     *
817
     * Before overwriting the old current L1 table on disk, make sure to
818
     * increase all refcounts for the clusters referenced by the new one.
819
     * Decrease the refcount referenced by the old one only when the L1
820
     * table is overwritten.
821
     */
822
0
    sn_l1_table = g_try_malloc0(cur_l1_bytes);
823
0
    if (cur_l1_bytes && sn_l1_table == NULL) {
824
0
        ret = -ENOMEM;
825
0
        goto fail;
826
0
    }
827
828
0
    ret = bdrv_pread(bs->file, sn->l1_table_offset, sn_l1_bytes, sn_l1_table,
829
0
                     0);
830
0
    if (ret < 0) {
831
0
        goto fail;
832
0
    }
833
834
0
    ret = qcow2_update_snapshot_refcount(bs, sn->l1_table_offset,
835
0
                                         sn->l1_size, 1);
836
0
    if (ret < 0) {
837
0
        goto fail;
838
0
    }
839
840
0
    ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L1,
841
0
                                        s->l1_table_offset, cur_l1_bytes,
842
0
                                        false);
843
0
    if (ret < 0) {
844
0
        goto fail;
845
0
    }
846
847
0
    ret = bdrv_pwrite_sync(bs->file, s->l1_table_offset, cur_l1_bytes,
848
0
                           sn_l1_table, 0);
849
0
    if (ret < 0) {
850
0
        goto fail;
851
0
    }
852
853
    /*
854
     * Decrease refcount of clusters of current L1 table.
855
     *
856
     * At this point, the in-memory s->l1_table points to the old L1 table,
857
     * whereas on disk we already have the new one.
858
     *
859
     * qcow2_update_snapshot_refcount special cases the current L1 table to use
860
     * the in-memory data instead of really using the offset to load a new one,
861
     * which is why this works.
862
     */
863
0
    ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset,
864
0
                                         s->l1_size, -1);
865
866
    /*
867
     * Now update the in-memory L1 table to be in sync with the on-disk one. We
868
     * need to do this even if updating refcounts failed.
869
     */
870
0
    for(i = 0;i < s->l1_size; i++) {
871
0
        s->l1_table[i] = be64_to_cpu(sn_l1_table[i]);
872
0
    }
873
874
0
    if (ret < 0) {
875
0
        goto fail;
876
0
    }
877
878
0
    g_free(sn_l1_table);
879
0
    sn_l1_table = NULL;
880
881
    /*
882
     * Update QCOW_OFLAG_COPIED in the active L1 table (it may have changed
883
     * when we decreased the refcount of the old snapshot.
884
     */
885
0
    ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
886
0
    if (ret < 0) {
887
0
        goto fail;
888
0
    }
889
890
0
    return 0;
891
892
0
fail:
893
0
    g_free(sn_l1_table);
894
0
    return ret;
895
0
}
896
897
int qcow2_snapshot_delete(BlockDriverState *bs,
898
                          const char *snapshot_id,
899
                          const char *name,
900
                          Error **errp)
901
0
{
902
0
    BDRVQcow2State *s = bs->opaque;
903
0
    QCowSnapshot sn;
904
0
    int snapshot_index, ret;
905
906
0
    if (has_data_file(bs)) {
907
0
        return -ENOTSUP;
908
0
    }
909
910
    /* Search the snapshot */
911
0
    snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
912
0
    if (snapshot_index < 0) {
913
0
        error_setg(errp, "Can't find the snapshot");
914
0
        return -ENOENT;
915
0
    }
916
0
    sn = s->snapshots[snapshot_index];
917
918
0
    ret = qcow2_validate_table(bs, sn.l1_table_offset, sn.l1_size,
919
0
                               L1E_SIZE, QCOW_MAX_L1_SIZE,
920
0
                               "Snapshot L1 table", errp);
921
0
    if (ret < 0) {
922
0
        return ret;
923
0
    }
924
925
    /* Remove it from the snapshot list */
926
0
    memmove(s->snapshots + snapshot_index,
927
0
            s->snapshots + snapshot_index + 1,
928
0
            (s->nb_snapshots - snapshot_index - 1) * sizeof(sn));
929
0
    s->nb_snapshots--;
930
0
    ret = qcow2_write_snapshots(bs);
931
0
    if (ret < 0) {
932
0
        error_setg_errno(errp, -ret,
933
0
                         "Failed to remove snapshot from snapshot list");
934
0
        return ret;
935
0
    }
936
937
    /*
938
     * The snapshot is now unused, clean up. If we fail after this point, we
939
     * won't recover but just leak clusters.
940
     */
941
0
    g_free(sn.unknown_extra_data);
942
0
    g_free(sn.id_str);
943
0
    g_free(sn.name);
944
945
    /*
946
     * Now decrease the refcounts of clusters referenced by the snapshot and
947
     * free the L1 table.
948
     */
949
0
    ret = qcow2_update_snapshot_refcount(bs, sn.l1_table_offset,
950
0
                                         sn.l1_size, -1);
951
0
    if (ret < 0) {
952
0
        error_setg_errno(errp, -ret, "Failed to free the cluster and L1 table");
953
0
        return ret;
954
0
    }
955
0
    qcow2_free_clusters(bs, sn.l1_table_offset, sn.l1_size * L1E_SIZE,
956
0
                        QCOW2_DISCARD_SNAPSHOT);
957
958
    /* must update the copied flag on the current cluster offsets */
959
0
    ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
960
0
    if (ret < 0) {
961
0
        error_setg_errno(errp, -ret,
962
0
                         "Failed to update snapshot status in disk");
963
0
        return ret;
964
0
    }
965
966
0
    return 0;
967
0
}
968
969
int qcow2_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
970
0
{
971
0
    BDRVQcow2State *s = bs->opaque;
972
0
    QEMUSnapshotInfo *sn_tab, *sn_info;
973
0
    QCowSnapshot *sn;
974
0
    int i;
975
976
0
    if (has_data_file(bs)) {
977
0
        return -ENOTSUP;
978
0
    }
979
0
    if (!s->nb_snapshots) {
980
0
        *psn_tab = NULL;
981
0
        return s->nb_snapshots;
982
0
    }
983
984
0
    sn_tab = g_new0(QEMUSnapshotInfo, s->nb_snapshots);
985
0
    for(i = 0; i < s->nb_snapshots; i++) {
986
0
        sn_info = sn_tab + i;
987
0
        sn = s->snapshots + i;
988
0
        pstrcpy(sn_info->id_str, sizeof(sn_info->id_str),
989
0
                sn->id_str);
990
0
        pstrcpy(sn_info->name, sizeof(sn_info->name),
991
0
                sn->name);
992
0
        sn_info->vm_state_size = sn->vm_state_size;
993
0
        sn_info->date_sec = sn->date_sec;
994
0
        sn_info->date_nsec = sn->date_nsec;
995
0
        sn_info->vm_clock_nsec = sn->vm_clock_nsec;
996
0
        sn_info->icount = sn->icount;
997
0
    }
998
0
    *psn_tab = sn_tab;
999
0
    return s->nb_snapshots;
1000
0
}
1001
1002
int qcow2_snapshot_load_tmp(BlockDriverState *bs,
1003
                            const char *snapshot_id,
1004
                            const char *name,
1005
                            Error **errp)
1006
0
{
1007
0
    int i, snapshot_index;
1008
0
    BDRVQcow2State *s = bs->opaque;
1009
0
    QCowSnapshot *sn;
1010
0
    uint64_t *new_l1_table;
1011
0
    int new_l1_bytes;
1012
0
    int ret;
1013
1014
0
    assert(bdrv_is_read_only(bs));
1015
1016
    /* Search the snapshot */
1017
0
    snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
1018
0
    if (snapshot_index < 0) {
1019
0
        error_setg(errp,
1020
0
                   "Can't find snapshot");
1021
0
        return -ENOENT;
1022
0
    }
1023
0
    sn = &s->snapshots[snapshot_index];
1024
1025
    /* Allocate and read in the snapshot's L1 table */
1026
0
    ret = qcow2_validate_table(bs, sn->l1_table_offset, sn->l1_size,
1027
0
                               L1E_SIZE, QCOW_MAX_L1_SIZE,
1028
0
                               "Snapshot L1 table", errp);
1029
0
    if (ret < 0) {
1030
0
        return ret;
1031
0
    }
1032
0
    new_l1_bytes = sn->l1_size * L1E_SIZE;
1033
0
    new_l1_table = qemu_try_blockalign(bs->file->bs, new_l1_bytes);
1034
0
    if (new_l1_table == NULL) {
1035
0
        return -ENOMEM;
1036
0
    }
1037
1038
0
    ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_bytes,
1039
0
                     new_l1_table, 0);
1040
0
    if (ret < 0) {
1041
0
        error_setg(errp, "Failed to read l1 table for snapshot");
1042
0
        qemu_vfree(new_l1_table);
1043
0
        return ret;
1044
0
    }
1045
1046
    /* Switch the L1 table */
1047
0
    qemu_vfree(s->l1_table);
1048
1049
0
    s->l1_size = sn->l1_size;
1050
0
    s->l1_table_offset = sn->l1_table_offset;
1051
0
    s->l1_table = new_l1_table;
1052
1053
0
    for(i = 0;i < s->l1_size; i++) {
1054
0
        be64_to_cpus(&s->l1_table[i]);
1055
0
    }
1056
1057
0
    return 0;
1058
0
}