]> git.proxmox.com Git - qemu.git/blame - block/vmdk.c
vmdk: fix double free
[qemu.git] / block / vmdk.c
CommitLineData
ea2384d3
FB
1/*
2 * Block driver for the VMDK format
5fafdf24 3 *
ea2384d3 4 * Copyright (c) 2004 Fabrice Bellard
ff1afc72 5 * Copyright (c) 2005 Filip Navara
5fafdf24 6 *
ea2384d3
FB
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 */
5f4da8c0 25
faf07963 26#include "qemu-common.h"
ea2384d3 27#include "block_int.h"
5efa9d5a 28#include "module.h"
ea2384d3 29
ea2384d3
FB
30#define VMDK3_MAGIC (('C' << 24) | ('O' << 16) | ('W' << 8) | 'D')
31#define VMDK4_MAGIC (('K' << 24) | ('D' << 16) | ('M' << 8) | 'V')
32
33typedef 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
46typedef 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];
ff1afc72 59} __attribute__((packed)) VMDK4Header;
ea2384d3
FB
60
61#define L2_CACHE_SIZE 16
62
63typedef struct BDRVVmdkState {
5f4da8c0 64 BlockDriverState *hd;
ea2384d3 65 int64_t l1_table_offset;
ff1afc72 66 int64_t l1_backup_table_offset;
ea2384d3 67 uint32_t *l1_table;
ff1afc72 68 uint32_t *l1_backup_table;
ea2384d3
FB
69 unsigned int l1_size;
70 uint32_t l1_entry_sectors;
71
72 unsigned int l2_size;
73 uint32_t *l2_cache;
74 uint32_t l2_cache_offsets[L2_CACHE_SIZE];
75 uint32_t l2_cache_counts[L2_CACHE_SIZE];
76
77 unsigned int cluster_sectors;
5f4da8c0 78 uint32_t parent_cid;
630530a6 79 int is_parent;
ea2384d3
FB
80} BDRVVmdkState;
81
630530a6
TS
82typedef struct VmdkMetaData {
83 uint32_t offset;
84 unsigned int l1_index;
85 unsigned int l2_index;
86 unsigned int l2_offset;
87 int valid;
88} VmdkMetaData;
89
90typedef struct ActiveBDRVState{
91 BlockDriverState *hd; // active image handler
92 uint64_t cluster_offset; // current write offset
93}ActiveBDRVState;
94
95static ActiveBDRVState activeBDRV;
96
97
ea2384d3
FB
98static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
99{
100 uint32_t magic;
101
102 if (buf_size < 4)
103 return 0;
104 magic = be32_to_cpu(*(uint32_t *)buf);
105 if (magic == VMDK3_MAGIC ||
106 magic == VMDK4_MAGIC)
107 return 100;
108 else
109 return 0;
110}
111
5f4da8c0
TS
112#define CHECK_CID 1
113
3b46e624 114#define SECTOR_SIZE 512
5f4da8c0 115#define DESC_SIZE 20*SECTOR_SIZE // 20 sectors of 512 bytes each
5fafdf24 116#define HEADER_SIZE 512 // first sector of 512 bytes
5f4da8c0
TS
117
118static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)
ea2384d3
FB
119{
120 BDRVVmdkState *s = bs->opaque;
5f4da8c0
TS
121 char desc[DESC_SIZE];
122 uint32_t cid;
7ccfb2eb 123 const char *p_name, *cid_str;
5f4da8c0
TS
124 size_t cid_str_size;
125
126 /* the descriptor offset = 0x200 */
127 if (bdrv_pread(s->hd, 0x200, desc, DESC_SIZE) != DESC_SIZE)
128 return 0;
129
130 if (parent) {
131 cid_str = "parentCID";
132 cid_str_size = sizeof("parentCID");
133 } else {
134 cid_str = "CID";
135 cid_str_size = sizeof("CID");
136 }
137
511d2b14 138 if ((p_name = strstr(desc,cid_str)) != NULL) {
5f4da8c0
TS
139 p_name += cid_str_size;
140 sscanf(p_name,"%x",&cid);
141 }
142
143 return cid;
144}
145
146static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)
147{
148 BDRVVmdkState *s = bs->opaque;
149 char desc[DESC_SIZE], tmp_desc[DESC_SIZE];
150 char *p_name, *tmp_str;
151
152 /* the descriptor offset = 0x200 */
153 if (bdrv_pread(s->hd, 0x200, desc, DESC_SIZE) != DESC_SIZE)
154 return -1;
155
156 tmp_str = strstr(desc,"parentCID");
363a37d5 157 pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);
511d2b14 158 if ((p_name = strstr(desc,"CID")) != NULL) {
5f4da8c0 159 p_name += sizeof("CID");
363a37d5
BS
160 snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);
161 pstrcat(desc, sizeof(desc), tmp_desc);
5f4da8c0
TS
162 }
163
164 if (bdrv_pwrite(s->hd, 0x200, desc, DESC_SIZE) != DESC_SIZE)
165 return -1;
166 return 0;
167}
168
169static int vmdk_is_cid_valid(BlockDriverState *bs)
170{
171#ifdef CHECK_CID
172 BDRVVmdkState *s = bs->opaque;
b171271a 173 BlockDriverState *p_bs = bs->backing_hd;
5f4da8c0
TS
174 uint32_t cur_pcid;
175
176 if (p_bs) {
177 cur_pcid = vmdk_read_cid(p_bs,0);
178 if (s->parent_cid != cur_pcid)
179 // CID not valid
180 return 0;
181 }
182#endif
183 // CID valid
184 return 1;
185}
186
187static int vmdk_snapshot_create(const char *filename, const char *backing_file)
188{
189 int snp_fd, p_fd;
53c2e716 190 int ret;
5f4da8c0 191 uint32_t p_cid;
5fafdf24 192 char *p_name, *gd_buf, *rgd_buf;
5f4da8c0
TS
193 const char *real_filename, *temp_str;
194 VMDK4Header header;
195 uint32_t gde_entries, gd_size;
196 int64_t gd_offset, rgd_offset, capacity, gt_size;
197 char p_desc[DESC_SIZE], s_desc[DESC_SIZE], hdr[HEADER_SIZE];
7ccfb2eb 198 static const char desc_template[] =
5f4da8c0
TS
199 "# Disk DescriptorFile\n"
200 "version=1\n"
201 "CID=%x\n"
202 "parentCID=%x\n"
203 "createType=\"monolithicSparse\"\n"
204 "parentFileNameHint=\"%s\"\n"
205 "\n"
206 "# Extent description\n"
7ccfb2eb 207 "RW %u SPARSE \"%s\"\n"
5f4da8c0
TS
208 "\n"
209 "# The Disk Data Base \n"
210 "#DDB\n"
211 "\n";
212
213 snp_fd = open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE, 0644);
214 if (snp_fd < 0)
53c2e716 215 return -errno;
5f4da8c0
TS
216 p_fd = open(backing_file, O_RDONLY | O_BINARY | O_LARGEFILE);
217 if (p_fd < 0) {
218 close(snp_fd);
53c2e716 219 return -errno;
5f4da8c0
TS
220 }
221
222 /* read the header */
53c2e716
JQ
223 if (lseek(p_fd, 0x0, SEEK_SET) == -1) {
224 ret = -errno;
5f4da8c0 225 goto fail;
53c2e716
JQ
226 }
227 if (read(p_fd, hdr, HEADER_SIZE) != HEADER_SIZE) {
228 ret = -errno;
5f4da8c0 229 goto fail;
53c2e716 230 }
5f4da8c0
TS
231
232 /* write the header */
53c2e716
JQ
233 if (lseek(snp_fd, 0x0, SEEK_SET) == -1) {
234 ret = -errno;
5f4da8c0 235 goto fail;
53c2e716
JQ
236 }
237 if (write(snp_fd, hdr, HEADER_SIZE) == -1) {
238 ret = -errno;
5f4da8c0 239 goto fail;
53c2e716 240 }
5f4da8c0
TS
241
242 memset(&header, 0, sizeof(header));
243 memcpy(&header,&hdr[4], sizeof(header)); // skip the VMDK4_MAGIC
244
53c2e716
JQ
245 if (ftruncate(snp_fd, header.grain_offset << 9)) {
246 ret = -errno;
1640366c 247 goto fail;
53c2e716 248 }
5f4da8c0 249 /* the descriptor offset = 0x200 */
53c2e716
JQ
250 if (lseek(p_fd, 0x200, SEEK_SET) == -1) {
251 ret = -errno;
5f4da8c0 252 goto fail;
53c2e716
JQ
253 }
254 if (read(p_fd, p_desc, DESC_SIZE) != DESC_SIZE) {
255 ret = -errno;
5f4da8c0 256 goto fail;
53c2e716 257 }
5f4da8c0 258
511d2b14 259 if ((p_name = strstr(p_desc,"CID")) != NULL) {
5f4da8c0
TS
260 p_name += sizeof("CID");
261 sscanf(p_name,"%x",&p_cid);
262 }
263
264 real_filename = filename;
265 if ((temp_str = strrchr(real_filename, '\\')) != NULL)
266 real_filename = temp_str + 1;
267 if ((temp_str = strrchr(real_filename, '/')) != NULL)
268 real_filename = temp_str + 1;
269 if ((temp_str = strrchr(real_filename, ':')) != NULL)
270 real_filename = temp_str + 1;
271
363a37d5
BS
272 snprintf(s_desc, sizeof(s_desc), desc_template, p_cid, p_cid, backing_file,
273 (uint32_t)header.capacity, real_filename);
5f4da8c0
TS
274
275 /* write the descriptor */
53c2e716
JQ
276 if (lseek(snp_fd, 0x200, SEEK_SET) == -1) {
277 ret = -errno;
5f4da8c0 278 goto fail;
53c2e716
JQ
279 }
280 if (write(snp_fd, s_desc, strlen(s_desc)) == -1) {
281 ret = -errno;
5f4da8c0 282 goto fail;
53c2e716 283 }
ea2384d3 284
5f4da8c0
TS
285 gd_offset = header.gd_offset * SECTOR_SIZE; // offset of GD table
286 rgd_offset = header.rgd_offset * SECTOR_SIZE; // offset of RGD table
287 capacity = header.capacity * SECTOR_SIZE; // Extent size
288 /*
289 * Each GDE span 32M disk, means:
290 * 512 GTE per GT, each GTE points to grain
291 */
292 gt_size = (int64_t)header.num_gtes_per_gte * header.granularity * SECTOR_SIZE;
53c2e716
JQ
293 if (!gt_size) {
294 ret = -EINVAL;
5f4da8c0 295 goto fail;
53c2e716 296 }
5fafdf24 297 gde_entries = (uint32_t)(capacity / gt_size); // number of gde/rgde
5f4da8c0
TS
298 gd_size = gde_entries * sizeof(uint32_t);
299
300 /* write RGD */
301 rgd_buf = qemu_malloc(gd_size);
53c2e716
JQ
302 if (lseek(p_fd, rgd_offset, SEEK_SET) == -1) {
303 ret = -errno;
5f4da8c0 304 goto fail_rgd;
53c2e716
JQ
305 }
306 if (read(p_fd, rgd_buf, gd_size) != gd_size) {
307 ret = -errno;
5f4da8c0 308 goto fail_rgd;
53c2e716
JQ
309 }
310 if (lseek(snp_fd, rgd_offset, SEEK_SET) == -1) {
311 ret = -errno;
5f4da8c0 312 goto fail_rgd;
53c2e716
JQ
313 }
314 if (write(snp_fd, rgd_buf, gd_size) == -1) {
315 ret = -errno;
5f4da8c0 316 goto fail_rgd;
53c2e716 317 }
5f4da8c0
TS
318
319 /* write GD */
320 gd_buf = qemu_malloc(gd_size);
53c2e716
JQ
321 if (lseek(p_fd, gd_offset, SEEK_SET) == -1) {
322 ret = -errno;
5f4da8c0 323 goto fail_gd;
53c2e716
JQ
324 }
325 if (read(p_fd, gd_buf, gd_size) != gd_size) {
326 ret = -errno;
5f4da8c0 327 goto fail_gd;
53c2e716
JQ
328 }
329 if (lseek(snp_fd, gd_offset, SEEK_SET) == -1) {
330 ret = -errno;
5f4da8c0 331 goto fail_gd;
53c2e716
JQ
332 }
333 if (write(snp_fd, gd_buf, gd_size) == -1) {
334 ret = -errno;
5f4da8c0 335 goto fail_gd;
53c2e716 336 }
5f4da8c0 337 qemu_free(gd_buf);
a161329b 338 qemu_free(rgd_buf);
5f4da8c0
TS
339
340 close(p_fd);
341 close(snp_fd);
342 return 0;
343
344 fail_gd:
345 qemu_free(gd_buf);
3b46e624 346 fail_rgd:
5f4da8c0
TS
347 qemu_free(rgd_buf);
348 fail:
349 close(p_fd);
350 close(snp_fd);
53c2e716 351 return ret;
5f4da8c0
TS
352}
353
354static void vmdk_parent_close(BlockDriverState *bs)
355{
356 if (bs->backing_hd)
357 bdrv_close(bs->backing_hd);
358}
359
b1d8e52e 360static int parent_open = 0;
5f4da8c0
TS
361static int vmdk_parent_open(BlockDriverState *bs, const char * filename)
362{
363 BDRVVmdkState *s = bs->opaque;
5fafdf24 364 char *p_name;
5f4da8c0
TS
365 char desc[DESC_SIZE];
366 char parent_img_name[1024];
367
368 /* the descriptor offset = 0x200 */
369 if (bdrv_pread(s->hd, 0x200, desc, DESC_SIZE) != DESC_SIZE)
370 return -1;
371
511d2b14 372 if ((p_name = strstr(desc,"parentFileNameHint")) != NULL) {
5f4da8c0
TS
373 char *end_name;
374 struct stat file_buf;
375
376 p_name += sizeof("parentFileNameHint") + 1;
511d2b14 377 if ((end_name = strchr(p_name,'\"')) == NULL)
5f4da8c0 378 return -1;
b171271a 379 if ((end_name - p_name) > sizeof (bs->backing_file) - 1)
b34d259a 380 return -1;
3b46e624 381
b171271a
KW
382 pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);
383 if (stat(bs->backing_file, &file_buf) != 0) {
5f4da8c0 384 path_combine(parent_img_name, sizeof(parent_img_name),
b171271a 385 filename, bs->backing_file);
5f4da8c0 386 } else {
363a37d5 387 pstrcpy(parent_img_name, sizeof(parent_img_name),
b171271a 388 bs->backing_file);
5f4da8c0
TS
389 }
390
b171271a
KW
391 bs->backing_hd = bdrv_new("");
392 if (!bs->backing_hd) {
5f4da8c0
TS
393 failure:
394 bdrv_close(s->hd);
ff1afc72 395 return -1;
5f4da8c0 396 }
630530a6 397 parent_open = 1;
f5edb014 398 if (bdrv_open(bs->backing_hd, parent_img_name, 0) < 0)
5f4da8c0 399 goto failure;
630530a6 400 parent_open = 0;
ff1afc72 401 }
5f4da8c0
TS
402
403 return 0;
404}
405
406static int vmdk_open(BlockDriverState *bs, const char *filename, int flags)
407{
408 BDRVVmdkState *s = bs->opaque;
409 uint32_t magic;
410 int l1_size, i, ret;
411
f5edb014
NS
412 if (parent_open) {
413 /* Parent must be opened as RO, no RDWR. */
414 flags = 0;
415 }
630530a6 416
b5eff355 417 ret = bdrv_file_open(&s->hd, filename, flags);
5f4da8c0
TS
418 if (ret < 0)
419 return ret;
420 if (bdrv_pread(s->hd, 0, &magic, sizeof(magic)) != sizeof(magic))
ea2384d3 421 goto fail;
5f4da8c0 422
7143c62c 423 magic = be32_to_cpu(magic);
ea2384d3
FB
424 if (magic == VMDK3_MAGIC) {
425 VMDK3Header header;
5f4da8c0
TS
426
427 if (bdrv_pread(s->hd, sizeof(magic), &header, sizeof(header)) != sizeof(header))
ea2384d3
FB
428 goto fail;
429 s->cluster_sectors = le32_to_cpu(header.granularity);
430 s->l2_size = 1 << 9;
431 s->l1_size = 1 << 6;
432 bs->total_sectors = le32_to_cpu(header.disk_sectors);
ff1afc72
FB
433 s->l1_table_offset = le32_to_cpu(header.l1dir_offset) << 9;
434 s->l1_backup_table_offset = 0;
ea2384d3
FB
435 s->l1_entry_sectors = s->l2_size * s->cluster_sectors;
436 } else if (magic == VMDK4_MAGIC) {
437 VMDK4Header header;
5f4da8c0
TS
438
439 if (bdrv_pread(s->hd, sizeof(magic), &header, sizeof(header)) != sizeof(header))
ea2384d3 440 goto fail;
bd6ea3c8
FB
441 bs->total_sectors = le64_to_cpu(header.capacity);
442 s->cluster_sectors = le64_to_cpu(header.granularity);
ea2384d3
FB
443 s->l2_size = le32_to_cpu(header.num_gtes_per_gte);
444 s->l1_entry_sectors = s->l2_size * s->cluster_sectors;
445 if (s->l1_entry_sectors <= 0)
446 goto fail;
5fafdf24 447 s->l1_size = (bs->total_sectors + s->l1_entry_sectors - 1)
ea2384d3 448 / s->l1_entry_sectors;
ff1afc72
FB
449 s->l1_table_offset = le64_to_cpu(header.rgd_offset) << 9;
450 s->l1_backup_table_offset = le64_to_cpu(header.gd_offset) << 9;
5f4da8c0 451
630530a6
TS
452 if (parent_open)
453 s->is_parent = 1;
454 else
455 s->is_parent = 0;
456
5f4da8c0
TS
457 // try to open parent images, if exist
458 if (vmdk_parent_open(bs, filename) != 0)
459 goto fail;
460 // write the CID once after the image creation
461 s->parent_cid = vmdk_read_cid(bs,1);
ea2384d3
FB
462 } else {
463 goto fail;
464 }
5f4da8c0 465
ea2384d3
FB
466 /* read the L1 table */
467 l1_size = s->l1_size * sizeof(uint32_t);
468 s->l1_table = qemu_malloc(l1_size);
5f4da8c0 469 if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, l1_size) != l1_size)
ea2384d3
FB
470 goto fail;
471 for(i = 0; i < s->l1_size; i++) {
472 le32_to_cpus(&s->l1_table[i]);
473 }
474
ff1afc72
FB
475 if (s->l1_backup_table_offset) {
476 s->l1_backup_table = qemu_malloc(l1_size);
5f4da8c0 477 if (bdrv_pread(s->hd, s->l1_backup_table_offset, s->l1_backup_table, l1_size) != l1_size)
ff1afc72
FB
478 goto fail;
479 for(i = 0; i < s->l1_size; i++) {
480 le32_to_cpus(&s->l1_backup_table[i]);
481 }
482 }
483
ea2384d3 484 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint32_t));
ea2384d3
FB
485 return 0;
486 fail:
ff1afc72 487 qemu_free(s->l1_backup_table);
ea2384d3
FB
488 qemu_free(s->l1_table);
489 qemu_free(s->l2_cache);
5f4da8c0 490 bdrv_delete(s->hd);
ea2384d3
FB
491 return -1;
492}
493
630530a6
TS
494static uint64_t get_cluster_offset(BlockDriverState *bs, VmdkMetaData *m_data,
495 uint64_t offset, int allocate);
5f4da8c0
TS
496
497static int get_whole_cluster(BlockDriverState *bs, uint64_t cluster_offset,
498 uint64_t offset, int allocate)
499{
500 uint64_t parent_cluster_offset;
501 BDRVVmdkState *s = bs->opaque;
502 uint8_t whole_grain[s->cluster_sectors*512]; // 128 sectors * 512 bytes each = grain size 64KB
503
504 // we will be here if it's first write on non-exist grain(cluster).
505 // try to read from parent image, if exist
b171271a
KW
506 if (bs->backing_hd) {
507 BDRVVmdkState *ps = bs->backing_hd->opaque;
5f4da8c0
TS
508
509 if (!vmdk_is_cid_valid(bs))
510 return -1;
5f4da8c0 511
b171271a
KW
512 parent_cluster_offset = get_cluster_offset(bs->backing_hd, NULL,
513 offset, allocate);
630530a6
TS
514
515 if (parent_cluster_offset) {
516 BDRVVmdkState *act_s = activeBDRV.hd->opaque;
517
518 if (bdrv_pread(ps->hd, parent_cluster_offset, whole_grain, ps->cluster_sectors*512) != ps->cluster_sectors*512)
519 return -1;
520
521 //Write grain only into the active image
522 if (bdrv_pwrite(act_s->hd, activeBDRV.cluster_offset << 9, whole_grain, sizeof(whole_grain)) != sizeof(whole_grain))
523 return -1;
524 }
525 }
526 return 0;
527}
528
529static int vmdk_L2update(BlockDriverState *bs, VmdkMetaData *m_data)
530{
531 BDRVVmdkState *s = bs->opaque;
532
533 /* update L2 table */
534 if (bdrv_pwrite(s->hd, ((int64_t)m_data->l2_offset * 512) + (m_data->l2_index * sizeof(m_data->offset)),
535 &(m_data->offset), sizeof(m_data->offset)) != sizeof(m_data->offset))
536 return -1;
537 /* update backup L2 table */
538 if (s->l1_backup_table_offset != 0) {
539 m_data->l2_offset = s->l1_backup_table[m_data->l1_index];
540 if (bdrv_pwrite(s->hd, ((int64_t)m_data->l2_offset * 512) + (m_data->l2_index * sizeof(m_data->offset)),
541 &(m_data->offset), sizeof(m_data->offset)) != sizeof(m_data->offset))
5f4da8c0
TS
542 return -1;
543 }
630530a6 544
5f4da8c0
TS
545 return 0;
546}
547
630530a6 548static uint64_t get_cluster_offset(BlockDriverState *bs, VmdkMetaData *m_data,
ff1afc72 549 uint64_t offset, int allocate)
ea2384d3
FB
550{
551 BDRVVmdkState *s = bs->opaque;
552 unsigned int l1_index, l2_offset, l2_index;
553 int min_index, i, j;
630530a6 554 uint32_t min_count, *l2_table, tmp = 0;
ea2384d3 555 uint64_t cluster_offset;
630530a6
TS
556
557 if (m_data)
558 m_data->valid = 0;
559
ea2384d3
FB
560 l1_index = (offset >> 9) / s->l1_entry_sectors;
561 if (l1_index >= s->l1_size)
562 return 0;
563 l2_offset = s->l1_table[l1_index];
564 if (!l2_offset)
565 return 0;
ea2384d3
FB
566 for(i = 0; i < L2_CACHE_SIZE; i++) {
567 if (l2_offset == s->l2_cache_offsets[i]) {
568 /* increment the hit count */
569 if (++s->l2_cache_counts[i] == 0xffffffff) {
570 for(j = 0; j < L2_CACHE_SIZE; j++) {
571 s->l2_cache_counts[j] >>= 1;
572 }
573 }
574 l2_table = s->l2_cache + (i * s->l2_size);
575 goto found;
576 }
577 }
578 /* not found: load a new entry in the least used one */
579 min_index = 0;
580 min_count = 0xffffffff;
581 for(i = 0; i < L2_CACHE_SIZE; i++) {
582 if (s->l2_cache_counts[i] < min_count) {
583 min_count = s->l2_cache_counts[i];
584 min_index = i;
585 }
586 }
587 l2_table = s->l2_cache + (min_index * s->l2_size);
5fafdf24 588 if (bdrv_pread(s->hd, (int64_t)l2_offset * 512, l2_table, s->l2_size * sizeof(uint32_t)) !=
5f4da8c0 589 s->l2_size * sizeof(uint32_t))
ea2384d3 590 return 0;
5f4da8c0 591
ea2384d3
FB
592 s->l2_cache_offsets[min_index] = l2_offset;
593 s->l2_cache_counts[min_index] = 1;
594 found:
595 l2_index = ((offset >> 9) / s->cluster_sectors) % s->l2_size;
596 cluster_offset = le32_to_cpu(l2_table[l2_index]);
630530a6 597
ff1afc72
FB
598 if (!cluster_offset) {
599 if (!allocate)
600 return 0;
630530a6
TS
601 // Avoid the L2 tables update for the images that have snapshots.
602 if (!s->is_parent) {
49140a77 603 cluster_offset = bdrv_getlength(s->hd);
630530a6
TS
604 bdrv_truncate(s->hd, cluster_offset + (s->cluster_sectors << 9));
605
606 cluster_offset >>= 9;
607 tmp = cpu_to_le32(cluster_offset);
608 l2_table[l2_index] = tmp;
609 // Save the active image state
610 activeBDRV.cluster_offset = cluster_offset;
611 activeBDRV.hd = bs;
ff1afc72 612 }
630530a6
TS
613 /* First of all we write grain itself, to avoid race condition
614 * that may to corrupt the image.
615 * This problem may occur because of insufficient space on host disk
616 * or inappropriate VM shutdown.
617 */
5f4da8c0
TS
618 if (get_whole_cluster(bs, cluster_offset, offset, allocate) == -1)
619 return 0;
630530a6
TS
620
621 if (m_data) {
622 m_data->offset = tmp;
623 m_data->l1_index = l1_index;
624 m_data->l2_index = l2_index;
625 m_data->l2_offset = l2_offset;
626 m_data->valid = 1;
627 }
ff1afc72 628 }
ea2384d3
FB
629 cluster_offset <<= 9;
630 return cluster_offset;
631}
632
5fafdf24 633static int vmdk_is_allocated(BlockDriverState *bs, int64_t sector_num,
ea2384d3
FB
634 int nb_sectors, int *pnum)
635{
636 BDRVVmdkState *s = bs->opaque;
637 int index_in_cluster, n;
638 uint64_t cluster_offset;
639
630530a6 640 cluster_offset = get_cluster_offset(bs, NULL, sector_num << 9, 0);
ea2384d3
FB
641 index_in_cluster = sector_num % s->cluster_sectors;
642 n = s->cluster_sectors - index_in_cluster;
643 if (n > nb_sectors)
644 n = nb_sectors;
645 *pnum = n;
646 return (cluster_offset != 0);
647}
648
5fafdf24 649static int vmdk_read(BlockDriverState *bs, int64_t sector_num,
ea2384d3
FB
650 uint8_t *buf, int nb_sectors)
651{
652 BDRVVmdkState *s = bs->opaque;
5f4da8c0 653 int index_in_cluster, n, ret;
ea2384d3 654 uint64_t cluster_offset;
5f4da8c0 655
ea2384d3 656 while (nb_sectors > 0) {
630530a6 657 cluster_offset = get_cluster_offset(bs, NULL, sector_num << 9, 0);
ea2384d3
FB
658 index_in_cluster = sector_num % s->cluster_sectors;
659 n = s->cluster_sectors - index_in_cluster;
660 if (n > nb_sectors)
661 n = nb_sectors;
662 if (!cluster_offset) {
5f4da8c0 663 // try to read from parent image, if exist
b171271a 664 if (bs->backing_hd) {
5f4da8c0
TS
665 if (!vmdk_is_cid_valid(bs))
666 return -1;
b171271a 667 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
5f4da8c0
TS
668 if (ret < 0)
669 return -1;
670 } else {
671 memset(buf, 0, 512 * n);
672 }
ea2384d3 673 } else {
5f4da8c0 674 if(bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512) != n * 512)
ea2384d3
FB
675 return -1;
676 }
677 nb_sectors -= n;
678 sector_num += n;
679 buf += n * 512;
680 }
681 return 0;
682}
683
5fafdf24 684static int vmdk_write(BlockDriverState *bs, int64_t sector_num,
ea2384d3
FB
685 const uint8_t *buf, int nb_sectors)
686{
ff1afc72 687 BDRVVmdkState *s = bs->opaque;
630530a6 688 VmdkMetaData m_data;
5f4da8c0 689 int index_in_cluster, n;
ff1afc72 690 uint64_t cluster_offset;
5f4da8c0 691 static int cid_update = 0;
ff1afc72 692
630530a6
TS
693 if (sector_num > bs->total_sectors) {
694 fprintf(stderr,
92868412
JM
695 "(VMDK) Wrong offset: sector_num=0x%" PRIx64
696 " total_sectors=0x%" PRIx64 "\n",
630530a6
TS
697 sector_num, bs->total_sectors);
698 return -1;
699 }
700
ff1afc72
FB
701 while (nb_sectors > 0) {
702 index_in_cluster = sector_num & (s->cluster_sectors - 1);
703 n = s->cluster_sectors - index_in_cluster;
704 if (n > nb_sectors)
705 n = nb_sectors;
630530a6 706 cluster_offset = get_cluster_offset(bs, &m_data, sector_num << 9, 1);
ff1afc72
FB
707 if (!cluster_offset)
708 return -1;
630530a6 709
5f4da8c0 710 if (bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512) != n * 512)
ff1afc72 711 return -1;
630530a6
TS
712 if (m_data.valid) {
713 /* update L2 tables */
714 if (vmdk_L2update(bs, &m_data) == -1)
715 return -1;
716 }
ff1afc72
FB
717 nb_sectors -= n;
718 sector_num += n;
719 buf += n * 512;
5f4da8c0
TS
720
721 // update CID on the first write every time the virtual disk is opened
722 if (!cid_update) {
723 vmdk_write_cid(bs, time(NULL));
724 cid_update++;
725 }
ff1afc72
FB
726 }
727 return 0;
ea2384d3
FB
728}
729
0e7e1989 730static int vmdk_create(const char *filename, QEMUOptionParameter *options)
8979b227
FB
731{
732 int fd, i;
733 VMDK4Header header;
734 uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
7ccfb2eb 735 static const char desc_template[] =
8979b227
FB
736 "# Disk DescriptorFile\n"
737 "version=1\n"
738 "CID=%x\n"
739 "parentCID=ffffffff\n"
740 "createType=\"monolithicSparse\"\n"
741 "\n"
742 "# Extent description\n"
7fd6d9fc 743 "RW %" PRId64 " SPARSE \"%s\"\n"
8979b227
FB
744 "\n"
745 "# The Disk Data Base \n"
746 "#DDB\n"
747 "\n"
ec36ba14 748 "ddb.virtualHWVersion = \"%d\"\n"
7fd6d9fc 749 "ddb.geometry.cylinders = \"%" PRId64 "\"\n"
8979b227
FB
750 "ddb.geometry.heads = \"16\"\n"
751 "ddb.geometry.sectors = \"63\"\n"
752 "ddb.adapterType = \"ide\"\n";
753 char desc[1024];
754 const char *real_filename, *temp_str;
0e7e1989
KW
755 int64_t total_size = 0;
756 const char *backing_file = NULL;
757 int flags = 0;
1640366c 758 int ret;
0e7e1989
KW
759
760 // Read out options
761 while (options && options->name) {
762 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
763 total_size = options->value.n / 512;
764 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
765 backing_file = options->value.s;
766 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {
767 flags |= options->value.n ? BLOCK_FLAG_COMPAT6: 0;
768 }
769 options++;
770 }
8979b227
FB
771
772 /* XXX: add support for backing file */
5f4da8c0
TS
773 if (backing_file) {
774 return vmdk_snapshot_create(filename, backing_file);
775 }
8979b227
FB
776
777 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
778 0644);
779 if (fd < 0)
b781cce5 780 return -errno;
8979b227
FB
781 magic = cpu_to_be32(VMDK4_MAGIC);
782 memset(&header, 0, sizeof(header));
783 header.version = cpu_to_le32(1);
784 header.flags = cpu_to_le32(3); /* ?? */
785 header.capacity = cpu_to_le64(total_size);
786 header.granularity = cpu_to_le64(128);
787 header.num_gtes_per_gte = cpu_to_le32(512);
788
789 grains = (total_size + header.granularity - 1) / header.granularity;
790 gt_size = ((header.num_gtes_per_gte * sizeof(uint32_t)) + 511) >> 9;
791 gt_count = (grains + header.num_gtes_per_gte - 1) / header.num_gtes_per_gte;
792 gd_size = (gt_count * sizeof(uint32_t) + 511) >> 9;
793
794 header.desc_offset = 1;
795 header.desc_size = 20;
796 header.rgd_offset = header.desc_offset + header.desc_size;
797 header.gd_offset = header.rgd_offset + gd_size + (gt_size * gt_count);
798 header.grain_offset =
799 ((header.gd_offset + gd_size + (gt_size * gt_count) +
800 header.granularity - 1) / header.granularity) *
801 header.granularity;
802
803 header.desc_offset = cpu_to_le64(header.desc_offset);
804 header.desc_size = cpu_to_le64(header.desc_size);
805 header.rgd_offset = cpu_to_le64(header.rgd_offset);
806 header.gd_offset = cpu_to_le64(header.gd_offset);
807 header.grain_offset = cpu_to_le64(header.grain_offset);
808
809 header.check_bytes[0] = 0xa;
810 header.check_bytes[1] = 0x20;
811 header.check_bytes[2] = 0xd;
812 header.check_bytes[3] = 0xa;
3b46e624
TS
813
814 /* write all the data */
1640366c
KS
815 ret = qemu_write_full(fd, &magic, sizeof(magic));
816 if (ret != sizeof(magic)) {
b781cce5 817 ret = -errno;
1640366c
KS
818 goto exit;
819 }
820 ret = qemu_write_full(fd, &header, sizeof(header));
821 if (ret != sizeof(header)) {
b781cce5 822 ret = -errno;
1640366c
KS
823 goto exit;
824 }
8979b227 825
1640366c
KS
826 ret = ftruncate(fd, header.grain_offset << 9);
827 if (ret < 0) {
b781cce5 828 ret = -errno;
1640366c
KS
829 goto exit;
830 }
8979b227
FB
831
832 /* write grain directory */
833 lseek(fd, le64_to_cpu(header.rgd_offset) << 9, SEEK_SET);
834 for (i = 0, tmp = header.rgd_offset + gd_size;
1640366c
KS
835 i < gt_count; i++, tmp += gt_size) {
836 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
837 if (ret != sizeof(tmp)) {
b781cce5 838 ret = -errno;
1640366c
KS
839 goto exit;
840 }
841 }
3b46e624 842
8979b227
FB
843 /* write backup grain directory */
844 lseek(fd, le64_to_cpu(header.gd_offset) << 9, SEEK_SET);
845 for (i = 0, tmp = header.gd_offset + gd_size;
1640366c
KS
846 i < gt_count; i++, tmp += gt_size) {
847 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
848 if (ret != sizeof(tmp)) {
b781cce5 849 ret = -errno;
1640366c
KS
850 goto exit;
851 }
852 }
8979b227
FB
853
854 /* compose the descriptor */
855 real_filename = filename;
856 if ((temp_str = strrchr(real_filename, '\\')) != NULL)
857 real_filename = temp_str + 1;
858 if ((temp_str = strrchr(real_filename, '/')) != NULL)
859 real_filename = temp_str + 1;
860 if ((temp_str = strrchr(real_filename, ':')) != NULL)
861 real_filename = temp_str + 1;
7ccfb2eb 862 snprintf(desc, sizeof(desc), desc_template, (unsigned int)time(NULL),
7fd6d9fc
BS
863 total_size, real_filename,
864 (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
865 total_size / (int64_t)(63 * 16));
8979b227
FB
866
867 /* write the descriptor */
868 lseek(fd, le64_to_cpu(header.desc_offset) << 9, SEEK_SET);
1640366c
KS
869 ret = qemu_write_full(fd, desc, strlen(desc));
870 if (ret != strlen(desc)) {
b781cce5 871 ret = -errno;
1640366c
KS
872 goto exit;
873 }
8979b227 874
1640366c
KS
875 ret = 0;
876exit:
8979b227 877 close(fd);
1640366c 878 return ret;
8979b227
FB
879}
880
e2731add 881static void vmdk_close(BlockDriverState *bs)
ea2384d3
FB
882{
883 BDRVVmdkState *s = bs->opaque;
5f4da8c0 884
ea2384d3
FB
885 qemu_free(s->l1_table);
886 qemu_free(s->l2_cache);
5f4da8c0
TS
887 // try to close parent image, if exist
888 vmdk_parent_close(s->hd);
5cbdd273 889 bdrv_delete(s->hd);
ea2384d3
FB
890}
891
7a6cba61
PB
892static void vmdk_flush(BlockDriverState *bs)
893{
894 BDRVVmdkState *s = bs->opaque;
5f4da8c0 895 bdrv_flush(s->hd);
7a6cba61
PB
896}
897
0e7e1989
KW
898
899static QEMUOptionParameter vmdk_create_options[] = {
db08adf5
KW
900 {
901 .name = BLOCK_OPT_SIZE,
902 .type = OPT_SIZE,
903 .help = "Virtual disk size"
904 },
905 {
906 .name = BLOCK_OPT_BACKING_FILE,
907 .type = OPT_STRING,
908 .help = "File name of a base image"
909 },
910 {
911 .name = BLOCK_OPT_COMPAT6,
912 .type = OPT_FLAG,
913 .help = "VMDK version 6 image"
914 },
0e7e1989
KW
915 { NULL }
916};
917
5efa9d5a 918static BlockDriver bdrv_vmdk = {
e60f469c
AJ
919 .format_name = "vmdk",
920 .instance_size = sizeof(BDRVVmdkState),
921 .bdrv_probe = vmdk_probe,
922 .bdrv_open = vmdk_open,
923 .bdrv_read = vmdk_read,
924 .bdrv_write = vmdk_write,
925 .bdrv_close = vmdk_close,
926 .bdrv_create = vmdk_create,
927 .bdrv_flush = vmdk_flush,
928 .bdrv_is_allocated = vmdk_is_allocated,
0e7e1989
KW
929
930 .create_options = vmdk_create_options,
ea2384d3 931};
5efa9d5a
AL
932
933static void bdrv_vmdk_init(void)
934{
935 bdrv_register(&bdrv_vmdk);
936}
937
938block_init(bdrv_vmdk_init);