Statistics
| Branch: | Revision:

root / block / vmdk.c @ 91b85bd3

History | View | Annotate | Download (32.2 kB)

1
/*
2
 * Block driver for the VMDK format
3
 *
4
 * Copyright (c) 2004 Fabrice Bellard
5
 * Copyright (c) 2005 Filip Navara
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 */
25

    
26
#include "qemu-common.h"
27
#include "block_int.h"
28
#include "module.h"
29

    
30
#define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
31
#define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
32

    
33
typedef struct {
34
    uint32_t version;
35
    uint32_t flags;
36
    uint32_t disk_sectors;
37
    uint32_t granularity;
38
    uint32_t l1dir_offset;
39
    uint32_t l1dir_size;
40
    uint32_t file_sectors;
41
    uint32_t cylinders;
42
    uint32_t heads;
43
    uint32_t sectors_per_track;
44
} VMDK3Header;
45

    
46
typedef struct {
47
    uint32_t version;
48
    uint32_t flags;
49
    int64_t capacity;
50
    int64_t granularity;
51
    int64_t desc_offset;
52
    int64_t desc_size;
53
    int32_t num_gtes_per_gte;
54
    int64_t rgd_offset;
55
    int64_t gd_offset;
56
    int64_t grain_offset;
57
    char filler[1];
58
    char check_bytes[4];
59
} __attribute__((packed)) VMDK4Header;
60

    
61
#define L2_CACHE_SIZE 16
62

    
63
typedef struct VmdkExtent {
64
    BlockDriverState *file;
65
    bool flat;
66
    int64_t sectors;
67
    int64_t end_sector;
68
    int64_t l1_table_offset;
69
    int64_t l1_backup_table_offset;
70
    uint32_t *l1_table;
71
    uint32_t *l1_backup_table;
72
    unsigned int l1_size;
73
    uint32_t l1_entry_sectors;
74

    
75
    unsigned int l2_size;
76
    uint32_t *l2_cache;
77
    uint32_t l2_cache_offsets[L2_CACHE_SIZE];
78
    uint32_t l2_cache_counts[L2_CACHE_SIZE];
79

    
80
    unsigned int cluster_sectors;
81
} VmdkExtent;
82

    
83
typedef struct BDRVVmdkState {
84
    int desc_offset;
85
    bool cid_updated;
86
    uint32_t parent_cid;
87
    int num_extents;
88
    /* Extent array with num_extents entries, ascend ordered by address */
89
    VmdkExtent *extents;
90
} BDRVVmdkState;
91

    
92
typedef struct VmdkMetaData {
93
    uint32_t offset;
94
    unsigned int l1_index;
95
    unsigned int l2_index;
96
    unsigned int l2_offset;
97
    int valid;
98
} VmdkMetaData;
99

    
100
static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
101
{
102
    uint32_t magic;
103

    
104
    if (buf_size < 4)
105
        return 0;
106
    magic = be32_to_cpu(*(uint32_t *)buf);
107
    if (magic == VMDK3_MAGIC ||
108
        magic == VMDK4_MAGIC) {
109
        return 100;
110
    } else {
111
        const char *p = (const char *)buf;
112
        const char *end = p + buf_size;
113
        while (p < end) {
114
            if (*p == '#') {
115
                /* skip comment line */
116
                while (p < end && *p != '\n') {
117
                    p++;
118
                }
119
                p++;
120
                continue;
121
            }
122
            if (*p == ' ') {
123
                while (p < end && *p == ' ') {
124
                    p++;
125
                }
126
                /* skip '\r' if windows line endings used. */
127
                if (p < end && *p == '\r') {
128
                    p++;
129
                }
130
                /* only accept blank lines before 'version=' line */
131
                if (p == end || *p != '\n') {
132
                    return 0;
133
                }
134
                p++;
135
                continue;
136
            }
137
            if (end - p >= strlen("version=X\n")) {
138
                if (strncmp("version=1\n", p, strlen("version=1\n")) == 0 ||
139
                    strncmp("version=2\n", p, strlen("version=2\n")) == 0) {
140
                    return 100;
141
                }
142
            }
143
            if (end - p >= strlen("version=X\r\n")) {
144
                if (strncmp("version=1\r\n", p, strlen("version=1\r\n")) == 0 ||
145
                    strncmp("version=2\r\n", p, strlen("version=2\r\n")) == 0) {
146
                    return 100;
147
                }
148
            }
149
            return 0;
150
        }
151
        return 0;
152
    }
153
}
154

    
155
#define CHECK_CID 1
156

    
157
#define SECTOR_SIZE 512
158
#define DESC_SIZE 20*SECTOR_SIZE        // 20 sectors of 512 bytes each
159
#define HEADER_SIZE 512                           // first sector of 512 bytes
160

    
161
static void vmdk_free_extents(BlockDriverState *bs)
162
{
163
    int i;
164
    BDRVVmdkState *s = bs->opaque;
165

    
166
    for (i = 0; i < s->num_extents; i++) {
167
        qemu_free(s->extents[i].l1_table);
168
        qemu_free(s->extents[i].l2_cache);
169
        qemu_free(s->extents[i].l1_backup_table);
170
    }
171
    qemu_free(s->extents);
172
}
173

    
174
static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
175
{
176
    char desc[DESC_SIZE];
177
    uint32_t cid;
178
    const char *p_name, *cid_str;
179
    size_t cid_str_size;
180
    BDRVVmdkState *s = bs->opaque;
181

    
182
    if (bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE) != DESC_SIZE) {
183
        return 0;
184
    }
