Statistics
| Branch: | Revision:

root / block / vdi.c @ 78439f6a

History | View | Annotate | Download (30.1 kB)

1
/*
2
 * Block driver for the Virtual Disk Image (VDI) format
3
 *
4
 * Copyright (c) 2009 Stefan Weil
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 2 of the License, or
9
 * (at your option) version 3 or any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 * Reference:
20
 * http://forums.virtualbox.org/viewtopic.php?t=8046
21
 *
22
 * This driver supports create / read / write operations on VDI images.
23
 *
24
 * Todo (see also TODO in code):
25
 *
26
 * Some features like snapshots are still missing.
27
 *
28
 * Deallocation of zero-filled blocks and shrinking images are missing, too
29
 * (might be added to common block layer).
30
 *
31
 * Allocation of blocks could be optimized (less writes to block map and
32
 * header).
33
 *
34
 * Read and write of adjacents blocks could be done in one operation
35
 * (current code uses one operation per block (1 MiB).
36
 *
37
 * The code is not thread safe (missing locks for changes in header and
38
 * block table, no problem with current QEMU).
39
 *
40
 * Hints:
41
 *
42
 * Blocks (VDI documentation) correspond to clusters (QEMU).
43
 * QEMU's backing files could be implemented using VDI snapshot files (TODO).
44
 * VDI snapshot files may also contain the complete machine state.
45
 * Maybe this machine state can be converted to QEMU PC machine snapshot data.
46
 *
47
 * The driver keeps a block cache (little endian entries) in memory.
48
 * For the standard block size (1 MiB), a 1 TiB disk will use 4 MiB RAM,
49
 * so this seems to be reasonable.
50
 */
51

    
52
#include "qemu-common.h"
53
#include "block_int.h"
54
#include "module.h"
55

    
56
#if defined(CONFIG_UUID)
57
#include <uuid/uuid.h>
58
#else
59
/* TODO: move uuid emulation to some central place in QEMU. */
60
#include "sysemu.h"     /* UUID_FMT */
61
typedef unsigned char uuid_t[16];
62
void uuid_generate(uuid_t out);
63
int uuid_is_null(const uuid_t uu);
64
void uuid_unparse(const uuid_t uu, char *out);
65
#endif
66

    
67
/* Code configuration options. */
68

    
69
/* Enable debug messages. */
70
//~ #define CONFIG_VDI_DEBUG
71

    
72
/* Support write operations on VDI images. */
73
#define CONFIG_VDI_WRITE
74

    
75
/* Support non-standard block (cluster) size. This is untested.
76
 * Maybe it will be needed for very large images.
77
 */
