master
c 1,535 lines 45.3 KB
Raw
1 /*
2 * Block driver for Parallels disk image format
3 *
4 * Copyright (c) 2007 Alex Beregszaszi
5 * Copyright (c) 2015 Denis V. Lunev <den@openvz.org>
6 *
7 * This code was originally based on comparing different disk images created
8 * by Parallels. Currently it is based on opened OpenVZ sources
9 * available at
10 * http://git.openvz.org/?p=ploop;a=summary
11 *
12 * Permission is hereby granted, free of charge, to any person obtaining a copy
13 * of this software and associated documentation files (the "Software"), to deal
14 * in the Software without restriction, including without limitation the rights
15 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 * copies of the Software, and to permit persons to whom the Software is
17 * furnished to do so, subject to the following conditions:
18 *
19 * The above copyright notice and this permission notice shall be included in
20 * all copies or substantial portions of the Software.
21 *
22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 * THE SOFTWARE.
29 */
30
31 #include "qemu/osdep.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "block/block_int.h"
35 #include "block/qdict.h"
36 #include "system/block-backend.h"
37 #include "qemu/module.h"
38 #include "qemu/option.h"
39 #include "qobject/qdict.h"
40 #include "qapi/qobject-input-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "qemu/bswap.h"
43 #include "qemu/bitmap.h"
44 #include "qemu/memalign.h"
45 #include "migration/blocker.h"
46 #include "parallels.h"
47
48 /**************************************************************/
49
50 #define HEADER_MAGIC "WithoutFreeSpace"
51 #define HEADER_MAGIC2 "WithouFreSpacExt"
52 #define HEADER_VERSION 2
53 #define HEADER_INUSE_MAGIC (0x746F6E59)
54 #define MAX_PARALLELS_IMAGE_FACTOR (1ull << 32)
55 #define PARALLELS_HEADER_READ_CHUNK (64 * 1024 * 1024)
56
57 static QEnumLookup prealloc_mode_lookup = {
58 .array = (const char *const[]) {
59 "falloc",
60 "truncate",
61 },
62 .size = PRL_PREALLOC_MODE__MAX
63 };
64
65 #define PARALLELS_OPT_PREALLOC_MODE "prealloc-mode"
66 #define PARALLELS_OPT_PREALLOC_SIZE "prealloc-size"
67
68 static QemuOptsList parallels_runtime_opts = {
69 .name = "parallels",
70 .head = QTAILQ_HEAD_INITIALIZER(parallels_runtime_opts.head),
71 .desc = {
72 {
73 .name = PARALLELS_OPT_PREALLOC_SIZE,
74 .type = QEMU_OPT_SIZE,
75 .help = "Preallocation size on image expansion",
76 .def_value_str = "128M",
77 },
78 {
79 .name = PARALLELS_OPT_PREALLOC_MODE,
80 .type = QEMU_OPT_STRING,
81 .help = "Preallocation mode on image expansion "
82 "(allowed values: falloc, truncate)",
83 .def_value_str = "falloc",
84 },
85 { /* end of list */ },
86 },
87 };
88
89 static QemuOptsList parallels_create_opts = {
90 .name = "parallels-create-opts",
91 .head = QTAILQ_HEAD_INITIALIZER(parallels_create_opts.head),
92 .desc = {
93 {
94 .name = BLOCK_OPT_SIZE,
95 .type = QEMU_OPT_SIZE,
96 .help = "Virtual disk size",
97 },
98 {
99 .name = BLOCK_OPT_CLUSTER_SIZE,
100 .type = QEMU_OPT_SIZE,
101 .help = "Parallels image cluster size",
102 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE),
103 },
104 { /* end of list */ }
105 }
106 };
107
108
109 static int64_t bat2sect(BDRVParallelsState *s, uint32_t idx)
110 {
111 return (uint64_t)le32_to_cpu(s->bat_bitmap[idx]) * s->off_multiplier;
112 }
113
114 static uint32_t bat_entry_off(uint32_t idx)
115 {
116 return sizeof(ParallelsHeader) + sizeof(uint32_t) * idx;
117 }
118
119 static int64_t seek_to_sector(BDRVParallelsState *s, int64_t sector_num)
120 {
121 uint32_t index, offset;
122 int64_t cluster_off;
123
124 index = sector_num / s->tracks;
125 offset = sector_num % s->tracks;
126
127 /* not allocated */
128 if ((index >= s->bat_size) || (s->bat_bitmap[index] == 0)) {
129 return -1;
130 }
131
132 cluster_off = bat2sect(s, index);
133 if (cluster_off < s->data_start || cluster_off + s->tracks > s->data_end) {
134 /* Cluster is outside of the image file or overlaps the header. */
135 return -1;
136 }
137
138 return cluster_off + offset;
139 }
140
141 static int cluster_remainder(BDRVParallelsState *s, int64_t sector_num,
142 int nb_sectors)
143 {
144 int ret = s->tracks - sector_num % s->tracks;
145 return MIN(nb_sectors, ret);
146 }
147
148 static uint32_t host_cluster_index(BDRVParallelsState *s, int64_t off)
149 {
150 off -= s->data_start << BDRV_SECTOR_BITS;
151 return off / s->cluster_size;
152 }
153
154 static int64_t block_status(BDRVParallelsState *s, int64_t sector_num,
155 int nb_sectors, int *pnum)
156 {
157 int64_t start_off = -2, prev_end_off = -2;
158
159 *pnum = 0;
160 while (nb_sectors > 0 || start_off == -2) {
161 int64_t offset = seek_to_sector(s, sector_num);
162 int to_end;
163
164 if (start_off == -2) {
165 start_off = offset;
166 prev_end_off = offset;
167 } else if (offset != prev_end_off) {
168 break;
169 }
170
171 to_end = cluster_remainder(s, sector_num, nb_sectors);
172 nb_sectors -= to_end;
173 sector_num += to_end;
174 *pnum += to_end;
175
176 if (offset > 0) {
177 prev_end_off += to_end;
178 }
179 }
180 return start_off;
181 }
182
183 static void parallels_set_bat_entry(BDRVParallelsState *s,
184 uint32_t index, uint32_t offset)
185 {
186 s->bat_bitmap[index] = cpu_to_le32(offset);
187 bitmap_set(s->bat_dirty_bmap, bat_entry_off(index) / s->bat_dirty_block, 1);
188 }
189
190 static int mark_used(BlockDriverState *bs, unsigned long *bitmap,
191 uint32_t bitmap_size, int64_t off, uint32_t count)
192 {
193 BDRVParallelsState *s = bs->opaque;
194 uint32_t cluster_index = host_cluster_index(s, off);
195 unsigned long next_used;
196 if ((uint64_t)cluster_index + count > bitmap_size) {
197 return -E2BIG;
198 }
199 next_used = find_next_bit(bitmap, bitmap_size, cluster_index);
200 if (next_used < (uint64_t)cluster_index + count) {
201 return -EBUSY;
202 }
203 bitmap_set(bitmap, cluster_index, count);
204 return 0;
205 }
206
207 /*
208 * Collect used bitmap. The image can contain errors, we should fill the
209 * bitmap anyway, as much as we can. This information will be used for
210 * error resolution.
211 */
212 static int GRAPH_RDLOCK parallels_fill_used_bitmap(BlockDriverState *bs)
213 {
214 BDRVParallelsState *s = bs->opaque;
215 int64_t payload_bytes;
216 uint32_t i;
217 int err = 0;
218
219 payload_bytes = bdrv_getlength(bs->file->bs);
220 if (payload_bytes < 0) {
221 return payload_bytes;
222 }
223 payload_bytes -= s->data_start * BDRV_SECTOR_SIZE;
224 if (payload_bytes < 0) {
225 return -EINVAL;
226 }
227
228 s->used_bmap_size = DIV_ROUND_UP(payload_bytes, s->cluster_size);
229 if (s->used_bmap_size == 0) {
230 return 0;
231 }
232 s->used_bmap = bitmap_try_new(s->used_bmap_size);
233 if (s->used_bmap == NULL) {
234 return -ENOMEM;
235 }
236
237 for (i = 0; i < s->bat_size; i++) {
238 int err2;
239 int64_t host_off = bat2sect(s, i) << BDRV_SECTOR_BITS;
240 if (host_off == 0) {
241 continue;
242 }
243
244 err2 = mark_used(bs, s->used_bmap, s->used_bmap_size, host_off, 1);
245 if (err2 < 0 && err == 0) {
246 err = err2;
247 }
248 }
249 return err;
250 }
251
252 static void parallels_free_used_bitmap(BlockDriverState *bs)
253 {
254 BDRVParallelsState *s = bs->opaque;
255 s->used_bmap_size = 0;
256 g_free(s->used_bmap);
257 }
258
259 static int64_t coroutine_fn GRAPH_RDLOCK
260 allocate_clusters(BlockDriverState *bs, int64_t sector_num,
261 int nb_sectors, int *pnum)
262 {
263 int ret = 0;
264 BDRVParallelsState *s = bs->opaque;
265 int64_t i, pos, idx, to_allocate, first_free, host_off;
266
267 pos = block_status(s, sector_num, nb_sectors, pnum);
268 if (pos > 0) {
269 return pos;
270 }
271
272 idx = sector_num / s->tracks;
273 to_allocate = DIV_ROUND_UP(sector_num + *pnum, s->tracks) - idx;
274
275 /*
276 * This function is called only by parallels_co_writev(), which will never
277 * pass a sector_num at or beyond the end of the image (because the block
278 * layer never passes such a sector_num to that function). Therefore, idx
279 * is always below s->bat_size.
280 * block_status() will limit *pnum so that sector_num + *pnum will not
281 * exceed the image end. Therefore, idx + to_allocate cannot exceed
282 * s->bat_size.
283 * Note that s->bat_size is an unsigned int, therefore idx + to_allocate
284 * will always fit into a uint32_t.
285 */
286 assert(idx < s->bat_size && idx + to_allocate <= s->bat_size);
287
288 first_free = find_first_zero_bit(s->used_bmap, s->used_bmap_size);
289 if (first_free == s->used_bmap_size) {
290 uint32_t new_usedsize;
291 int64_t bytes = to_allocate * s->cluster_size;
292 bytes += s->prealloc_size * BDRV_SECTOR_SIZE;
293
294 host_off = s->data_end * BDRV_SECTOR_SIZE;
295
296 /*
297 * We require the expanded size to read back as zero. If the
298 * user permitted truncation, we try that; but if it fails, we
299 * force the safer-but-slower fallocate.
300 */
301 if (s->prealloc_mode == PRL_PREALLOC_MODE_TRUNCATE) {
302 ret = bdrv_co_truncate(bs->file, host_off + bytes,
303 false, PREALLOC_MODE_OFF,
304 BDRV_REQ_ZERO_WRITE, NULL);
305 if (ret == -ENOTSUP) {
306 s->prealloc_mode = PRL_PREALLOC_MODE_FALLOCATE;
307 }
308 }
309 if (s->prealloc_mode == PRL_PREALLOC_MODE_FALLOCATE) {
310 ret = bdrv_co_pwrite_zeroes(bs->file, host_off, bytes, 0);
311 }
312 if (ret < 0) {
313 return ret;
314 }
315
316 new_usedsize = s->used_bmap_size + bytes / s->cluster_size;
317 s->used_bmap = bitmap_zero_extend(s->used_bmap, s->used_bmap_size,
318 new_usedsize);
319 s->used_bmap_size = new_usedsize;
320 } else {
321 int64_t next_used;
322 next_used = find_next_bit(s->used_bmap, s->used_bmap_size, first_free);
323
324 /* Not enough continuous clusters in the middle, adjust the size */
325 if (next_used - first_free < to_allocate) {
326 to_allocate = next_used - first_free;
327 *pnum = (idx + to_allocate) * s->tracks - sector_num;
328 }
329
330 host_off = s->data_start * BDRV_SECTOR_SIZE;
331 host_off += first_free * s->cluster_size;
332
333 /*
334 * No need to preallocate if we are using tail area from the above
335 * branch. In the other case we are likely re-using hole. Preallocate
336 * the space if required by the prealloc_mode.
337 */
338 if (s->prealloc_mode == PRL_PREALLOC_MODE_FALLOCATE &&
339 host_off < s->data_end * BDRV_SECTOR_SIZE) {
340 ret = bdrv_co_pwrite_zeroes(bs->file, host_off,
341 s->cluster_size * to_allocate, 0);
342 if (ret < 0) {
343 return ret;
344 }
345 }
346 }
347
348 /*
349 * Try to read from backing to fill empty clusters
350 * FIXME: 1. previous write_zeroes may be redundant
351 * 2. most of data we read from backing will be rewritten by
352 * parallels_co_writev. On aligned-to-cluster write we do not need
353 * this read at all.
354 * 3. it would be good to combine write of data from backing and new
355 * data into one write call.
356 */
357 if (bs->backing) {
358 int64_t nb_cow_sectors = to_allocate * s->tracks;
359 int64_t nb_cow_bytes = nb_cow_sectors << BDRV_SECTOR_BITS;
360 void *buf = qemu_blockalign(bs, nb_cow_bytes);
361
362 ret = bdrv_co_pread(bs->backing, idx * s->tracks * BDRV_SECTOR_SIZE,
363 nb_cow_bytes, buf, 0);
364 if (ret < 0) {
365 qemu_vfree(buf);
366 return ret;
367 }
368
369 ret = bdrv_co_pwrite(bs->file, s->data_end * BDRV_SECTOR_SIZE,
370 nb_cow_bytes, buf, 0);
371 qemu_vfree(buf);
372 if (ret < 0) {
373 return ret;
374 }
375 }
376
377 ret = mark_used(bs, s->used_bmap, s->used_bmap_size, host_off, to_allocate);
378 if (ret < 0) {
379 /* Image consistency is broken. Alarm! */
380 return ret;
381 }
382 for (i = 0; i < to_allocate; i++) {
383 parallels_set_bat_entry(s, idx + i,
384 host_off / BDRV_SECTOR_SIZE / s->off_multiplier);
385 host_off += s->cluster_size;
386 }
387 if (host_off > s->data_end * BDRV_SECTOR_SIZE) {
388 s->data_end = host_off / BDRV_SECTOR_SIZE;
389 }
390
391 return bat2sect(s, idx) + sector_num % s->tracks;
392 }
393
394
395 static int coroutine_fn GRAPH_RDLOCK
396 parallels_co_flush_to_os(BlockDriverState *bs)
397 {
398 BDRVParallelsState *s = bs->opaque;
399 unsigned long size = DIV_ROUND_UP(s->header_size, s->bat_dirty_block);
400 unsigned long bit;
401
402 qemu_co_mutex_lock(&s->lock);
403
404 bit = find_first_bit(s->bat_dirty_bmap, size);
405 while (bit < size) {
406 uint32_t off = bit * s->bat_dirty_block;
407 uint32_t to_write = s->bat_dirty_block;
408 int ret;
409
410 if (off + to_write > s->header_size) {
411 to_write = s->header_size - off;
412 }
413 ret = bdrv_co_pwrite(bs->file, off, to_write,
414 (uint8_t *)s->header + off, 0);
415 if (ret < 0) {
416 qemu_co_mutex_unlock(&s->lock);
417 return ret;
418 }
419 bit = find_next_bit(s->bat_dirty_bmap, size, bit + 1);
420 }
421 bitmap_zero(s->bat_dirty_bmap, size);
422
423 qemu_co_mutex_unlock(&s->lock);
424 return 0;
425 }
426
427 static int coroutine_fn GRAPH_RDLOCK
428 parallels_co_block_status(BlockDriverState *bs, unsigned int mode,
429 int64_t offset, int64_t bytes, int64_t *pnum,
430 int64_t *map, BlockDriverState **file)
431 {
432 BDRVParallelsState *s = bs->opaque;
433 int count;
434
435 assert(QEMU_IS_ALIGNED(offset | bytes, BDRV_SECTOR_SIZE));
436 qemu_co_mutex_lock(&s->lock);
437 offset = block_status(s, offset >> BDRV_SECTOR_BITS,
438 bytes >> BDRV_SECTOR_BITS, &count);
439 qemu_co_mutex_unlock(&s->lock);
440
441 *pnum = count * BDRV_SECTOR_SIZE;
442 if (offset < 0) {
443 return 0;
444 }
445
446 *map = offset * BDRV_SECTOR_SIZE;
447 *file = bs->file->bs;
448 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
449 }
450
451 static int coroutine_fn GRAPH_RDLOCK
452 parallels_co_writev(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
453 QEMUIOVector *qiov, int flags)
454 {
455 BDRVParallelsState *s = bs->opaque;
456 uint64_t bytes_done = 0;
457 QEMUIOVector hd_qiov;
458 int ret = 0;
459
460 qemu_iovec_init(&hd_qiov, qiov->niov);
461
462 while (nb_sectors > 0) {
463 int64_t position;
464 int n, nbytes;
465
466 qemu_co_mutex_lock(&s->lock);
467 position = allocate_clusters(bs, sector_num, nb_sectors, &n);
468 qemu_co_mutex_unlock(&s->lock);
469 if (position < 0) {
470 ret = (int)position;
471 break;
472 }
473
474 nbytes = n << BDRV_SECTOR_BITS;
475
476 qemu_iovec_reset(&hd_qiov);
477 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, nbytes);
478
479 ret = bdrv_co_pwritev(bs->file, position * BDRV_SECTOR_SIZE, nbytes,
480 &hd_qiov, 0);
481 if (ret < 0) {
482 break;
483 }
484
485 nb_sectors -= n;
486 sector_num += n;
487 bytes_done += nbytes;
488 }
489
490 qemu_iovec_destroy(&hd_qiov);
491 return ret;
492 }
493
494 static int coroutine_fn GRAPH_RDLOCK
495 parallels_co_readv(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
496 QEMUIOVector *qiov)
497 {
498 BDRVParallelsState *s = bs->opaque;
499 uint64_t bytes_done = 0;
500 QEMUIOVector hd_qiov;
501 int ret = 0;
502
503 qemu_iovec_init(&hd_qiov, qiov->niov);
504
505 while (nb_sectors > 0) {
506 int64_t position;
507 int n, nbytes;
508
509 qemu_co_mutex_lock(&s->lock);
510 position = block_status(s, sector_num, nb_sectors, &n);
511 qemu_co_mutex_unlock(&s->lock);
512
513 nbytes = n << BDRV_SECTOR_BITS;
514
515 qemu_iovec_reset(&hd_qiov);
516 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, nbytes);
517
518 if (position < 0) {
519 if (bs->backing) {
520 ret = bdrv_co_preadv(bs->backing, sector_num * BDRV_SECTOR_SIZE,
521 nbytes, &hd_qiov, 0);
522 if (ret < 0) {
523 break;
524 }
525 } else {
526 qemu_iovec_memset(&hd_qiov, 0, 0, nbytes);
527 }
528 } else {
529 ret = bdrv_co_preadv(bs->file, position * BDRV_SECTOR_SIZE, nbytes,
530 &hd_qiov, 0);
531 if (ret < 0) {
532 break;
533 }
534 }
535
536 nb_sectors -= n;
537 sector_num += n;
538 bytes_done += nbytes;
539 }
540
541 qemu_iovec_destroy(&hd_qiov);
542 return ret;
543 }
544
545
546 static int coroutine_fn GRAPH_RDLOCK
547 parallels_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
548 {
549 int ret = 0;
550 uint32_t cluster, count;
551 BDRVParallelsState *s = bs->opaque;
552
553 /*
554 * The image does not support ZERO mark inside the BAT, which means that
555 * stale data could be exposed from the backing file.
556 */
557 if (bs->backing) {
558 return -ENOTSUP;
559 }
560
561 if (!QEMU_IS_ALIGNED(offset, s->cluster_size)) {
562 return -ENOTSUP;
563 } else if (!QEMU_IS_ALIGNED(bytes, s->cluster_size)) {
564 return -ENOTSUP;
565 }
566
567 cluster = offset / s->cluster_size;
568 count = bytes / s->cluster_size;
569
570 qemu_co_mutex_lock(&s->lock);
571 for (; count > 0; cluster++, count--) {
572 int64_t host_off = bat2sect(s, cluster) << BDRV_SECTOR_BITS;
573 if (host_off == 0) {
574 continue;
575 }
576
577 ret = bdrv_co_pdiscard(bs->file, host_off, s->cluster_size);
578 if (ret < 0) {
579 goto done;
580 }
581
582 parallels_set_bat_entry(s, cluster, 0);
583 bitmap_clear(s->used_bmap, host_cluster_index(s, host_off), 1);
584 }
585 done:
586 qemu_co_mutex_unlock(&s->lock);
587 return ret;
588 }
589
590 static int coroutine_fn GRAPH_RDLOCK
591 parallels_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
592 BdrvRequestFlags flags)
593 {
594 /*
595 * The zero flag is missed in the Parallels format specification. We can
596 * resort to discard if we have no backing file (this condition is checked
597 * inside parallels_co_pdiscard().
598 */
599 return parallels_co_pdiscard(bs, offset, bytes);
600 }
601
602
603 static void parallels_check_unclean(BlockDriverState *bs,
604 BdrvCheckResult *res,
605 BdrvCheckMode fix)
606 {
607 BDRVParallelsState *s = bs->opaque;
608
609 if (!s->header_unclean) {
610 return;
611 }
612
613 fprintf(stderr, "%s image was not closed correctly\n",
614 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR");
615 res->corruptions++;
616 if (fix & BDRV_FIX_ERRORS) {
617 /* parallels_close will do the job right */
618 res->corruptions_fixed++;
619 s->header_unclean = false;
620 }
621 }
622
623 /*
624 * Returns true if data_off is correct, otherwise false. In both cases
625 * correct_offset is set to the proper value.
626 */
627 static bool parallels_test_data_off(BDRVParallelsState *s,
628 int64_t file_nb_sectors,
629 uint32_t *correct_offset)
630 {
631 uint32_t data_off, min_off;
632 bool old_magic;
633
634 /*
635 * There are two slightly different image formats: with "WithoutFreeSpace"
636 * or "WithouFreSpacExt" magic words. Call the first one as "old magic".
637 * In such images data_off field can be zero. In this case the offset is
638 * calculated as the end of BAT table plus some padding to ensure sector
639 * size alignment.
640 */
641 old_magic = !memcmp(s->header->magic, HEADER_MAGIC, 16);
642
643 min_off = DIV_ROUND_UP(bat_entry_off(s->bat_size), BDRV_SECTOR_SIZE);
644 if (!old_magic) {
645 min_off = ROUND_UP(min_off, s->cluster_size / BDRV_SECTOR_SIZE);
646 }
647
648 if (correct_offset) {
649 *correct_offset = min_off;
650 }
651
652 data_off = le32_to_cpu(s->header->data_off);
653 if (data_off == 0 && old_magic) {
654 return true;
655 }
656
657 if (data_off < min_off || data_off > file_nb_sectors) {
658 return false;
659 }
660
661 if (correct_offset) {
662 *correct_offset = data_off;
663 }
664
665 return true;
666 }
667
668 static int coroutine_fn GRAPH_RDLOCK
669 parallels_check_data_off(BlockDriverState *bs, BdrvCheckResult *res,
670 BdrvCheckMode fix)
671 {
672 BDRVParallelsState *s = bs->opaque;
673 int64_t file_size;
674 uint32_t data_off;
675
676 file_size = bdrv_co_nb_sectors(bs->file->bs);
677 if (file_size < 0) {
678 res->check_errors++;
679 return file_size;
680 }
681
682 if (parallels_test_data_off(s, file_size, &data_off)) {
683 return 0;
684 }
685
686 res->corruptions++;
687 if (fix & BDRV_FIX_ERRORS) {
688 int err;
689 s->header->data_off = cpu_to_le32(data_off);
690 s->data_start = data_off;
691
692 parallels_free_used_bitmap(bs);
693 err = parallels_fill_used_bitmap(bs);
694 if (err == -ENOMEM) {
695 res->check_errors++;
696 return err;
697 }
698
699 res->corruptions_fixed++;
700 }
701
702 fprintf(stderr, "%s data_off field has incorrect value\n",
703 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR");
704
705 return 0;
706 }
707
708 static int coroutine_fn GRAPH_RDLOCK
709 parallels_check_outside_image(BlockDriverState *bs, BdrvCheckResult *res,
710 BdrvCheckMode fix)
711 {
712 BDRVParallelsState *s = bs->opaque;
713 uint32_t i;
714 int64_t off, high_off, size, data_start_off;
715
716 size = bdrv_co_getlength(bs->file->bs);
717 if (size < 0) {
718 res->check_errors++;
719 return size;
720 }
721 data_start_off = s->data_start << BDRV_SECTOR_BITS;
722
723 high_off = 0;
724 for (i = 0; i < s->bat_size; i++) {
725 off = bat2sect(s, i) << BDRV_SECTOR_BITS;
726 if (off == 0) {
727 continue;
728 }
729 if (off < data_start_off || off + s->cluster_size > size) {
730 fprintf(stderr, "%s cluster %u is outside image\n",
731 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
732 res->corruptions++;
733 if (fix & BDRV_FIX_ERRORS) {
734 parallels_set_bat_entry(s, i, 0);
735 res->corruptions_fixed++;
736 }
737 continue;
738 }
739 if (high_off < off) {
740 high_off = off;
741 }
742 }
743
744 if (high_off == 0) {
745 res->image_end_offset = s->data_end << BDRV_SECTOR_BITS;
746 } else {
747 res->image_end_offset = high_off + s->cluster_size;
748 s->data_end = res->image_end_offset >> BDRV_SECTOR_BITS;
749 }
750
751 return 0;
752 }
753
754 static int coroutine_fn GRAPH_RDLOCK
755 parallels_check_leak(BlockDriverState *bs, BdrvCheckResult *res,
756 BdrvCheckMode fix, bool explicit)
757 {
758 BDRVParallelsState *s = bs->opaque;
759 int64_t size;
760 int ret;
761
762 size = bdrv_co_getlength(bs->file->bs);
763 if (size < 0) {
764 res->check_errors++;
765 return size;
766 }
767
768 if (size > res->image_end_offset) {
769 int64_t count;
770 count = DIV_ROUND_UP(size - res->image_end_offset, s->cluster_size);
771 if (explicit) {
772 fprintf(stderr,
773 "%s space leaked at the end of the image %" PRId64 "\n",
774 fix & BDRV_FIX_LEAKS ? "Repairing" : "ERROR",
775 size - res->image_end_offset);
776 res->leaks += count;
777 }
778 if (fix & BDRV_FIX_LEAKS) {
779 Error *local_err = NULL;
780
781 /*
782 * In order to really repair the image, we must shrink it.
783 * That means we have to pass exact=true.
784 */
785 ret = bdrv_co_truncate(bs->file, res->image_end_offset, true,
786 PREALLOC_MODE_OFF, 0, &local_err);
787 if (ret < 0) {
788 error_report_err(local_err);
789 res->check_errors++;
790 return ret;
791 }
792 if (explicit) {
793 res->leaks_fixed += count;
794 }
795 }
796 }
797
798 return 0;
799 }
800
801 static int coroutine_fn GRAPH_RDLOCK
802 parallels_check_duplicate(BlockDriverState *bs, BdrvCheckResult *res,
803 BdrvCheckMode fix)
804 {
805 BDRVParallelsState *s = bs->opaque;
806 int64_t host_off, host_sector, guest_sector;
807 unsigned long *bitmap;
808 uint32_t i, bitmap_size, bat_entry;
809 int n, ret = 0;
810 uint64_t *buf = NULL;
811 bool fixed = false;
812
813 /*
814 * Create a bitmap of used clusters.
815 * If a bit is set, there is a BAT entry pointing to this cluster.
816 * Loop through the BAT entries, check bits relevant to an entry offset.
817 * If bit is set, this entry is duplicated. Otherwise set the bit.
818 *
819 * We shouldn't worry about newly allocated clusters outside the image
820 * because they are created higher then any existing cluster pointed by
821 * a BAT entry.
822 */
823 bitmap_size = host_cluster_index(s, res->image_end_offset);
824 if (bitmap_size == 0) {
825 return 0;
826 }
827 if (res->image_end_offset % s->cluster_size) {
828 /* A not aligned image end leads to a bitmap shorter by 1 */
829 bitmap_size++;
830 }
831
832 bitmap = bitmap_new(bitmap_size);
833
834 buf = qemu_blockalign(bs, s->cluster_size);
835
836 for (i = 0; i < s->bat_size; i++) {
837 host_off = bat2sect(s, i) << BDRV_SECTOR_BITS;
838 if (host_off == 0) {
839 continue;
840 }
841
842 ret = mark_used(bs, bitmap, bitmap_size, host_off, 1);
843 assert(ret != -E2BIG);
844 if (ret == 0) {
845 continue;
846 }
847
848 /* this cluster duplicates another one */
849 fprintf(stderr, "%s duplicate offset in BAT entry %u\n",
850 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
851
852 res->corruptions++;
853
854 if (!(fix & BDRV_FIX_ERRORS)) {
855 continue;
856 }
857
858 /*
859 * Reset the entry and allocate a new cluster
860 * for the relevant guest offset. In this way we let
861 * the lower layer to place the new cluster properly.
862 * Copy the original cluster to the allocated one.
863 * But before save the old offset value for repairing
864 * if we have an error.
865 */
866 bat_entry = s->bat_bitmap[i];
867 parallels_set_bat_entry(s, i, 0);
868
869 ret = bdrv_co_pread(bs->file, host_off, s->cluster_size, buf, 0);
870 if (ret < 0) {
871 res->check_errors++;
872 goto out_repair_bat;
873 }
874
875 guest_sector = (i * (int64_t)s->cluster_size) >> BDRV_SECTOR_BITS;
876 host_sector = allocate_clusters(bs, guest_sector, s->tracks, &n);
877 if (host_sector < 0) {
878 res->check_errors++;
879 goto out_repair_bat;
880 }
881 host_off = host_sector << BDRV_SECTOR_BITS;
882
883 ret = bdrv_co_pwrite(bs->file, host_off, s->cluster_size, buf, 0);
884 if (ret < 0) {
885 res->check_errors++;
886 goto out_repair_bat;
887 }
888
889 if (host_off + s->cluster_size > res->image_end_offset) {
890 res->image_end_offset = host_off + s->cluster_size;
891 }
892
893 /*
894 * In the future allocate_cluster() will reuse holed offsets
895 * inside the image. Keep the used clusters bitmap content
896 * consistent for the new allocated clusters too.
897 *
898 * Note, clusters allocated outside the current image are not
899 * considered, and the bitmap size doesn't change. This specifically
900 * means that -E2BIG is OK.
901 */
902 ret = mark_used(bs, bitmap, bitmap_size, host_off, 1);
903 if (ret == -EBUSY) {
904 res->check_errors++;
905 goto out_repair_bat;
906 }
907
908 fixed = true;
909 res->corruptions_fixed++;
910
911 }
912
913 if (fixed) {
914 /*
915 * When new clusters are allocated, the file size increases by
916 * 128 Mb. We need to truncate the file to the right size. Let
917 * the leak fix code make its job without res changing.
918 */
919 ret = parallels_check_leak(bs, res, fix, false);
920 }
921
922 out_free:
923 g_free(buf);
924 g_free(bitmap);
925 return ret;
926 /*
927 * We can get here only from places where index and old_offset have
928 * meaningful values.
929 */
930 out_repair_bat:
931 s->bat_bitmap[i] = bat_entry;
932 goto out_free;
933 }
934
935 static void parallels_collect_statistics(BlockDriverState *bs,
936 BdrvCheckResult *res,
937 BdrvCheckMode fix)
938 {
939 BDRVParallelsState *s = bs->opaque;
940 int64_t off, prev_off;
941 uint32_t i;
942
943 res->bfi.total_clusters = s->bat_size;
944 res->bfi.compressed_clusters = 0; /* compression is not supported */
945
946 prev_off = 0;
947 for (i = 0; i < s->bat_size; i++) {
948 off = bat2sect(s, i) << BDRV_SECTOR_BITS;
949 /*
950 * If BDRV_FIX_ERRORS is not set, out-of-image BAT entries were not
951 * fixed. Skip not allocated and out-of-image BAT entries.
952 */
953 if (off == 0 || off + s->cluster_size > res->image_end_offset) {
954 prev_off = 0;
955 continue;
956 }
957
958 if (prev_off != 0 && (prev_off + s->cluster_size) != off) {
959 res->bfi.fragmented_clusters++;
960 }
961 prev_off = off;
962 res->bfi.allocated_clusters++;
963 }
964 }
965
966 static int coroutine_fn GRAPH_RDLOCK
967 parallels_co_check(BlockDriverState *bs, BdrvCheckResult *res,
968 BdrvCheckMode fix)
969 {
970 BDRVParallelsState *s = bs->opaque;
971 int ret;
972
973 WITH_QEMU_LOCK_GUARD(&s->lock) {
974 parallels_check_unclean(bs, res, fix);
975
976 ret = parallels_check_data_off(bs, res, fix);
977 if (ret < 0) {
978 return ret;
979 }
980
981 ret = parallels_check_outside_image(bs, res, fix);
982 if (ret < 0) {
983 return ret;
984 }
985
986 ret = parallels_check_leak(bs, res, fix, true);
987 if (ret < 0) {
988 return ret;
989 }
990
991 ret = parallels_check_duplicate(bs, res, fix);
992 if (ret < 0) {
993 return ret;
994 }
995
996 parallels_collect_statistics(bs, res, fix);
997 }
998
999 ret = bdrv_co_flush(bs);
1000 if (ret < 0) {
1001 res->check_errors++;
1002 }
1003
1004 return ret;
1005 }
1006
1007
1008 static int coroutine_fn GRAPH_UNLOCKED
1009 parallels_co_create(BlockdevCreateOptions* opts, Error **errp)
1010 {
1011 BlockdevCreateOptionsParallels *parallels_opts;
1012 BlockDriverState *bs;
1013 BlockBackend *blk;
1014 int64_t total_size, cl_size, bat_count;
1015 uint64_t cylinders;
1016 uint32_t bat_entries, bat_sectors;
1017 ParallelsHeader header;
1018 uint8_t tmp[BDRV_SECTOR_SIZE];
1019 int ret;
1020
1021 assert(opts->driver == BLOCKDEV_DRIVER_PARALLELS);
1022 parallels_opts = &opts->u.parallels;
1023
1024 /* Sanity checks */
1025 total_size = parallels_opts->size;
1026
1027 if (parallels_opts->has_cluster_size) {
1028 cl_size = parallels_opts->cluster_size;
1029 } else {
1030 cl_size = DEFAULT_CLUSTER_SIZE;
1031 }
1032
1033 /* Bounds cl_size so the multiplication below can't overflow int64_t. */
1034 if (cl_size >= INT64_MAX / MAX_PARALLELS_IMAGE_FACTOR) {
1035 error_setg(errp, "Cluster size is too large");
1036 return -EINVAL;
1037 }
1038 if (cl_size <= 0 || total_size >= MAX_PARALLELS_IMAGE_FACTOR * cl_size) {
1039 error_setg(errp, "Image size is too large for this cluster size");
1040 return -E2BIG;
1041 }
1042
1043 bat_count = DIV_ROUND_UP(total_size, cl_size);
1044 if (bat_count > INT_MAX / (int64_t)sizeof(uint32_t)) {
1045 error_setg(errp, "Catalog too large");
1046 return -EFBIG;
1047 }
1048
1049 if (!QEMU_IS_ALIGNED(total_size, BDRV_SECTOR_SIZE)) {
1050 error_setg(errp, "Image size must be a multiple of 512 bytes");
1051 return -EINVAL;
1052 }
1053
1054 if (!QEMU_IS_ALIGNED(cl_size, BDRV_SECTOR_SIZE)) {
1055 error_setg(errp, "Cluster size must be a multiple of 512 bytes");
1056 return -EINVAL;
1057 }
1058
1059 /* Create BlockBackend to write to the image */
1060 bs = bdrv_co_open_blockdev_ref(parallels_opts->file, errp);
1061 if (bs == NULL) {
1062 return -EIO;
1063 }
1064
1065 blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
1066 errp);
1067 if (!blk) {
1068 ret = -EPERM;
1069 goto out;
1070 }
1071 blk_set_allow_write_beyond_eof(blk, true);
1072
1073 /* Create image format */
1074 bat_entries = bat_count;
1075 bat_sectors = DIV_ROUND_UP(bat_entry_off(bat_entries), cl_size);
1076 bat_sectors = (bat_sectors * cl_size) >> BDRV_SECTOR_BITS;
1077
1078 memset(&header, 0, sizeof(header));
1079 memcpy(header.magic, HEADER_MAGIC2, sizeof(header.magic));
1080 header.version = cpu_to_le32(HEADER_VERSION);
1081 /* don't care much about geometry, it is not used on image level */
1082 header.heads = cpu_to_le32(HEADS_NUMBER);
1083 cylinders = total_size / BDRV_SECTOR_SIZE / HEADS_NUMBER / SEC_IN_CYL;
1084 /* Write only by spec, do not care */
1085 if (cylinders >= UINT32_MAX) {
1086 cylinders = UINT32_MAX;
1087 }
1088 header.cylinders = cpu_to_le32(cylinders);
1089 header.tracks = cpu_to_le32(cl_size >> BDRV_SECTOR_BITS);
1090 header.bat_entries = cpu_to_le32(bat_entries);
1091 header.nb_sectors = cpu_to_le64(DIV_ROUND_UP(total_size, BDRV_SECTOR_SIZE));
1092 header.data_off = cpu_to_le32(bat_sectors);
1093
1094 /* write all the data */
1095 memset(tmp, 0, sizeof(tmp));
1096 memcpy(tmp, &header, sizeof(header));
1097
1098 ret = blk_co_pwrite(blk, 0, BDRV_SECTOR_SIZE, tmp, 0);
1099 if (ret < 0) {
1100 goto exit;
1101 }
1102 ret = blk_co_pwrite_zeroes(blk, BDRV_SECTOR_SIZE,
1103 (bat_sectors - 1) << BDRV_SECTOR_BITS, 0);
1104 if (ret < 0) {
1105 goto exit;
1106 }
1107
1108 ret = 0;
1109 out:
1110 blk_co_unref(blk);
1111 bdrv_co_unref(bs);
1112 return ret;
1113
1114 exit:
1115 error_setg_errno(errp, -ret, "Failed to create Parallels image");
1116 goto out;
1117 }
1118
1119 static int coroutine_fn GRAPH_UNLOCKED
1120 parallels_co_create_opts(BlockDriver *drv, const char *filename,
1121 QemuOpts *opts, Error **errp)
1122 {
1123 BlockdevCreateOptions *create_options = NULL;
1124 BlockDriverState *bs = NULL;
1125 QDict *qdict;
1126 Visitor *v;
1127 int ret;
1128
1129 static const QDictRenames opt_renames[] = {
1130 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
1131 { NULL, NULL },
1132 };
1133
1134 /* Parse options and convert legacy syntax */
1135 qdict = qemu_opts_to_qdict_filtered(opts, NULL, &parallels_create_opts,
1136 true);
1137
1138 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
1139 ret = -EINVAL;
1140 goto done;
1141 }
1142
1143 /* Create and open the file (protocol layer) */
1144 ret = bdrv_co_create_file(filename, opts, true, errp);
1145 if (ret < 0) {
1146 goto done;
1147 }
1148
1149 bs = bdrv_co_open(filename, NULL, NULL,
1150 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
1151 if (bs == NULL) {
1152 ret = -EIO;
1153 goto done;
1154 }
1155
1156 /* Now get the QAPI type BlockdevCreateOptions */
1157 qdict_put_str(qdict, "driver", "parallels");
1158 qdict_put_str(qdict, "file", bs->node_name);
1159
1160 v = qobject_input_visitor_new_flat_confused(qdict, errp);
1161 if (!v) {
1162 ret = -EINVAL;
1163 goto done;
1164 }
1165
1166 visit_type_BlockdevCreateOptions(v, NULL, &create_options, errp);
1167 visit_free(v);
1168 if (!create_options) {
1169 ret = -EINVAL;
1170 goto done;
1171 }
1172
1173 /* Silently round up sizes */
1174 create_options->u.parallels.size =
1175 ROUND_UP(create_options->u.parallels.size, BDRV_SECTOR_SIZE);
1176 create_options->u.parallels.cluster_size =
1177 ROUND_UP(create_options->u.parallels.cluster_size, BDRV_SECTOR_SIZE);
1178
1179 /* Create the Parallels image (format layer) */
1180 ret = parallels_co_create(create_options, errp);
1181 if (ret < 0) {
1182 goto done;
1183 }
1184 ret = 0;
1185
1186 done:
1187 qobject_unref(qdict);
1188 bdrv_co_unref(bs);
1189 qapi_free_BlockdevCreateOptions(create_options);
1190 return ret;
1191 }
1192
1193
1194 static int parallels_probe(const uint8_t *buf, int buf_size,
1195 const char *filename)
1196 {
1197 const ParallelsHeader *ph = (const void *)buf;
1198
1199 if (buf_size < sizeof(ParallelsHeader)) {
1200 return 0;
1201 }
1202
1203 if ((!memcmp(ph->magic, HEADER_MAGIC, 16) ||
1204 !memcmp(ph->magic, HEADER_MAGIC2, 16)) &&
1205 (le32_to_cpu(ph->version) == HEADER_VERSION)) {
1206 return 100;
1207 }
1208
1209 return 0;
1210 }
1211
1212 static int GRAPH_RDLOCK parallels_update_header(BlockDriverState *bs)
1213 {
1214 BDRVParallelsState *s = bs->opaque;
1215 unsigned size = MAX(bdrv_opt_mem_align(bs->file->bs),
1216 sizeof(ParallelsHeader));
1217
1218 if (size > s->header_size) {
1219 size = s->header_size;
1220 }
1221 return bdrv_pwrite_sync(bs->file, 0, size, s->header, 0);
1222 }
1223
1224
1225 static int parallels_opts_prealloc(BlockDriverState *bs, QDict *options,
1226 Error **errp)
1227 {
1228 int err;
1229 char *buf;
1230 int64_t bytes;
1231 BDRVParallelsState *s = bs->opaque;
1232 Error *local_err = NULL;
1233 QemuOpts *opts = qemu_opts_create(&parallels_runtime_opts, NULL, 0, errp);
1234 if (!opts) {
1235 return -ENOMEM;
1236 }
1237
1238 err = -EINVAL;
1239 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1240 goto done;
1241 }
1242
1243 bytes = qemu_opt_get_size_del(opts, PARALLELS_OPT_PREALLOC_SIZE, 0);
1244 s->prealloc_size = bytes >> BDRV_SECTOR_BITS;
1245 buf = qemu_opt_get_del(opts, PARALLELS_OPT_PREALLOC_MODE);
1246 /* prealloc_mode can be downgraded later during allocate_clusters */
1247 s->prealloc_mode = qapi_enum_parse(&prealloc_mode_lookup, buf,
1248 PRL_PREALLOC_MODE_FALLOCATE,
1249 &local_err);
1250 g_free(buf);
1251 if (local_err != NULL) {
1252 error_propagate(errp, local_err);
1253 goto done;
1254 }
1255 err = 0;
1256
1257 done:
1258 qemu_opts_del(opts);
1259 return err;
1260 }
1261
1262 static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
1263 Error **errp)
1264 {
1265 BDRVParallelsState *s = bs->opaque;
1266 ParallelsHeader ph;
1267 int ret, i;
1268 uint32_t size, header_off;
1269 int64_t file_nb_sectors, sector;
1270 uint32_t data_start;
1271 bool need_check = false;
1272
1273 ret = parallels_opts_prealloc(bs, options, errp);
1274 if (ret < 0) {
1275 return ret;
1276 }
1277
1278 ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
1279 if (ret < 0) {
1280 return ret;
1281 }
1282
1283 GRAPH_RDLOCK_GUARD_MAINLOOP();
1284
1285 file_nb_sectors = bdrv_nb_sectors(bs->file->bs);
1286 if (file_nb_sectors < 0) {
1287 return -EINVAL;
1288 }
1289
1290 ret = bdrv_pread(bs->file, 0, sizeof(ph), &ph, 0);
1291 if (ret < 0) {
1292 return ret;
1293 }
1294
1295 bs->total_sectors = le64_to_cpu(ph.nb_sectors);
1296
1297 if (le32_to_cpu(ph.version) != HEADER_VERSION) {
1298 goto fail_format;
1299 }
1300 if (!memcmp(ph.magic, HEADER_MAGIC, 16)) {
1301 s->off_multiplier = 1;
1302 bs->total_sectors = 0xffffffff & bs->total_sectors;
1303 } else if (!memcmp(ph.magic, HEADER_MAGIC2, 16)) {
1304 s->off_multiplier = le32_to_cpu(ph.tracks);
1305 } else {
1306 goto fail_format;
1307 }
1308
1309 s->tracks = le32_to_cpu(ph.tracks);
1310 if (s->tracks == 0) {
1311 error_setg(errp, "Invalid image: Zero sectors per track");
1312 return -EINVAL;
1313 }
1314 if (s->tracks > INT32_MAX/513) {
1315 error_setg(errp, "Invalid image: Too big cluster");
1316 return -EFBIG;
1317 }
1318 s->prealloc_size = MAX(s->tracks, s->prealloc_size);
1319 s->cluster_size = s->tracks << BDRV_SECTOR_BITS;
1320
1321 s->bat_size = le32_to_cpu(ph.bat_entries);
1322 if (s->bat_size > INT_MAX / sizeof(uint32_t)) {
1323 error_setg(errp, "Catalog too large");
1324 return -EFBIG;
1325 }
1326 if (le64_to_cpu(ph.ext_off) >= (INT64_MAX >> BDRV_SECTOR_BITS)) {
1327 error_setg(errp, "Invalid image: Too big offset");
1328 return -EFBIG;
1329 }
1330
1331 if ((uint64_t)s->bat_size * s->tracks < bs->total_sectors) {
1332 error_setg(errp, "Invalid image: Catalog size too small for "
1333 "advertised disk size");
1334 return -EINVAL;
1335 }
1336
1337 size = bat_entry_off(s->bat_size);
1338 s->header_size = ROUND_UP(size, bdrv_opt_mem_align(bs->file->bs));
1339 s->header = qemu_try_blockalign(bs->file->bs, s->header_size);
1340 if (s->header == NULL) {
1341 return -ENOMEM;
1342 }
1343
1344 /* A single request s->header_size large exceeds BDRV_REQUEST_MAX_BYTES. */
1345 for (header_off = 0; header_off < s->header_size;
1346 header_off += PARALLELS_HEADER_READ_CHUNK) {
1347 uint32_t chunk = MIN(s->header_size - header_off,
1348 PARALLELS_HEADER_READ_CHUNK);
1349
1350 ret = bdrv_pread(bs->file, header_off, chunk,
1351 (uint8_t *)s->header + header_off, 0);
1352 if (ret < 0) {
1353 goto fail;
1354 }
1355 }
1356 s->bat_bitmap = (uint32_t *)(s->header + 1);
1357
1358 if (le32_to_cpu(ph.inuse) == HEADER_INUSE_MAGIC) {
1359 need_check = s->header_unclean = true;
1360 }
1361
1362 {
1363 bool ok = parallels_test_data_off(s, file_nb_sectors, &data_start);
1364 need_check = need_check || !ok;
1365 }
1366
1367 s->data_start = data_start;
1368 s->data_end = s->data_start;
1369 if (s->data_end < (s->header_size >> BDRV_SECTOR_BITS)) {
1370 /*
1371 * There is not enough unused space to fit to block align between BAT
1372 * and actual data. We can't avoid read-modify-write...
1373 */
1374 s->header_size = size;
1375 }
1376
1377 if (ph.ext_off) {
1378 if (flags & BDRV_O_RDWR) {
1379 /*
1380 * It's unsafe to open image RW if there is an extension (as we
1381 * don't support it). But parallels driver in QEMU historically
1382 * ignores the extension, so print warning and don't care.
1383 */
1384 warn_report("Format Extension ignored in RW mode");
1385 } else {
1386 ret = parallels_read_format_extension(
1387 bs, le64_to_cpu(ph.ext_off) << BDRV_SECTOR_BITS, errp);
1388 if (ret < 0) {
1389 goto fail;
1390 }
1391 }
1392 }
1393
1394 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_INACTIVE)) {
1395 s->header->inuse = cpu_to_le32(HEADER_INUSE_MAGIC);
1396 ret = parallels_update_header(bs);
1397 if (ret < 0) {
1398 goto fail;
1399 }
1400 }
1401
1402 s->bat_dirty_block = 4 * qemu_real_host_page_size();
1403 s->bat_dirty_bmap =
1404 bitmap_new(DIV_ROUND_UP(s->header_size, s->bat_dirty_block));
1405
1406 /* Disable migration until bdrv_activate method is added */
1407 error_setg(&s->migration_blocker, "The Parallels format used by node '%s' "
1408 "does not support live migration",
1409 bdrv_get_device_or_node_name(bs));
1410
1411 ret = migrate_add_blocker_normal(&s->migration_blocker, errp);
1412 if (ret < 0) {
1413 goto fail;
1414 }
1415 qemu_co_mutex_init(&s->lock);
1416
1417 for (i = 0; i < s->bat_size; i++) {
1418 sector = bat2sect(s, i);
1419 if (sector == 0) {
1420 continue; /* not allocated */
1421 }
1422 if (sector < data_start || sector + s->tracks > file_nb_sectors) {
1423 /* Cluster is outside of the image file or overlaps the header. */
1424 need_check = true;
1425 continue;
1426 }
1427 if (sector + s->tracks > s->data_end) {
1428 s->data_end = sector + s->tracks;
1429 }
1430 }
1431
1432 if (!need_check) {
1433 ret = parallels_fill_used_bitmap(bs);
1434 if (ret == -ENOMEM) {
1435 goto fail;
1436 }
1437 need_check = need_check || ret < 0; /* These are correctable errors */
1438 }
1439
1440 /*
1441 * We don't repair the image here if it's opened for checks. Also we don't
1442 * want to change inactive images and can't change readonly images.
1443 */
1444 if ((flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) || !(flags & BDRV_O_RDWR)) {
1445 return 0;
1446 }
1447
1448 /* Repair the image if corruption was detected. */
1449 if (need_check) {
1450 BdrvCheckResult res;
1451 ret = bdrv_check(bs, &res, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1452 if (ret < 0) {
1453 error_setg_errno(errp, -ret, "Could not repair corrupted image");
1454 migrate_del_blocker(&s->migration_blocker);
1455 goto fail;
1456 }
1457 }
1458 return 0;
1459
1460 fail_format:
1461 error_setg(errp, "Image not in Parallels format");
1462 return -EINVAL;
1463
1464 fail:
1465 /*
1466 * "s" object was allocated by g_malloc0 so we can safely
1467 * try to free its fields even they were not allocated.
1468 */
1469 parallels_free_used_bitmap(bs);
1470
1471 g_free(s->bat_dirty_bmap);
1472 qemu_vfree(s->header);
1473 return ret;
1474 }
1475
1476
1477 static void parallels_close(BlockDriverState *bs)
1478 {
1479 BDRVParallelsState *s = bs->opaque;
1480
1481 GRAPH_RDLOCK_GUARD_MAINLOOP();
1482
1483 if ((bs->open_flags & BDRV_O_RDWR) && !(bs->open_flags & BDRV_O_INACTIVE)) {
1484 s->header->inuse = 0;
1485 parallels_update_header(bs);
1486
1487 /* errors are ignored, so we might as well pass exact=true */
1488 bdrv_truncate(bs->file, s->data_end << BDRV_SECTOR_BITS, true,
1489 PREALLOC_MODE_OFF, 0, NULL);
1490 }
1491
1492 parallels_free_used_bitmap(bs);
1493
1494 g_free(s->bat_dirty_bmap);
1495 qemu_vfree(s->header);
1496
1497 migrate_del_blocker(&s->migration_blocker);
1498 }
1499
1500 static bool parallels_is_support_dirty_bitmaps(BlockDriverState *bs)
1501 {
1502 return 1;
1503 }
1504
1505 static BlockDriver bdrv_parallels = {
1506 .format_name = "parallels",
1507 .instance_size = sizeof(BDRVParallelsState),
1508 .create_opts = &parallels_create_opts,
1509 .is_format = true,
1510 .supports_backing = true,
1511
1512 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1513 .bdrv_supports_persistent_dirty_bitmap = parallels_is_support_dirty_bitmaps,
1514
1515 .bdrv_probe = parallels_probe,
1516 .bdrv_open = parallels_open,
1517 .bdrv_close = parallels_close,
1518 .bdrv_child_perm = bdrv_default_perms,
1519 .bdrv_co_block_status = parallels_co_block_status,
1520 .bdrv_co_flush_to_os = parallels_co_flush_to_os,
1521 .bdrv_co_readv = parallels_co_readv,
1522 .bdrv_co_writev = parallels_co_writev,
1523 .bdrv_co_create = parallels_co_create,
1524 .bdrv_co_create_opts = parallels_co_create_opts,
1525 .bdrv_co_check = parallels_co_check,
1526 .bdrv_co_pdiscard = parallels_co_pdiscard,
1527 .bdrv_co_pwrite_zeroes = parallels_co_pwrite_zeroes,
1528 };
1529
1530 static void bdrv_parallels_init(void)
1531 {
1532 bdrv_register(&bdrv_parallels);
1533 }
1534
1535 block_init(bdrv_parallels_init);