185

    
186
    if (parent) {
187
        cid_str = "parentCID";
188
        cid_str_size = sizeof("parentCID");
189
    } else {
190
        cid_str = "CID";
191
        cid_str_size = sizeof("CID");
192
    }
193

    
194
    if ((p_name = strstr(desc,cid_str)) != NULL) {
195
        p_name += cid_str_size;
196
        sscanf(p_name,"%x",&cid);
197
    }
198

    
199
    return cid;
200
}
201

    
202
static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
203
{
204
    char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
205
    char *p_name, *tmp_str;
206
    BDRVVmdkState *s = bs->opaque;
207

    
208
    memset(desc, 0, sizeof(desc));
209
    if (bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE) != DESC_SIZE) {
210
        return -EIO;
211
    }
212

    
213
    tmp_str = strstr(desc,"parentCID");
214
    pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
215
    if ((p_name = strstr(desc,"CID")) != NULL) {
216
        p_name += sizeof("CID");
217
        snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
218
        pstrcat(desc, sizeof(desc), tmp_desc);
219
    }
220

    
221
    if (bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE) < 0) {
222
        return -EIO;
223
    }
224
    return 0;
225
}
226

    
227
static int vmdk_is_cid_valid(BlockDriverState *bs)
228
{
229
#ifdef CHECK_CID
230
    BDRVVmdkState *s = bs->opaque;
231
    BlockDriverState *p_bs = bs->backing_hd;
232
    uint32_t cur_pcid;
233

    
234
    if (p_bs) {
235
        cur_pcid = vmdk_read_cid(p_bs,0);
236
        if (s->parent_cid != cur_pcid)
237
            // CID not valid
238
            return 0;
239
    }
240
#endif
241
    // CID valid
242
    return 1;
243
}
244

    
245
static int vmdk_snapshot_create(const char *filename, const char *backing_file)
246
{
247
    int snp_fd, p_fd;
248
    int ret;
249
    uint32_t p_cid;
250
    char *p_name, *gd_buf, *rgd_buf;
251
    const char *real_filename, *temp_str;
252
    VMDK4Header header;
253
    uint32_t gde_entries, gd_size;
254
    int64_t gd_offset, rgd_offset, capacity, gt_size;
255
    char p_desc[DESC_SIZE], s_desc[DESC_SIZE], hdr[HEADER_SIZE];
256
    static const char desc_template[] =
257
    "# Disk DescriptorFile\n"
258
    "version=1\n"
259
    "CID=%x\n"
260
    "parentCID=%x\n"
261
    "createType=\"monolithicSparse\"\n"
262
    "parentFileNameHint=\"%s\"\n"
263
    "\n"
264
    "# Extent description\n"
265
    "RW %u SPARSE \"%s\"\n"
266
    "\n"
267
    "# The Disk Data Base \n"
268
    "#DDB\n"
269
    "\n";
270

    
271
    snp_fd = open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE, 0644);
272
    if (snp_fd < 0)
273
        return -errno;
274
    p_fd = open(backing_file, O_RDONLY | O_BINARY | O_LARGEFILE);
275
    if (p_fd < 0) {
276
        close(snp_fd);
277
        return -errno;
278
    }
279

    
280
    /* read the header */
281
    if (lseek(p_fd, 0x0, SEEK_SET) == -1) {
282
        ret = -errno;
283
        goto fail;
284
    }
285
    if (read(p_fd, hdr, HEADER_SIZE) != HEADER_SIZE) {
286
        ret = -errno;
287
        goto fail;
288
    }
289

    
290
    /* write the header */
291
    if (lseek(snp_fd, 0x0, SEEK_SET) == -1) {
292
        ret = -errno;
293
        goto fail;
294
    }
295
    if (write(snp_fd, hdr, HEADER_SIZE) == -1) {
296
        ret = -errno;
297
        goto fail;
298
    }
299

    
300
    memset(&header, 0, sizeof(header));
301
    memcpy(&header,&hdr[4], sizeof(header)); // skip the VMDK4_MAGIC
302

    
303
    if (ftruncate(snp_fd, header.grain_offset << 9)) {
304
        ret = -errno;
305
        goto fail;
306
    }
307
    /* the descriptor offset = 0x200 */
308
    if (lseek(p_fd, 0x200, SEEK_SET) == -1) {
309
        ret = -errno;
310
        goto fail;
311
    }
312
    if (read(p_fd, p_desc, DESC_SIZE) != DESC_SIZE) {
313
        ret = -errno;
314
        goto fail;
315
    }