78
//~ #define CONFIG_VDI_BLOCK_SIZE
79

    
80
/* Support static (fixed, pre-allocated) images. */
81
#define CONFIG_VDI_STATIC_IMAGE
82

    
83
/* Command line option for static images. */
84
#define BLOCK_OPT_STATIC "static"
85

    
86
#define KiB     1024
87
#define MiB     (KiB * KiB)
88

    
89
#define SECTOR_SIZE 512
90
#define DEFAULT_CLUSTER_SIZE (1 * MiB)
91

    
92
#if defined(CONFIG_VDI_DEBUG)
93
#define logout(fmt, ...) \
94
                fprintf(stderr, "vdi\t%-24s" fmt, __func__, ##__VA_ARGS__)
95
#else
96
#define logout(fmt, ...) ((void)0)
97
#endif
98

    
99
/* Image signature. */
100
#define VDI_SIGNATURE 0xbeda107f
101

    
102
/* Image version. */
103
#define VDI_VERSION_1_1 0x00010001
104

    
105
/* Image type. */
106
#define VDI_TYPE_DYNAMIC 1
107
#define VDI_TYPE_STATIC  2
108

    
109
/* Innotek / SUN images use these strings in header.text:
110
 * "<<< innotek VirtualBox Disk Image >>>\n"
111
 * "<<< Sun xVM VirtualBox Disk Image >>>\n"
112
 * "<<< Sun VirtualBox Disk Image >>>\n"
113
 * The value does not matter, so QEMU created images use a different text.
114
 */
115
#define VDI_TEXT "<<< QEMU VM Virtual Disk Image >>>\n"
116

    
117
/* A never-allocated block; semantically arbitrary content. */
118
#define VDI_UNALLOCATED 0xffffffffU
119

    
120
/* A discarded (no longer allocated) block; semantically zero-filled. */
121
#define VDI_DISCARDED   0xfffffffeU
122

    
123
#define VDI_IS_ALLOCATED(X) ((X) < VDI_DISCARDED)
124

    
125
#if !defined(CONFIG_UUID)
126
void uuid_generate(uuid_t out)
127
{
128
    memset(out, 0, sizeof(uuid_t));
129
}
130

    
131
int uuid_is_null(const uuid_t uu)
132
{
133
    uuid_t null_uuid = { 0 };
134
    return memcmp(uu, null_uuid, sizeof(uuid_t)) == 0;
135
}
136

    
137
void uuid_unparse(const uuid_t uu, char *out)
138
{
139
    snprintf(out, 37, UUID_FMT,
140
            uu[0], uu[1], uu[2], uu[3], uu[4], uu[5], uu[6], uu[7],
141
            uu[8], uu[9], uu[10], uu[11], uu[12], uu[13], uu[14], uu[15]);
142
}
143
#endif
144

    
145
typedef struct {
146
    BlockDriverAIOCB common;
147
    int64_t sector_num;
148
    QEMUIOVector *qiov;
149
    uint8_t *buf;
150
    /* Total number of sectors. */
151
    int nb_sectors;
152
    /* Number of sectors for current AIO. */
153
    int n_sectors;
154
    /* New allocated block map entry. */
155
    uint32_t bmap_first;
156
    uint32_t bmap_last;
157
    /* Buffer for new allocated block. */
158
    void *block_buffer;
159
    void *orig_buf;
160
    bool is_write;
161
    int header_modified;
162
    BlockDriverAIOCB *hd_aiocb;
163
    struct iovec hd_iov;
164
    QEMUIOVector hd_qiov;
165
    QEMUBH *bh;
166
} VdiAIOCB;
167

    
168
typedef struct {
169
    char text[0x40];
170
    uint32_t signature;
171
    uint32_t version;
172
    uint32_t header_size;
173
    uint32_t image_type;
174
    uint32_t image_flags;
175
    char description[256];
176
    uint32_t offset_bmap;
177
    uint32_t offset_data;
178
    uint32_t cylinders;         /* disk geometry, unused here */
179
    uint32_t heads;             /* disk geometry, unused here */
180
    uint32_t sectors;           /* disk geometry, unused here */
181
    uint32_t sector_size;
182
    uint32_t unused1;
183
    uint64_t disk_size;
184
    uint32_t block_size;
185
    uint32_t block_extra;       /* unused here */
186
    uint32_t blocks_in_image;
187
    uint32_t blocks_allocated;
188
    uuid_t uuid_image;
189
    uuid_t uuid_last_snap;
190
    uuid_t uuid_link;
191
    uuid_t uuid_parent;
192
    uint64_t unused2[7];
193
} VdiHeader;
194

    
195
typedef struct {
196
    /* The block map entries are little endian (even in memory). */
197
    uint32_t *bmap;
198
    /* Size of block (bytes). */
199
    uint32_t block_size;
200
    /* Size of block (sectors). */
201
    uint32_t block_sectors;
202
    /* First sector of block map. */
203
    uint32_t bmap_sector;
204
    /* VDI header (converted to host endianness). */
205
    VdiHeader header;
206
} BDRVVdiState;
207

    
208
/* Change UUID from little endian (IPRT = VirtualBox format) to big endian
209
 * format (network byte order, standard, see RFC 4122) and vice versa.
210
 */
211
static void uuid_convert(uuid_t uuid)
212
{
213
    bswap32s((uint32_t *)&uuid[0]);
214
    bswap16s((uint16_t *)&uuid[4]);
215
    bswap16s((uint16_t *)&uuid[6]);
216
}
217

    
218
static void vdi_header_to_cpu(VdiHeader *header)
219
{
220
    le32_to_cpus(&header->signature);
221
    le32_to_cpus(&header->version);
222
    le32_to_cpus(&header->header_size);
223
    le32_to_cpus(&header->image_type);
224
    le32_to_cpus(&header->image_flags);
225
    le32_to_cpus(&header->offset_bmap);
226
    le32_to_cpus(&header->offset_data);
227
    le32_to_cpus(&header->cylinders);
228
    le32_to_cpus(&header->heads);
229
    le32_to_cpus(&header->sectors);
230
    le32_to_cpus(&header->sector_size);
231
    le64_to_cpus(&header->disk_size);
232
    le32_to_cpus(&header->block_size);
233
    le32_to_cpus(&header->block_extra);
234
    le32_to_cpus(&header->blocks_in_image);
235
    le32_to_cpus(&header->blocks_allocated);
236
    uuid_convert(header->uuid_image);
237
    uuid_convert(header->uuid_last_snap);
238
    uuid_convert(header->uuid_link);
239
    uuid_convert(header->uuid_parent);
240
}
241

    
242
static void vdi_header_to_le(VdiHeader *header)
243
{
244
    cpu_to_le32s(&header->signature);
245
    cpu_to_le32s(&header->version);
246
    cpu_to_le32s(&header->header_size);
247
    cpu_to_le32s(&header->image_type);
248
    cpu_to_le32s(&header->image_flags);
249
    cpu_to_le32s(&header->offset_bmap);
250
    cpu_to_le32s(&header->offset_data);
251
    cpu_to_le32s(&header->cylinders);
252
    cpu_to_le32s(&header->heads);
253
    cpu_to_le32s(&header->sectors);
254
    cpu_to_le32s(&header->sector_size);
255
    cpu_to_le64s(&header->disk_size);
256
    cpu_to_le32s(&header->block_size);
257
    cpu_to_le32s(&header->block_extra);
258
    cpu_to_le32s(&header->blocks_in_image);
259
    cpu_to_le32s(&header->blocks_allocated);
260
    cpu_to_le32s(&header->blocks_allocated);
261
    uuid_convert(header->uuid_image);
262
    uuid_convert(header->uuid_last_snap);
263
    uuid_convert(header->uuid_link);
264
    uuid_convert(header->uuid_parent);
265
}
266

    
267
#if defined(CONFIG_VDI_DEBUG)
268
static void vdi_header_print(VdiHeader *header)
269
{
270
    char uuid[37];
271
    logout("text        %s", header->text);
272
    logout("signature   0x%04x\n", header->signature);
273
    logout("header size 0x%04x\n", header->header_size);
274
    logout("image type  0x%04x\n", header->image_type);
275
    logout("image flags 0x%04x\n", header->image_flags);
276
    logout("description %s\n", header->description);
277
    logout("offset bmap 0x%04x\n", header->offset_bmap);
278
    logout("offset data 0x%04x\n", header->offset_data);
279
    logout("cylinders   0x%04x\n", header->cylinders);
280
    logout("heads       0x%04x\n", header->heads);
281
    logout("sectors     0x%04x\n", header->sectors);
282
    logout("sector size 0x%04x\n", header->sector_size);
283
    logout("image size  0x%" PRIx64 " B (%" PRIu64 " MiB)\n",
284
           header->disk_size, header->disk_size / MiB);
285
    logout("block size  0x%04x\n", header->block_size);
286
    logout("block extra 0x%04x\n", header->block_extra);
287
    logout("blocks tot. 0x%04x\n", header->blocks_in_image);
288
    logout("blocks all. 0x%04x\n", header->blocks_allocated);
289
    uuid_unparse(header->uuid_image, uuid);
290
    logout("uuid image  %s\n", uuid);
291
    uuid_unparse(header->uuid_last_snap, uuid);
292
    logout("uuid snap   %s\n", uuid);
293
    uuid_unparse(header->uuid_link, uuid);
294
    logout("uuid link   %s\n", uuid);
295
    uuid_unparse(header->uuid_parent, uuid);
296
    logout("uuid parent %s\n", uuid);
297
}
298
#endif
299

    
300
static int vdi_check(BlockDriverState *bs, BdrvCheckResult *res)
301
{
302
    /* TODO: additional checks possible. */
303
    BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
304
    uint32_t blocks_allocated = 0;
305
    uint32_t block;
306
    uint32_t *bmap;
307
    logout("\n");
308

    
309
    bmap = g_malloc(s->header.blocks_in_image * sizeof(uint32_t));
310
    memset(bmap, 0xff, s->header.blocks_in_image * sizeof(uint32_t));
311

    
312
    /* Check block map and value of blocks_allocated. */
313
    for (block = 0; block < s->header.blocks_in_image; block++) {
314
        uint32_t bmap_entry = le32_to_cpu(s->bmap[block]);
315
        if (VDI_IS_ALLOCATED(bmap_entry)) {
316
            if (bmap_entry < s->header.blocks_in_image) {
317
                blocks_allocated++;
318
                if (!VDI_IS_ALLOCATED(bmap[bmap_entry])) {
319
                    bmap[bmap_entry] = bmap_entry;
320
                } else {
321
                    fprintf(stderr, "ERROR: block index %" PRIu32
322
                            " also used by %" PRIu32 "\n", bmap[bmap_entry], bmap_entry);
323
                    res->corruptions++;
324
                }
325
            } else {
326
                fprintf(stderr, "ERROR: block index %" PRIu32
327
                        " too large, is %" PRIu32 "\n", block, bmap_entry);
328
                res->corruptions++;
329
            }
330
        }
331
    }
332
    if (blocks_allocated != s->header.blocks_allocated) {
333
        fprintf(stderr, "ERROR: allocated blocks mismatch, is %" PRIu32
334
               ", should be %" PRIu32 "\n",
335
               blocks_allocated, s->header.blocks_allocated);
336
        res->corruptions++;
337
    }
338

    
339
    g_free(bmap);
340

    
341
    return 0;
342
}
343

    
344
static int vdi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
345
{
346
    /* TODO: vdi_get_info would be needed for machine snapshots.
347
       vm_state_offset is still missing. */
348
    BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
349
    logout("\n");
350
    bdi->cluster_size = s->block_size;
351
    bdi->vm_state_offset = 0;
352
    return 0;
353
}
354

    
355
static int vdi_make_empty(BlockDriverState *bs)
356
{
357
    /* TODO: missing code. */
358
    logout("\n");
359
    /* The return value for missing code must be 0, see block.c. */
360
    return 0;
361
}
362

    
363
static int vdi_probe(const uint8_t *buf, int buf_size, const char *filename)
364
{
365
    const VdiHeader *header = (const VdiHeader *)buf;
366
    int result = 0;
367

    
368
    logout("\n");
369

    
370
    if (buf_size < sizeof(*header)) {
371
        /* Header too small, no VDI. */
372
    } else if (le32_to_cpu(header->signature) == VDI_SIGNATURE) {
373
        result = 100;
374
    }
375

    
376
    if (result == 0) {
377
        logout("no vdi image\n");
378
    } else {
379
        logout("%s", header->text);
380
    }
381

    
382
    return result;
383
}
384

    
385
static int vdi_open(BlockDriverState *bs, int flags)
386
{
387
    BDRVVdiState *s = bs->opaque;
388
    VdiHeader header;
389
    size_t bmap_size;
390

    
391
    logout("\n");
392

    
393
    if (bdrv_read(bs->file, 0, (uint8_t *)&header, 1) < 0) {
394
        goto fail;
395
    }
396

    
397
    vdi_header_to_cpu(&header);
398
#if defined(CONFIG_VDI_DEBUG)
399
    vdi_header_print(&header);
400
#endif
401

    
402
    if (header.disk_size % SECTOR_SIZE != 0) {
403
        /* 'VBoxManage convertfromraw' can create images with odd disk sizes.
404
           We accept them but round the disk size to the next multiple of
405
           SECTOR_SIZE. */
406
        logout("odd disk size %" PRIu64 " B, round up\n", header.disk_size);
407
        header.disk_size += SECTOR_SIZE - 1;
408
        header.disk_size &= ~(SECTOR_SIZE - 1);
409
    }
410

    
411
    if (header.version != VDI_VERSION_1_1) {
412
        logout("unsupported version %u.%u\n",
413
               header.version >> 16, header.version & 0xffff);
414
        goto fail;
415
    } else if (header.offset_bmap % SECTOR_SIZE != 0) {
416
        /* We only support block maps which start on a sector boundary. */
417
        logout("unsupported block map offset 0x%x B\n", header.offset_bmap);
418
        goto fail;
419
    } else if (header.offset_data % SECTOR_SIZE != 0) {
420
        /* We only support data blocks which start on a sector boundary. */
421
        logout("unsupported data offset 0x%x B\n", header.offset_data);
422
        goto fail;
423
    } else if (header.sector_size != SECTOR_SIZE) {
424
        logout("unsupported sector size %u B\n", header.sector_size);
425
        goto fail;
426
    } else if (header.block_size != 1 * MiB) {
427
        logout("unsupported block size %u B\n", header.block_size);
428
        goto fail;
429
    } else if (header.disk_size >
430
               (uint64_t)header.blocks_in_image * header.block_size) {
431
        logout("unsupported disk size %" PRIu64 " B\n", header.disk_size);
432
        goto fail;
433
    } else if (!uuid_is_null(header.uuid_link)) {
434
        logout("link uuid != 0, unsupported\n");
435
        goto fail;
436
    } else if (!uuid_is_null(header.uuid_parent)) {
437
        logout("parent uuid != 0, unsupported\n");
438
        goto fail;
439
    }
440

    
441
    bs->total_sectors = header.disk_size / SECTOR_SIZE;
442

    
443
    s->block_size = header.block_size;
444
    s->block_sectors = header.block_size / SECTOR_SIZE;
445
    s->bmap_sector = header.offset_bmap / SECTOR_SIZE;
446
    s->header = header;
447

    
448
    bmap_size = header.blocks_in_image * sizeof(uint32_t);
449
    bmap_size = (bmap_size + SECTOR_SIZE - 1) / SECTOR_SIZE;
450
    if (bmap_size > 0) {
451
        s->bmap = g_malloc(bmap_size * SECTOR_SIZE);
452
    }
453
    if (bdrv_read(bs->file, s->bmap_sector, (uint8_t *)s->bmap, bmap_size) < 0) {
454
        goto fail_free_bmap;
455
    }
456

    
457
    return 0;
458

    
459
 fail_free_bmap:
460
    g_free(s->bmap);
461

    
462
 fail:
463
    return -1;
464
}
465

    
466
static int vdi_is_allocated(BlockDriverState *bs, int64_t sector_num,
467
                             int nb_sectors, int *pnum)
468
{
469
    /* TODO: Check for too large sector_num (in bdrv_is_allocated or here). */
470
    BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
471
    size_t bmap_index = sector_num / s->block_sectors;
472
    size_t sector_in_block = sector_num % s->block_sectors;
473
    int n_sectors = s->block_sectors - sector_in_block;
474
    uint32_t bmap_entry = le32_to_cpu(s->bmap[bmap_index]);
475
    logout("%p, %" PRId64 ", %d, %p\n", bs, sector_num, nb_sectors, pnum);
476
    if (n_sectors > nb_sectors) {
477
        n_sectors = nb_sectors;
478
    }
479
    *pnum = n_sectors;
480
    return VDI_IS_ALLOCATED(bmap_entry);
481
}
482

    
483
static void vdi_aio_cancel(BlockDriverAIOCB *blockacb)
484
{
485
    /* TODO: This code is untested. How can I get it executed? */
486
    VdiAIOCB *acb = container_of(blockacb, VdiAIOCB, common);
487
    logout("\n");
488
    if (acb->hd_aiocb) {
489
        bdrv_aio_cancel(acb->hd_aiocb);
490
    }
491
    qemu_aio_release(acb);
492
}
493

    
494
static AIOPool vdi_aio_pool = {
495
    .aiocb_size = sizeof(VdiAIOCB),
496
    .cancel = vdi_aio_cancel,
497
};
498

    
499
static VdiAIOCB *vdi_aio_setup(BlockDriverState *bs, int64_t sector_num,
500
        QEMUIOVector *qiov, int nb_sectors,
501
        BlockDriverCompletionFunc *cb, void *opaque, int is_write)
502
{
503
    VdiAIOCB *acb;
504

    
505
    logout("%p, %" PRId64 ", %p, %d, %p, %p, %d\n",
506
           bs, sector_num, qiov, nb_sectors, cb, opaque, is_write);
507

    
508
    acb = qemu_aio_get(&vdi_aio_pool, bs, cb, opaque);
509
    if (acb) {
510
        acb->hd_aiocb = NULL;
511
        acb->sector_num = sector_num;
512
        acb->qiov = qiov;
513
        acb->is_write = is_write;
514

    
515
        if (qiov->niov > 1) {
516
            acb->buf = qemu_blockalign(bs, qiov->size);
517
            acb->orig_buf = acb->buf;
518
            if (is_write) {
519
                qemu_iovec_to_buffer(qiov, acb->buf);
520
            }
521
        } else {
522
            acb->buf = (uint8_t *)qiov->iov->iov_base;
523
        }
524
        acb->nb_sectors = nb_sectors;
525
        acb->n_sectors = 0;
526
        acb->bmap_first = VDI_UNALLOCATED;
527
        acb->bmap_last = VDI_UNALLOCATED;
528
        acb->block_buffer = NULL;
529
        acb->header_modified = 0;
530
    }
531
    return acb;
532
}
533

    
534
static int vdi_schedule_bh(QEMUBHFunc *cb, VdiAIOCB *acb)
535
{
536
    logout("\n");
537

    
538
    if (acb->bh) {
539
        return -EIO;
540
    }
541

    
542
    acb->bh = qemu_bh_new(cb, acb);
543
    if (!acb->bh) {
544
        return -EIO;
545
    }
546

    
547
    qemu_bh_schedule(acb->bh);
548

    
549
    return 0;
550
}
551

    
552
static void vdi_aio_read_cb(void *opaque, int ret);
553
static void vdi_aio_write_cb(void *opaque, int ret);
554

    
555
static void vdi_aio_rw_bh(void *opaque)
556
{
557
    VdiAIOCB *acb = opaque;
558
    logout("\n");
559
    qemu_bh_delete(acb->bh);
560
    acb->bh = NULL;
561

    
562
    if (acb->is_write) {
563
        vdi_aio_write_cb(opaque, 0);
564
    } else {
565
        vdi_aio_read_cb(opaque, 0);
566
    }
567
}
568

    
569
static void vdi_aio_read_cb(void *opaque, int ret)
570
{
571
    VdiAIOCB *acb = opaque;
572
    BlockDriverState *bs = acb->common.bs;
573
    BDRVVdiState *s = bs->opaque;
574
    uint32_t bmap_entry;
575
    uint32_t block_index;
576
    uint32_t sector_in_block;
577
    uint32_t n_sectors;
578

    
579
    logout("%u sectors read\n", acb->n_sectors);
580

    
581
    acb->hd_aiocb = NULL;
582

    
583
    if (ret < 0) {
584
        goto done;
585
    }
586

    
587
    acb->nb_sectors -= acb->n_sectors;
588

    
589
    if (acb->nb_sectors == 0) {
590
        /* request completed */
591
        ret = 0;
592
        goto done;
593
    }
594

    
595
    acb->sector_num += acb->n_sectors;
596
    acb->buf += acb->n_sectors * SECTOR_SIZE;
597

    
598
    block_index = acb->sector_num / s->block_sectors;
599
    sector_in_block = acb->sector_num % s->block_sectors;
600
    n_sectors = s->block_sectors - sector_in_block;
601
    if (n_sectors > acb->nb_sectors) {
602
        n_sectors = acb->nb_sectors;
603
    }
604

    
605
    logout("will read %u sectors starting at sector %" PRIu64 "\n",
606
           n_sectors, acb->sector_num);
607

    
608
    /* prepare next AIO request */
609
    acb->n_sectors = n_sectors;
610
    bmap_entry = le32_to_cpu(s->bmap[block_index]);
611
    if (!VDI_IS_ALLOCATED(bmap_entry)) {
612
        /* Block not allocated, return zeros, no need to wait. */
613
        memset(acb->buf, 0, n_sectors * SECTOR_SIZE);
614
        ret = vdi_schedule_bh(vdi_aio_rw_bh, acb);
615
        if (ret < 0) {
616
            goto done;
617
        }
618
    } else {
619
        uint64_t offset = s->header.offset_data / SECTOR_SIZE +
620
                          (uint64_t)bmap_entry * s->block_sectors +
621
                          sector_in_block;
622
        acb->hd_iov.iov_base = (void *)acb->buf;
623
        acb->hd_iov.iov_len = n_sectors * SECTOR_SIZE;
624
        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
625
        acb->hd_aiocb = bdrv_aio_readv(bs->file, offset, &acb->hd_qiov,
626
                                       n_sectors, vdi_aio_read_cb, acb);
627
        if (acb->hd_aiocb == NULL) {
628
            ret = -EIO;
629
            goto done;
630
        }
631
    }
632
    return;
633
done:
634
    if (acb->qiov->niov > 1) {
635
        qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
636
        qemu_vfree(acb->orig_buf);
637
    }
638
    acb->common.cb(acb->common.opaque, ret);
639
    qemu_aio_release(acb);
640
}
641

    
642
static BlockDriverAIOCB *vdi_aio_readv(BlockDriverState *bs,
643
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
644
        BlockDriverCompletionFunc *cb, void *opaque)
645
{
646
    VdiAIOCB *acb;
647
    int ret;
648

    
649
    logout("\n");
650
    acb = vdi_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
651
    if (!acb) {
652
        return NULL;
653
    }
654

    
655
    ret = vdi_schedule_bh(vdi_aio_rw_bh, acb);
656
    if (ret < 0) {
657
        if (acb->qiov->niov > 1) {
658
            qemu_vfree(acb->orig_buf);
659
        }
660
        qemu_aio_release(acb);
661
        return NULL;
662
    }
663

    
664
    return &acb->common;
665
}
666

    
667
static void vdi_aio_write_cb(void *opaque, int ret)
668
{
669
    VdiAIOCB *acb = opaque;
670
    BlockDriverState *bs = acb->common.bs;
671
    BDRVVdiState *s = bs->opaque;
672
    uint32_t bmap_entry;
673
    uint32_t block_index;
674
    uint32_t sector_in_block;
675
    uint32_t n_sectors;
676

    
677
    acb->hd_aiocb = NULL;
678

    
679
    if (ret < 0) {
680
        goto done;
681
    }
682

    
683
    acb->nb_sectors -= acb->n_sectors;
684
    acb->sector_num += acb->n_sectors;
685
    acb->buf += acb->n_sectors * SECTOR_SIZE;
686

    
687
    if (acb->nb_sectors == 0) {
688
        logout("finished data write\n");
689
        acb->n_sectors = 0;
690
        if (acb->header_modified) {
691
            VdiHeader *header = acb->block_buffer;
692
            logout("now writing modified header\n");
693
            assert(VDI_IS_ALLOCATED(acb->bmap_first));
694
            *header = s->header;
695
            vdi_header_to_le(header);
696
            acb->header_modified = 0;
697
            acb->hd_iov.iov_base = acb->block_buffer;
698
            acb->hd_iov.iov_len = SECTOR_SIZE;
699
            qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
700
            acb->hd_aiocb = bdrv_aio_writev(bs->file, 0, &acb->hd_qiov, 1,
701
                                            vdi_aio_write_cb, acb);
702
            if (acb->hd_aiocb == NULL) {
703
                ret = -EIO;
704
                goto done;
705
            }
706
            return;
707
        } else if (VDI_IS_ALLOCATED(acb->bmap_first)) {
708
            /* One or more new blocks were allocated. */
709
            uint64_t offset;
710
            uint32_t bmap_first;
711
            uint32_t bmap_last;
712
            g_free(acb->block_buffer);
713
            acb->block_buffer = NULL;
714
            bmap_first = acb->bmap_first;
715
            bmap_last = acb->bmap_last;
716
            logout("now writing modified block map entry %u...%u\n",
717
                   bmap_first, bmap_last);
718
            /* Write modified sectors from block map. */
719
            bmap_first /= (SECTOR_SIZE / sizeof(uint32_t));
720
            bmap_last /= (SECTOR_SIZE / sizeof(uint32_t));
721
            n_sectors = bmap_last - bmap_first + 1;
722
            offset = s->bmap_sector + bmap_first;
723
            acb->bmap_first = VDI_UNALLOCATED;
724
            acb->hd_iov.iov_base = (void *)((uint8_t *)&s->bmap[0] +
725
                                            bmap_first * SECTOR_SIZE);
726
            acb->hd_iov.iov_len = n_sectors * SECTOR_SIZE;
727
            qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
728
            logout("will write %u block map sectors starting from entry %u\n",
729
                   n_sectors, bmap_first);
730
            acb->hd_aiocb = bdrv_aio_writev(bs->file, offset, &acb->hd_qiov,
731
                                            n_sectors, vdi_aio_write_cb, acb);
732
            if (acb->hd_aiocb == NULL) {
733
                ret = -EIO;
734
                goto done;
735
            }
736
            return;
737
        }
738
        ret = 0;
739
        goto done;
740
    }
741

    
742
    logout("%u sectors written\n", acb->n_sectors);
743

    
744
    block_index = acb->sector_num / s->block_sectors;
745
    sector_in_block = acb->sector_num % s->block_sectors;
746
    n_sectors = s->block_sectors - sector_in_block;
747
    if (n_sectors > acb->nb_sectors) {
748
        n_sectors = acb->nb_sectors;
749
    }
750

    
751
    logout("will write %u sectors starting at sector %" PRIu64 "\n",
752
           n_sectors, acb->sector_num);
753

    
754
    /* prepare next AIO request */
755
    acb->n_sectors = n_sectors;
756
    bmap_entry = le32_to_cpu(s->bmap[block_index]);
757
    if (!VDI_IS_ALLOCATED(bmap_entry)) {
758
        /* Allocate new block and write to it. */
759
        uint64_t offset;
760
        uint8_t *block;
761
        bmap_entry = s->header.blocks_allocated;
762
        s->bmap[block_index] = cpu_to_le32(bmap_entry);
763
        s->header.blocks_allocated++;
764
        offset = s->header.offset_data / SECTOR_SIZE +
765
                 (uint64_t)bmap_entry * s->block_sectors;
766
        block = acb->block_buffer;
767
        if (block == NULL) {
768
            block = g_malloc0(s->block_size);
769
            acb->block_buffer = block;
770
            acb->bmap_first = block_index;
771
            assert(!acb->header_modified);
772
            acb->header_modified = 1;
773
        }
774
        acb->bmap_last = block_index;
775
        memcpy(block + sector_in_block * SECTOR_SIZE,
776
               acb->buf, n_sectors * SECTOR_SIZE);
777
        acb->hd_iov.iov_base = (void *)block;
778
        acb->hd_iov.iov_len = s->block_size;
779
        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
780
        acb->hd_aiocb = bdrv_aio_writev(bs->file, offset,
781
                                        &acb->hd_qiov, s->block_sectors,
782
                                        vdi_aio_write_cb, acb);
783
        if (acb->hd_aiocb == NULL) {
784
            ret = -EIO;
785
            goto done;
786
        }
787
    } else {
788
        uint64_t offset = s->header.offset_data / SECTOR_SIZE +
789
                          (uint64_t)bmap_entry * s->block_sectors +
790
                          sector_in_block;
791
        acb->hd_iov.iov_base = (void *)acb->buf;
792
        acb->hd_iov.iov_len = n_sectors * SECTOR_SIZE;
793
        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
794
        acb->hd_aiocb = bdrv_aio_writev(bs->file, offset, &acb->hd_qiov,
795
                                        n_sectors, vdi_aio_write_cb, acb);
796
        if (acb->hd_aiocb == NULL) {
797
            ret = -EIO;
798
            goto done;
799
        }
800
    }
801

    
802
    return;
803

    
804
done:
805
    if (acb->qiov->niov > 1) {
806
        qemu_vfree(acb->orig_buf);
807
    }
808
    acb->common.cb(acb->common.opaque, ret);
809
    qemu_aio_release(acb);
810
}
811

    
812
static BlockDriverAIOCB *vdi_aio_writev(BlockDriverState *bs,
813
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
814
        BlockDriverCompletionFunc *cb, void *opaque)
815
{
816
    VdiAIOCB *acb;
817
    int ret;
818

    
819
    logout("\n");
820
    acb = vdi_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
821
    if (!acb) {
822
        return NULL;
823
    }
824

    
825
    ret = vdi_schedule_bh(vdi_aio_rw_bh, acb);
826
    if (ret < 0) {
827
        if (acb->qiov->niov > 1) {
828
            qemu_vfree(acb->orig_buf);
829
        }
830
        qemu_aio_release(acb);
831
        return NULL;
832
    }
833

    
834
    return &acb->common;
835
}
836

    
837
static int vdi_create(const char *filename, QEMUOptionParameter *options)
838
{
839
    int fd;
840
    int result = 0;
841
    uint64_t bytes = 0;
842
    uint32_t blocks;
843
    size_t block_size = DEFAULT_CLUSTER_SIZE;
844
    uint32_t image_type = VDI_TYPE_DYNAMIC;
845
    VdiHeader header;
846
    size_t i;
847
    size_t bmap_size;
848
    uint32_t *bmap;
849

    
850
    logout("\n");
851

    
852
    /* Read out options. */
853
    while (options && options->name) {
854
        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
855
            bytes = options->value.n;
856
#if defined(CONFIG_VDI_BLOCK_SIZE)
857
        } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
858
            if (options->value.n) {
859
                /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */
860
                block_size = options->value.n;
861
            }
862
#endif
863
#if defined(CONFIG_VDI_STATIC_IMAGE)
864
        } else if (!strcmp(options->name, BLOCK_OPT_STATIC)) {
865
            if (options->value.n) {
866
                image_type = VDI_TYPE_STATIC;
867
            }
868
#endif
869
        }
870
        options++;
871
    }
872

    
873
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
874
              0644);
875
    if (fd < 0) {
876
        return -errno;
877
    }
878

    
879
    /* We need enough blocks to store the given disk size,
880
       so always round up. */
881
    blocks = (bytes + block_size - 1) / block_size;
882

    
883
    bmap_size = blocks * sizeof(uint32_t);
884
    bmap_size = ((bmap_size + SECTOR_SIZE - 1) & ~(SECTOR_SIZE -1));
885

    
886
    memset(&header, 0, sizeof(header));
887
    pstrcpy(header.text, sizeof(header.text), VDI_TEXT);
888
    header.signature = VDI_SIGNATURE;
889
    header.version = VDI_VERSION_1_1;
890
    header.header_size = 0x180;
891
    header.image_type = image_type;
892
    header.offset_bmap = 0x200;
893
    header.offset_data = 0x200 + bmap_size;
894
    header.sector_size = SECTOR_SIZE;
895
    header.disk_size = bytes;
896
    header.block_size = block_size;
897
    header.blocks_in_image = blocks;
898
    if (image_type == VDI_TYPE_STATIC) {
899
        header.blocks_allocated = blocks;
900
    }
901
    uuid_generate(header.uuid_image);
902
    uuid_generate(header.uuid_last_snap);
903
    /* There is no need to set header.uuid_link or header.uuid_parent here. */