316

    
317
    if ((p_name = strstr(p_desc,"CID")) != NULL) {
318
        p_name += sizeof("CID");
319
        sscanf(p_name,"%x",&p_cid);
320
    }
321

    
322
    real_filename = filename;
323
    if ((temp_str = strrchr(real_filename, '\\')) != NULL)
324
        real_filename = temp_str + 1;
325
    if ((temp_str = strrchr(real_filename, '/')) != NULL)
326
        real_filename = temp_str + 1;
327
    if ((temp_str = strrchr(real_filename, ':')) != NULL)
328
        real_filename = temp_str + 1;
329

    
330
    snprintf(s_desc, sizeof(s_desc), desc_template, p_cid, p_cid, backing_file,
331
             (uint32_t)header.capacity, real_filename);
332

    
333
    /* write the descriptor */
334
    if (lseek(snp_fd, 0x200, SEEK_SET) == -1) {
335
        ret = -errno;
336
        goto fail;
337
    }
338
    if (write(snp_fd, s_desc, strlen(s_desc)) == -1) {
339
        ret = -errno;
340
        goto fail;
341
    }
342

    
343
    gd_offset = header.gd_offset * SECTOR_SIZE;     // offset of GD table
344
    rgd_offset = header.rgd_offset * SECTOR_SIZE;   // offset of RGD table
345
    capacity = header.capacity * SECTOR_SIZE;       // Extent size
346
    /*
347
     * Each GDE span 32M disk, means:
348
     * 512 GTE per GT, each GTE points to grain
349
     */
350
    gt_size = (int64_t)header.num_gtes_per_gte * header.granularity * SECTOR_SIZE;
351
    if (!gt_size) {
352
        ret = -EINVAL;
353
        goto fail;
354
    }
355
    gde_entries = (uint32_t)(capacity / gt_size);  // number of gde/rgde
356
    gd_size = gde_entries * sizeof(uint32_t);
357

    
358
    /* write RGD */
359
    rgd_buf = qemu_malloc(gd_size);
360
    if (lseek(p_fd, rgd_offset, SEEK_SET) == -1) {
361
        ret = -errno;
362
        goto fail_rgd;
363
    }
364
    if (read(p_fd, rgd_buf, gd_size) != gd_size) {
365
        ret = -errno;
366
        goto fail_rgd;
367
    }
368
    if (lseek(snp_fd, rgd_offset, SEEK_SET) == -1) {
369
        ret = -errno;
370
        goto fail_rgd;
371
    }
372
    if (write(snp_fd, rgd_buf, gd_size) == -1) {
373
        ret = -errno;
374
        goto fail_rgd;
375
    }
376

    
377
    /* write GD */
378
    gd_buf = qemu_malloc(gd_size);
379
    if (lseek(p_fd, gd_offset, SEEK_SET) == -1) {
380
        ret = -errno;
381
        goto fail_gd;
382
    }
383
    if (read(p_fd, gd_buf, gd_size) != gd_size) {
384
        ret = -errno;
385
        goto fail_gd;
386
    }
387
    if (lseek(snp_fd, gd_offset, SEEK_SET) == -1) {
388
        ret = -errno;
389
        goto fail_gd;
390
    }
391
    if (write(snp_fd, gd_buf, gd_size) == -1) {
392
        ret = -errno;
393
        goto fail_gd;
394
    }
395
    ret = 0;
396

    
397
fail_gd:
398
    qemu_free(gd_buf);
399
fail_rgd:
400
    qemu_free(rgd_buf);
401
fail:
402
    close(p_fd);
403
    close(snp_fd);
404
    return ret;
405
}
406

    
407
static int vmdk_parent_open(BlockDriverState *bs)
408
{
409
    char *p_name;
410
    char desc[DESC_SIZE];
411
    BDRVVmdkState *s = bs->opaque;
412

    
413
    if (bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE) != DESC_SIZE) {
414
        return -1;
415
    }
416

    
417
    if ((p_name = strstr(desc,"parentFileNameHint")) != NULL) {
418
        char *end_name;
419

    
420
        p_name += sizeof("parentFileNameHint") + 1;
421
        if ((end_name = strchr(p_name,'\"')) == NULL)
422
            return -1;
423
        if ((end_name - p_name) > sizeof (bs->backing_file) - 1)
424
            return -1;
425

    
426
        pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
427
    }
428

    
429
    return 0;
430
}
431

    
432
/* Create and append extent to the extent array. Return the added VmdkExtent
433
 * address. return NULL if allocation failed. */
434
static VmdkExtent *vmdk_add_extent(BlockDriverState *bs,
435
                           BlockDriverState *file, bool flat, int64_t sectors,
436
                           int64_t l1_offset, int64_t l1_backup_offset,
437
                           uint32_t l1_size,
438
                           int l2_size, unsigned int cluster_sectors)