904
#if defined(CONFIG_VDI_DEBUG)
905
    vdi_header_print(&header);
906
#endif
907
    vdi_header_to_le(&header);
908
    if (write(fd, &header, sizeof(header)) < 0) {
909
        result = -errno;
910
    }
911

    
912
    bmap = NULL;
913
    if (bmap_size > 0) {
914
        bmap = (uint32_t *)g_malloc0(bmap_size);
915
    }
916
    for (i = 0; i < blocks; i++) {
917
        if (image_type == VDI_TYPE_STATIC) {
918
            bmap[i] = i;
919
        } else {
920
            bmap[i] = VDI_UNALLOCATED;
921
        }
922
    }
923
    if (write(fd, bmap, bmap_size) < 0) {
924
        result = -errno;
925
    }
926
    g_free(bmap);
927
    if (image_type == VDI_TYPE_STATIC) {
928
        if (ftruncate(fd, sizeof(header) + bmap_size + blocks * block_size)) {
929
            result = -errno;
930
        }
931
    }
932

    
933
    if (close(fd) < 0) {
934
        result = -errno;
935
    }
936

    
937
    return result;
938
}
939

    
940
static void vdi_close(BlockDriverState *bs)
941
{
942
}
943

    
944
static coroutine_fn int vdi_co_flush(BlockDriverState *bs)
945
{
946
    logout("\n");
947
    return bdrv_co_flush(bs->file);
948
}
949

    
950

    
951
static QEMUOptionParameter vdi_create_options[] = {
952
    {
953
        .name = BLOCK_OPT_SIZE,
954
        .type = OPT_SIZE,
955
        .help = "Virtual disk size"
956
    },
957
#if defined(CONFIG_VDI_BLOCK_SIZE)
958
    {
959
        .name = BLOCK_OPT_CLUSTER_SIZE,
960
        .type = OPT_SIZE,
961
        .help = "VDI cluster (block) size",
962
        .value = { .n = DEFAULT_CLUSTER_SIZE },
963
    },
964
#endif
965
#if defined(CONFIG_VDI_STATIC_IMAGE)
966
    {
967
        .name = BLOCK_OPT_STATIC,
968
        .type = OPT_FLAG,
969
        .help = "VDI static (pre-allocated) image"
970
    },
971
#endif
972
    /* TODO: An additional option to set UUID values might be useful. */
973
    { NULL }
974
};
975

    
976
static BlockDriver bdrv_vdi = {
977
    .format_name = "vdi",
978
    .instance_size = sizeof(BDRVVdiState),
979
    .bdrv_probe = vdi_probe,
980
    .bdrv_open = vdi_open,
981
    .bdrv_close = vdi_close,
982
    .bdrv_create = vdi_create,
983
    .bdrv_co_flush = vdi_co_flush,
984
    .bdrv_is_allocated = vdi_is_allocated,
985
    .bdrv_make_empty = vdi_make_empty,
986

    
987
    .bdrv_aio_readv = vdi_aio_readv,
988
#if defined(CONFIG_VDI_WRITE)
989
    .bdrv_aio_writev = vdi_aio_writev,
990
#endif
991

    
992
    .bdrv_get_info = vdi_get_info,
993

    
994
    .create_options = vdi_create_options,
995
    .bdrv_check = vdi_check,
996
};
997

    
998
static void bdrv_vdi_init(void)
999
{
1000
    logout("\n");
1001
    bdrv_register(&bdrv_vdi);
1002
}
1003

    
1004
block_init(bdrv_vdi_init);