439
{
440
    VmdkExtent *extent;
441
    BDRVVmdkState *s = bs->opaque;
442

    
443
    s->extents = qemu_realloc(s->extents,
444
                              (s->num_extents + 1) * sizeof(VmdkExtent));
445
    extent = &s->extents[s->num_extents];
446
    s->num_extents++;
447

    
448
    memset(extent, 0, sizeof(VmdkExtent));
449
    extent->file = file;
450
    extent->flat = flat;
451
    extent->sectors = sectors;
452
    extent->l1_table_offset = l1_offset;
453
    extent->l1_backup_table_offset = l1_backup_offset;
454
    extent->l1_size = l1_size;
455
    extent->l1_entry_sectors = l2_size * cluster_sectors;
456
    extent->l2_size = l2_size;
457
    extent->cluster_sectors = cluster_sectors;
458

    
459
    if (s->num_extents > 1) {
460
        extent->end_sector = (*(extent - 1)).end_sector + extent->sectors;
461
    } else {
462
        extent->end_sector = extent->sectors;
463
    }
464
    bs->total_sectors = extent->end_sector;
465
    return extent;
466
}
467

    
468
static int vmdk_init_tables(BlockDriverState *bs, VmdkExtent *extent)
469
{
470
    int ret;
471
    int l1_size, i;
472

    
473
    /* read the L1 table */
474
    l1_size = extent->l1_size * sizeof(uint32_t);
475
    extent->l1_table = qemu_malloc(l1_size);
476
    ret = bdrv_pread(extent->file,
477
                    extent->l1_table_offset,
478
                    extent->l1_table,
479
                    l1_size);
480
    if (ret < 0) {
481
        goto fail_l1;
482
    }
483
    for (i = 0; i < extent->l1_size; i++) {
484
        le32_to_cpus(&extent->l1_table[i]);
485
    }
486

    
487
    if (extent->l1_backup_table_offset) {
488
        extent->l1_backup_table = qemu_malloc(l1_size);
489
        ret = bdrv_pread(extent->file,
490
                        extent->l1_backup_table_offset,
491
                        extent->l1_backup_table,
492
                        l1_size);
493
        if (ret < 0) {
494
            goto fail_l1b;
495
        }
496
        for (i = 0; i < extent->l1_size; i++) {
497
            le32_to_cpus(&extent->l1_backup_table[i]);
498
        }
499
    }
500

    
501
    extent->l2_cache =
502
        qemu_malloc(extent->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
503
    return 0;
504
 fail_l1b:
505
    qemu_free(extent->l1_backup_table);
506
 fail_l1:
507
    qemu_free(extent->l1_table);
508
    return ret;
509
}
510

    
511
static int vmdk_open_vmdk3(BlockDriverState *bs, int flags)
512
{
513
    int ret;
514
    uint32_t magic;
515
    VMDK3Header header;
516
    BDRVVmdkState *s = bs->opaque;
517
    VmdkExtent *extent;
518

    
519
    s->desc_offset = 0x200;
520
    ret = bdrv_pread(bs->file, sizeof(magic), &header, sizeof(header));
521
    if (ret < 0) {
522
        goto fail;
523
    }
524
    extent = vmdk_add_extent(bs,
525
                             bs->file, false,
526
                             le32_to_cpu(header.disk_sectors),
527
                             le32_to_cpu(header.l1dir_offset) << 9,
528
                             0, 1 << 6, 1 << 9,
529
                             le32_to_cpu(header.granularity));
530
    ret = vmdk_init_tables(bs, extent);
531
    if (ret) {
532
        /* vmdk_init_tables cleans up on fail, so only free allocation of
533
         * vmdk_add_extent here. */
534
        goto fail;
535
    }
536
    return 0;
537
 fail:
538
    vmdk_free_extents(bs);
539
    return ret;
540
}
541

    
542
static int vmdk_open_vmdk4(BlockDriverState *bs, int flags)
543
{
544
    int ret;
545
    uint32_t magic;
546
    uint32_t l1_size, l1_entry_sectors;
547
    VMDK4Header header;
548
    BDRVVmdkState *s = bs->opaque;
549
    VmdkExtent *extent;
550

    
551
    s->desc_offset = 0x200;
552
    ret = bdrv_pread(bs->file, sizeof(magic), &header, sizeof(header));
553
    if (ret < 0) {
554
        goto fail;
555
    }
556
    l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gte)
557
                        * le64_to_cpu(header.granularity);
558
    l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)
559
                / l1_entry_sectors;
560
    extent = vmdk_add_extent(bs, bs->file, false,
561
                          le64_to_cpu(header.capacity),
562
                          le64_to_cpu(header.gd_offset) << 9,
563
                          le64_to_cpu(header.rgd_offset) << 9,
564
                          l1_size,
565
                          le32_to_cpu(header.num_gtes_per_gte),
566
                          le64_to_cpu(header.granularity));
567
    if (extent->l1_entry_sectors <= 0) {
568
        ret = -EINVAL;
569
        goto fail;
570
    }
571
    /* try to open parent images, if exist */
572
    ret = vmdk_parent_open(bs);
573
    if (ret) {
574
        goto fail;
575
    }
576
    s->parent_cid = vmdk_read_cid(bs, 1);
577
    ret = vmdk_init_tables(bs, extent);
578
    if (ret) {
579
        goto fail;
580
    }
581
    return 0;
582
 fail:
583
    vmdk_free_extents(bs);
584
    return ret;
585
}
586

    
587
static int vmdk_open(BlockDriverState *bs, int flags)
588
{
589
    uint32_t magic;
590

    
591
    if (bdrv_pread(bs->file, 0, &magic, sizeof(magic)) != sizeof(magic)) {
592
        return -EIO;
593
    }
594

    
595
    magic = be32_to_cpu(magic);
596
    if (magic == VMDK3_MAGIC) {
597
        return vmdk_open_vmdk3(bs, flags);
598
    } else if (magic == VMDK4_MAGIC) {
599
        return vmdk_open_vmdk4(bs, flags);
600
    } else {
601
        return -EINVAL;
602
    }
603
}
604

    
605
static int get_whole_cluster(BlockDriverState *bs,
606
                VmdkExtent *extent,
607
                uint64_t cluster_offset,
608
                uint64_t offset,
609
                bool allocate)
610
{
611
    /* 128 sectors * 512 bytes each = grain size 64KB */
612
    uint8_t  whole_grain[extent->cluster_sectors * 512];
613

    
614
    /* we will be here if it's first write on non-exist grain(cluster).
615
     * try to read from parent image, if exist */
616
    if (bs->backing_hd) {
617
        int ret;
618

    
619
        if (!vmdk_is_cid_valid(bs))
620
            return -1;
621

    
622
        /* floor offset to cluster */
623
        offset -= offset % (extent->cluster_sectors * 512);
624
        ret = bdrv_read(bs->backing_hd, offset >> 9, whole_grain,
625
                extent->cluster_sectors);
626
        if (ret < 0) {
627
            return -1;
628
        }
629

    
630
        /* Write grain only into the active image */
631
        ret = bdrv_write(extent->file, cluster_offset, whole_grain,
632
                extent->cluster_sectors);
633
        if (ret < 0) {
634
            return -1;
635
        }
636
    }
637
    return 0;
638
}
639

    
640
static int vmdk_L2update(VmdkExtent *extent, VmdkMetaData *m_data)
641
{
642
    /* update L2 table */
643
    if (bdrv_pwrite_sync(
644
                extent->file,
645
                ((int64_t)m_data->l2_offset * 512)
646
                    + (m_data->l2_index * sizeof(m_data->offset)),
647
                &(m_data->offset),
648
                sizeof(m_data->offset)
649
            ) < 0) {
650
        return -1;
651
    }
652
    /* update backup L2 table */
653
    if (extent->l1_backup_table_offset != 0) {
654
        m_data->l2_offset = extent->l1_backup_table[m_data->l1_index];
655
        if (bdrv_pwrite_sync(
656
                    extent->file,
657
                    ((int64_t)m_data->l2_offset * 512)
658
                        + (m_data->l2_index * sizeof(m_data->offset)),
659
                    &(m_data->offset), sizeof(m_data->offset)
660
                ) < 0) {
661
            return -1;
662
        }
663
    }
664

    
665
    return 0;
666
}
667

    
668
static int get_cluster_offset(BlockDriverState *bs,
669
                                    VmdkExtent *extent,
670
                                    VmdkMetaData *m_data,
671
                                    uint64_t offset,
672
                                    int allocate,
673
                                    uint64_t *cluster_offset)
674
{
675
    unsigned int l1_index, l2_offset, l2_index;
676
    int min_index, i, j;
677
    uint32_t min_count, *l2_table, tmp = 0;
678

    
679
    if (m_data)
680
        m_data->valid = 0;
681
    if (extent->flat) {
682
        *cluster_offset = 0;
683
        return 0;
684
    }
685

    
686
    l1_index = (offset >> 9) / extent->l1_entry_sectors;
687
    if (l1_index >= extent->l1_size) {
688
        return -1;
689
    }
690
    l2_offset = extent->l1_table[l1_index];
691
    if (!l2_offset) {
692
        return -1;
693
    }
694
    for (i = 0; i < L2_CACHE_SIZE; i++) {
695
        if (l2_offset == extent->l2_cache_offsets[i]) {
696
            /* increment the hit count */
697
            if (++extent->l2_cache_counts[i] == 0xffffffff) {
698
                for (j = 0; j < L2_CACHE_SIZE; j++) {
699
                    extent->l2_cache_counts[j] >>= 1;
700
                }
701
            }
702
            l2_table = extent->l2_cache + (i * extent->l2_size);
703
            goto found;
704
        }
705
    }
706
    /* not found: load a new entry in the least used one */
707
    min_index = 0;
708
    min_count = 0xffffffff;
709
    for (i = 0; i < L2_CACHE_SIZE; i++) {
710
        if (extent->l2_cache_counts[i] < min_count) {
711
            min_count = extent->l2_cache_counts[i];
712
            min_index = i;
713
        }
714
    }
715
    l2_table = extent->l2_cache + (min_index * extent->l2_size);
716
    if (bdrv_pread(
717
                extent->file,
718
                (int64_t)l2_offset * 512,
719
                l2_table,
720
                extent->l2_size * sizeof(uint32_t)
721
            ) != extent->l2_size * sizeof(uint32_t)) {
722
        return -1;
723
    }
724

    
725
    extent->l2_cache_offsets[min_index] = l2_offset;
726
    extent->l2_cache_counts[min_index] = 1;
727
 found:
728
    l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size;
729
    *cluster_offset = le32_to_cpu(l2_table[l2_index]);
730

    
731
    if (!*cluster_offset) {
732
        if (!allocate) {
733
            return -1;
734
        }
735

    
736
        // Avoid the L2 tables update for the images that have snapshots.
737
        *cluster_offset = bdrv_getlength(extent->file);
738
        bdrv_truncate(
739
            extent->file,
740
            *cluster_offset + (extent->cluster_sectors << 9)
741
        );
742

    
743
        *cluster_offset >>= 9;
744
        tmp = cpu_to_le32(*cluster_offset);
745
        l2_table[l2_index] = tmp;
746

    
747
        /* First of all we write grain itself, to avoid race condition
748
         * that may to corrupt the image.
749
         * This problem may occur because of insufficient space on host disk
750
         * or inappropriate VM shutdown.
751
         */
752
        if (get_whole_cluster(
753
                bs, extent, *cluster_offset, offset, allocate) == -1)
754
            return -1;
755

    
756
        if (m_data) {
757
            m_data->offset = tmp;
758
            m_data->l1_index = l1_index;
759
            m_data->l2_index = l2_index;
760
            m_data->l2_offset = l2_offset;
761
            m_data->valid = 1;
762
        }
763
    }
764
    *cluster_offset <<= 9;
765
    return 0;
766
}
767

    
768
static VmdkExtent *find_extent(BDRVVmdkState *s,
769
                                int64_t sector_num, VmdkExtent *start_hint)
770
{
771
    VmdkExtent *extent = start_hint;
772

    
773
    if (!extent) {
774
        extent = &s->extents[0];
775
    }
776
    while (extent < &s->extents[s->num_extents]) {
777
        if (sector_num < extent->end_sector) {
778
            return extent;
779
        }
780
        extent++;
781
    }
782
    return NULL;
783
}
784

    
785
static int vmdk_is_allocated(BlockDriverState *bs, int64_t sector_num,
786
                             int nb_sectors, int *pnum)
787
{
788
    BDRVVmdkState *s = bs->opaque;
789
    int64_t index_in_cluster, n, ret;
790
    uint64_t offset;
791
    VmdkExtent *extent;
792

    
793
    extent = find_extent(s, sector_num, NULL);
794
    if (!extent) {
795
        return 0;
796
    }
797
    ret = get_cluster_offset(bs, extent, NULL,
798
                            sector_num * 512, 0, &offset);
799
    /* get_cluster_offset returning 0 means success */
800
    ret = !ret;
801

    
802
    index_in_cluster = sector_num % extent->cluster_sectors;
803
    n = extent->cluster_sectors - index_in_cluster;
804
    if (n > nb_sectors)
805
        n = nb_sectors;
806
    *pnum = n;
807
    return ret;
808
}
809

    
810
static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
811
                    uint8_t *buf, int nb_sectors)
812
{
813
    BDRVVmdkState *s = bs->opaque;
814
    int ret;
815
    uint64_t n, index_in_cluster;
816
    VmdkExtent *extent = NULL;
817
    uint64_t cluster_offset;
818

    
819
    while (nb_sectors > 0) {
820
        extent = find_extent(s, sector_num, extent);
821
        if (!extent) {
822
            return -EIO;
823
        }
824
        ret = get_cluster_offset(
825
                            bs, extent, NULL,
826
                            sector_num << 9, 0, &cluster_offset);
827
        index_in_cluster = sector_num % extent->cluster_sectors;
828
        n = extent->cluster_sectors - index_in_cluster;
829
        if (n > nb_sectors)
830
            n = nb_sectors;
831
        if (ret) {
832
            /* if not allocated, try to read from parent image, if exist */
833
            if (bs->backing_hd) {
834
                if (!vmdk_is_cid_valid(bs))
835
                    return -1;
836
                ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
837
                if (ret < 0)
838
                    return -1;
839
            } else {
840
                memset(buf, 0, 512 * n);
841
            }
842
        } else {
843
            if(bdrv_pread(bs->file, cluster_offset + index_in_cluster * 512, buf, n * 512) != n * 512)
844
                return -1;
845
        }
846
        nb_sectors -= n;
847
        sector_num += n;
848
        buf += n * 512;
849
    }
850
    return 0;
851
}
852

    
853
static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
854
                     const uint8_t *buf, int nb_sectors)
855
{
856
    BDRVVmdkState *s = bs->opaque;
857
    VmdkExtent *extent = NULL;
858
    int n, ret;
859
    int64_t index_in_cluster;
860
    uint64_t cluster_offset;
861
    VmdkMetaData m_data;
862

    
863
    if (sector_num > bs->total_sectors) {
864
        fprintf(stderr,
865
                "(VMDK) Wrong offset: sector_num=0x%" PRIx64
866
                " total_sectors=0x%" PRIx64 "\n",
867
                sector_num, bs->total_sectors);
868
        return -1;
869
    }
870

    
871
    while (nb_sectors > 0) {
872
        extent = find_extent(s, sector_num, extent);
873
        if (!extent) {
874
            return -EIO;
875
        }
876
        ret = get_cluster_offset(
877
                                bs,
878
                                extent,
879
                                &m_data,
880
                                sector_num << 9, 1,
881
                                &cluster_offset);
882
        if (ret) {
883
            return -EINVAL;
884
        }
885
        index_in_cluster = sector_num % extent->cluster_sectors;
886
        n = extent->cluster_sectors - index_in_cluster;
887
        if (n > nb_sectors) {
888
            n = nb_sectors;
889
        }
890

    
891
        if (bdrv_pwrite(bs->file,
892
                        cluster_offset + index_in_cluster * 512,
893
                        buf, n * 512)
894
                != n * 512) {
895
            return -1;
896
        }
897
        if (m_data.valid) {
898
            /* update L2 tables */
899
            if (vmdk_L2update(extent, &m_data) == -1) {
900
                return -1;
901
            }
902
        }
903
        nb_sectors -= n;
904
        sector_num += n;
905
        buf += n * 512;
906

    
907
        // update CID on the first write every time the virtual disk is opened
908
        if (!s->cid_updated) {
909
            vmdk_write_cid(bs, time(NULL));
910
            s->cid_updated = true;
911
        }
912
    }
913
    return 0;
914
}
915

    
916
static int vmdk_create(const char *filename, QEMUOptionParameter *options)
917
{
918
    int fd, i;
919
    VMDK4Header header;
920
    uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
921
    static const char desc_template[] =
922
        "# Disk DescriptorFile\n"
923
        "version=1\n"
924
        "CID=%x\n"
925
        "parentCID=ffffffff\n"
926
        "createType=\"monolithicSparse\"\n"
927
        "\n"
928
        "# Extent description\n"
929
        "RW %" PRId64 " SPARSE \"%s\"\n"
930
        "\n"
931
        "# The Disk Data Base \n"
932
        "#DDB\n"
933
        "\n"
934
        "ddb.virtualHWVersion = \"%d\"\n"
935
        "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
936
        "ddb.geometry.heads = \"16\"\n"
937
        "ddb.geometry.sectors = \"63\"\n"
938
        "ddb.adapterType = \"ide\"\n";
939
    char desc[1024];
940
    const char *real_filename, *temp_str;
941
    int64_t total_size = 0;
942
    const char *backing_file = NULL;
943
    int flags = 0;
944
    int ret;
945

    
946
    // Read out options
947
    while (options && options->name) {
948
        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
949
            total_size = options->value.n / 512;
950
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
951
            backing_file = options->value.s;
952
        } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
953
            flags |= options->value.n ? BLOCK_FLAG_COMPAT6: 0;
954
        }
955
        options++;
956
    }
957

    
958
    /* XXX: add support for backing file */
959
    if (backing_file) {
960
        return vmdk_snapshot_create(filename, backing_file);
961
    }
962

    
963
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
964
              0644);
965
    if (fd < 0)
966
        return -errno;
967
    magic = cpu_to_be32(VMDK4_MAGIC);
968
    memset(&header, 0, sizeof(header));
969
    header.version = 1;
970
    header.flags = 3; /* ?? */
971
    header.capacity = total_size;
972
    header.granularity = 128;
973
    header.num_gtes_per_gte = 512;
974

    
975
    grains = (total_size + header.granularity - 1) / header.granularity;
976
    gt_size = ((header.num_gtes_per_gte * sizeof(uint32_t)) + 511) >> 9;
977
    gt_count = (grains + header.num_gtes_per_gte - 1) / header.num_gtes_per_gte;
978
    gd_size = (gt_count * sizeof(uint32_t) + 511) >> 9;
979

    
980
    header.desc_offset = 1;
981
    header.desc_size = 20;
982
    header.rgd_offset = header.desc_offset + header.desc_size;
983
    header.gd_offset = header.rgd_offset + gd_size + (gt_size * gt_count);
984
    header.grain_offset =
985
       ((header.gd_offset + gd_size + (gt_size * gt_count) +
986
         header.granularity - 1) / header.granularity) *
987
        header.granularity;
988

    
989
    /* swap endianness for all header fields */
990
    header.version = cpu_to_le32(header.version);
991
    header.flags = cpu_to_le32(header.flags);
992
    header.capacity = cpu_to_le64(header.capacity);
993
    header.granularity = cpu_to_le64(header.granularity);
994
    header.num_gtes_per_gte = cpu_to_le32(header.num_gtes_per_gte);
995
    header.desc_offset = cpu_to_le64(header.desc_offset);
996
    header.desc_size = cpu_to_le64(header.desc_size);
997
    header.rgd_offset = cpu_to_le64(header.rgd_offset);
998
    header.gd_offset = cpu_to_le64(header.gd_offset);
999
    header.grain_offset = cpu_to_le64(header.grain_offset);
1000

    
1001
    header.check_bytes[0] = 0xa;
1002
    header.check_bytes[1] = 0x20;
1003
    header.check_bytes[2] = 0xd;
1004
    header.check_bytes[3] = 0xa;
1005

    
1006
    /* write all the data */
1007
    ret = qemu_write_full(fd, &magic, sizeof(magic));
1008
    if (ret != sizeof(magic)) {
1009
        ret = -errno;
1010
        goto exit;
1011
    }
1012
    ret = qemu_write_full(fd, &header, sizeof(header));
1013
    if (ret != sizeof(header)) {
1014
        ret = -errno;
1015
        goto exit;
1016
    }
1017

    
1018
    ret = ftruncate(fd, le64_to_cpu(header.grain_offset) << 9);
1019
    if (ret < 0) {
1020
        ret = -errno;
1021
        goto exit;
1022
    }
1023

    
1024
    /* write grain directory */
1025
    lseek(fd, le64_to_cpu(header.rgd_offset) << 9, SEEK_SET);
1026
    for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_size;
1027
         i < gt_count; i++, tmp += gt_size) {
1028
        ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1029
        if (ret != sizeof(tmp)) {
1030
            ret = -errno;
1031
            goto exit;
1032
        }
1033
    }
1034

    
1035
    /* write backup grain directory */
1036
    lseek(fd, le64_to_cpu(header.gd_offset) << 9, SEEK_SET);
1037
    for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_size;
1038
         i < gt_count; i++, tmp += gt_size) {
1039
        ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1040
        if (ret != sizeof(tmp)) {
1041
            ret = -errno;
1042
            goto exit;
1043
        }
1044
    }
1045

    
1046
    /* compose the descriptor */
1047
    real_filename = filename;
1048
    if ((temp_str = strrchr(real_filename, '\\')) != NULL)
1049
        real_filename = temp_str + 1;
1050
    if ((temp_str = strrchr(real_filename, '/')) != NULL)
1051
        real_filename = temp_str + 1;
1052
    if ((temp_str = strrchr(real_filename, ':')) != NULL)
1053
        real_filename = temp_str + 1;
1054
    snprintf(desc, sizeof(desc), desc_template, (unsigned int)time(NULL),
1055
             total_size, real_filename,
1056
             (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
1057
             total_size / (int64_t)(63 * 16));
1058

    
1059
    /* write the descriptor */
1060
    lseek(fd, le64_to_cpu(header.desc_offset) << 9, SEEK_SET);
1061
    ret = qemu_write_full(fd, desc, strlen(desc));
1062
    if (ret != strlen(desc)) {
1063
        ret = -errno;
1064
        goto exit;
1065
    }
1066

    
1067
    ret = 0;
1068
exit:
1069
    close(fd);
1070
    return ret;
1071
}
1072

    
1073
static void vmdk_close(BlockDriverState *bs)
1074
{
1075
    vmdk_free_extents(bs);
1076
}
1077

    
1078
static int vmdk_flush(BlockDriverState *bs)
1079
{
1080
    int i, ret, err;
1081
    BDRVVmdkState *s = bs->opaque;
1082

    
1083
    ret = bdrv_flush(bs->file);
1084
    for (i = 0; i < s->num_extents; i++) {
1085
        err = bdrv_flush(s->extents[i].file);
1086
        if (err < 0) {
1087
            ret = err;
1088
        }
1089
    }
1090
    return ret;
1091
}
1092

    
1093

    
1094
static QEMUOptionParameter vmdk_create_options[] = {
1095
    {
1096
        .name = BLOCK_OPT_SIZE,
1097
        .type = OPT_SIZE,
1098
        .help = "Virtual disk size"
1099
    },
1100
    {
1101
        .name = BLOCK_OPT_BACKING_FILE,
1102
        .type = OPT_STRING,
1103
        .help = "File name of a base image"
1104
    },
1105
    {
1106
        .name = BLOCK_OPT_COMPAT6,
1107
        .type = OPT_FLAG,
1108
        .help = "VMDK version 6 image"
1109
    },
1110
    { NULL }
1111
};
1112

    
1113
static BlockDriver bdrv_vmdk = {
1114
    .format_name        = "vmdk",
1115
    .instance_size        = sizeof(BDRVVmdkState),
1116
    .bdrv_probe                = vmdk_probe,
1117
    .bdrv_open      = vmdk_open,
1118
    .bdrv_read                = vmdk_read,
1119
    .bdrv_write                = vmdk_write,
1120
    .bdrv_close                = vmdk_close,
1121
    .bdrv_create        = vmdk_create,
1122
    .bdrv_flush                = vmdk_flush,
1123
    .bdrv_is_allocated        = vmdk_is_allocated,
1124

    
1125
    .create_options = vmdk_create_options,
1126
};
1127

    
1128
static void bdrv_vmdk_init(void)
1129
{
1130
    bdrv_register(&bdrv_vmdk);
1131
}
1132

    
1133
block_init(bdrv_vmdk_init);