]> git.proxmox.com Git - mirror_qemu.git/blame - block/qed.c
block/dmg: improve zeroes handling
[mirror_qemu.git] / block / qed.c
CommitLineData
75411d23
SH
1/*
2 * QEMU Enhanced Disk Format
3 *
4 * Copyright IBM, Corp. 2010
5 *
6 * Authors:
7 * Stefan Hajnoczi <stefanha@linux.vnet.ibm.com>
8 * Anthony Liguori <aliguori@us.ibm.com>
9 *
10 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
11 * See the COPYING.LIB file in the top-level directory.
12 *
13 */
14
1de7afc9 15#include "qemu/timer.h"
eabba580 16#include "trace.h"
75411d23 17#include "qed.h"
7b1b5d19 18#include "qapi/qmp/qerror.h"
caf71f86 19#include "migration/migration.h"
75411d23 20
d7331bed 21static const AIOCBInfo qed_aiocb_info = {
eabba580 22 .aiocb_size = sizeof(QEDAIOCB),
eabba580
SH
23};
24
75411d23
SH
25static int bdrv_qed_probe(const uint8_t *buf, int buf_size,
26 const char *filename)
27{
28 const QEDHeader *header = (const QEDHeader *)buf;
29
30 if (buf_size < sizeof(*header)) {
31 return 0;
32 }
33 if (le32_to_cpu(header->magic) != QED_MAGIC) {
34 return 0;
35 }
36 return 100;
37}
38
39/**
40 * Check whether an image format is raw
41 *
42 * @fmt: Backing file format, may be NULL
43 */
44static bool qed_fmt_is_raw(const char *fmt)
45{
46 return fmt && strcmp(fmt, "raw") == 0;
47}
48
49static void qed_header_le_to_cpu(const QEDHeader *le, QEDHeader *cpu)
50{
51 cpu->magic = le32_to_cpu(le->magic);
52 cpu->cluster_size = le32_to_cpu(le->cluster_size);
53 cpu->table_size = le32_to_cpu(le->table_size);
54 cpu->header_size = le32_to_cpu(le->header_size);
55 cpu->features = le64_to_cpu(le->features);
56 cpu->compat_features = le64_to_cpu(le->compat_features);
57 cpu->autoclear_features = le64_to_cpu(le->autoclear_features);
58 cpu->l1_table_offset = le64_to_cpu(le->l1_table_offset);
59 cpu->image_size = le64_to_cpu(le->image_size);
60 cpu->backing_filename_offset = le32_to_cpu(le->backing_filename_offset);
61 cpu->backing_filename_size = le32_to_cpu(le->backing_filename_size);
62}
63
64static void qed_header_cpu_to_le(const QEDHeader *cpu, QEDHeader *le)
65{
66 le->magic = cpu_to_le32(cpu->magic);
67 le->cluster_size = cpu_to_le32(cpu->cluster_size);
68 le->table_size = cpu_to_le32(cpu->table_size);
69 le->header_size = cpu_to_le32(cpu->header_size);
70 le->features = cpu_to_le64(cpu->features);
71 le->compat_features = cpu_to_le64(cpu->compat_features);
72 le->autoclear_features = cpu_to_le64(cpu->autoclear_features);
73 le->l1_table_offset = cpu_to_le64(cpu->l1_table_offset);
74 le->image_size = cpu_to_le64(cpu->image_size);
75 le->backing_filename_offset = cpu_to_le32(cpu->backing_filename_offset);
76 le->backing_filename_size = cpu_to_le32(cpu->backing_filename_size);
77}
78
b10170ac 79int qed_write_header_sync(BDRVQEDState *s)
75411d23
SH
80{
81 QEDHeader le;
82 int ret;
83
84 qed_header_cpu_to_le(&s->header, &le);
85 ret = bdrv_pwrite(s->bs->file, 0, &le, sizeof(le));
86 if (ret != sizeof(le)) {
87 return ret;
88 }
89 return 0;
90}
91
01979a98
SH
92typedef struct {
93 GenericCB gencb;
94 BDRVQEDState *s;
95 struct iovec iov;
96 QEMUIOVector qiov;
97 int nsectors;
98 uint8_t *buf;
99} QEDWriteHeaderCB;
100
101static void qed_write_header_cb(void *opaque, int ret)
102{
103 QEDWriteHeaderCB *write_header_cb = opaque;
104
105 qemu_vfree(write_header_cb->buf);
106 gencb_complete(write_header_cb, ret);
107}
108
109static void qed_write_header_read_cb(void *opaque, int ret)
110{
111 QEDWriteHeaderCB *write_header_cb = opaque;
112 BDRVQEDState *s = write_header_cb->s;
01979a98
SH
113
114 if (ret) {
115 qed_write_header_cb(write_header_cb, ret);
116 return;
117 }
118
119 /* Update header */
120 qed_header_cpu_to_le(&s->header, (QEDHeader *)write_header_cb->buf);
121
ad54ae80
PB
122 bdrv_aio_writev(s->bs->file, 0, &write_header_cb->qiov,
123 write_header_cb->nsectors, qed_write_header_cb,
124 write_header_cb);
01979a98
SH
125}
126
127/**
128 * Update header in-place (does not rewrite backing filename or other strings)
129 *
130 * This function only updates known header fields in-place and does not affect
131 * extra data after the QED header.
132 */
097310b5 133static void qed_write_header(BDRVQEDState *s, BlockCompletionFunc cb,
01979a98
SH
134 void *opaque)
135{
136 /* We must write full sectors for O_DIRECT but cannot necessarily generate
137 * the data following the header if an unrecognized compat feature is
138 * active. Therefore, first read the sectors containing the header, update
139 * them, and write back.
140 */
141
01979a98
SH
142 int nsectors = (sizeof(QEDHeader) + BDRV_SECTOR_SIZE - 1) /
143 BDRV_SECTOR_SIZE;
144 size_t len = nsectors * BDRV_SECTOR_SIZE;
145 QEDWriteHeaderCB *write_header_cb = gencb_alloc(sizeof(*write_header_cb),
146 cb, opaque);
147
148 write_header_cb->s = s;
149 write_header_cb->nsectors = nsectors;
150 write_header_cb->buf = qemu_blockalign(s->bs, len);
151 write_header_cb->iov.iov_base = write_header_cb->buf;
152 write_header_cb->iov.iov_len = len;
153 qemu_iovec_init_external(&write_header_cb->qiov, &write_header_cb->iov, 1);
154
ad54ae80
PB
155 bdrv_aio_readv(s->bs->file, 0, &write_header_cb->qiov, nsectors,
156 qed_write_header_read_cb, write_header_cb);
01979a98
SH
157}
158
75411d23
SH
159static uint64_t qed_max_image_size(uint32_t cluster_size, uint32_t table_size)
160{
161 uint64_t table_entries;
162 uint64_t l2_size;
163
164 table_entries = (table_size * cluster_size) / sizeof(uint64_t);
165 l2_size = table_entries * cluster_size;
166
167 return l2_size * table_entries;
168}
169
170static bool qed_is_cluster_size_valid(uint32_t cluster_size)
171{
172 if (cluster_size < QED_MIN_CLUSTER_SIZE ||
173 cluster_size > QED_MAX_CLUSTER_SIZE) {
174 return false;
175 }
176 if (cluster_size & (cluster_size - 1)) {
177 return false; /* not power of 2 */
178 }
179 return true;
180}
181
182static bool qed_is_table_size_valid(uint32_t table_size)
183{
184 if (table_size < QED_MIN_TABLE_SIZE ||
185 table_size > QED_MAX_TABLE_SIZE) {
186 return false;
187 }
188 if (table_size & (table_size - 1)) {
189 return false; /* not power of 2 */
190 }
191 return true;
192}
193
194static bool qed_is_image_size_valid(uint64_t image_size, uint32_t cluster_size,
195 uint32_t table_size)
196{
197 if (image_size % BDRV_SECTOR_SIZE != 0) {
198 return false; /* not multiple of sector size */
199 }
200 if (image_size > qed_max_image_size(cluster_size, table_size)) {
201 return false; /* image is too large */
202 }
203 return true;
204}
205
206/**
207 * Read a string of known length from the image file
208 *
209 * @file: Image file
210 * @offset: File offset to start of string, in bytes
211 * @n: String length in bytes
212 * @buf: Destination buffer
213 * @buflen: Destination buffer length in bytes
214 * @ret: 0 on success, -errno on failure
215 *
216 * The string is NUL-terminated.
217 */
218static int qed_read_string(BlockDriverState *file, uint64_t offset, size_t n,
219 char *buf, size_t buflen)
220{
221 int ret;
222 if (n >= buflen) {
223 return -EINVAL;
224 }
225 ret = bdrv_pread(file, offset, buf, n);
226 if (ret < 0) {
227 return ret;
228 }
229 buf[n] = '\0';
230 return 0;
231}
232
eabba580
SH
233/**
234 * Allocate new clusters
235 *
236 * @s: QED state
237 * @n: Number of contiguous clusters to allocate
238 * @ret: Offset of first allocated cluster
239 *
240 * This function only produces the offset where the new clusters should be
241 * written. It updates BDRVQEDState but does not make any changes to the image
242 * file.
243 */
244static uint64_t qed_alloc_clusters(BDRVQEDState *s, unsigned int n)
245{
246 uint64_t offset = s->file_size;
247 s->file_size += n * s->header.cluster_size;
248 return offset;
249}
250
298800ca
SH
251QEDTable *qed_alloc_table(BDRVQEDState *s)
252{
253 /* Honor O_DIRECT memory alignment requirements */
254 return qemu_blockalign(s->bs,
255 s->header.cluster_size * s->header.table_size);
256}
257
eabba580
SH
258/**
259 * Allocate a new zeroed L2 table
260 */
261static CachedL2Table *qed_new_l2_table(BDRVQEDState *s)
262{
263 CachedL2Table *l2_table = qed_alloc_l2_cache_entry(&s->l2_cache);
264
265 l2_table->table = qed_alloc_table(s);
266 l2_table->offset = qed_alloc_clusters(s, s->header.table_size);
267
268 memset(l2_table->table->offsets, 0,
269 s->header.cluster_size * s->header.table_size);
270 return l2_table;
271}
272
273static void qed_aio_next_io(void *opaque, int ret);
274
6f321e93
SH
275static void qed_plug_allocating_write_reqs(BDRVQEDState *s)
276{
277 assert(!s->allocating_write_reqs_plugged);
278
279 s->allocating_write_reqs_plugged = true;
280}
281
282static void qed_unplug_allocating_write_reqs(BDRVQEDState *s)
283{
284 QEDAIOCB *acb;
285
286 assert(s->allocating_write_reqs_plugged);
287
288 s->allocating_write_reqs_plugged = false;
289
290 acb = QSIMPLEQ_FIRST(&s->allocating_write_reqs);
291 if (acb) {
292 qed_aio_next_io(acb, 0);
293 }
294}
295
296static void qed_finish_clear_need_check(void *opaque, int ret)
297{
298 /* Do nothing */
299}
300
301static void qed_flush_after_clear_need_check(void *opaque, int ret)
302{
303 BDRVQEDState *s = opaque;
304
305 bdrv_aio_flush(s->bs, qed_finish_clear_need_check, s);
306
307 /* No need to wait until flush completes */
308 qed_unplug_allocating_write_reqs(s);
309}
310
311static void qed_clear_need_check(void *opaque, int ret)
312{
313 BDRVQEDState *s = opaque;
314
315 if (ret) {
316 qed_unplug_allocating_write_reqs(s);
317 return;
318 }
319
320 s->header.features &= ~QED_F_NEED_CHECK;
321 qed_write_header(s, qed_flush_after_clear_need_check, s);
322}
323
324static void qed_need_check_timer_cb(void *opaque)
325{
326 BDRVQEDState *s = opaque;
327
328 /* The timer should only fire when allocating writes have drained */
329 assert(!QSIMPLEQ_FIRST(&s->allocating_write_reqs));
330
331 trace_qed_need_check_timer_cb(s);
332
333 qed_plug_allocating_write_reqs(s);
334
335 /* Ensure writes are on disk before clearing flag */
336 bdrv_aio_flush(s->bs, qed_clear_need_check, s);
337}
338
339static void qed_start_need_check_timer(BDRVQEDState *s)
340{
341 trace_qed_start_need_check_timer(s);
342
bc72ad67 343 /* Use QEMU_CLOCK_VIRTUAL so we don't alter the image file while suspended for
6f321e93
SH
344 * migration.
345 */
bc72ad67 346 timer_mod(s->need_check_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
6f321e93
SH
347 get_ticks_per_sec() * QED_NEED_CHECK_TIMEOUT);
348}
349
350/* It's okay to call this multiple times or when no timer is started */
351static void qed_cancel_need_check_timer(BDRVQEDState *s)
352{
353 trace_qed_cancel_need_check_timer(s);
bc72ad67 354 timer_del(s->need_check_timer);
6f321e93
SH
355}
356
e023b2e2
PB
357static void bdrv_qed_rebind(BlockDriverState *bs)
358{
359 BDRVQEDState *s = bs->opaque;
360 s->bs = bs;
361}
362
a8c868c3
SH
363static void bdrv_qed_detach_aio_context(BlockDriverState *bs)
364{
365 BDRVQEDState *s = bs->opaque;
366
367 qed_cancel_need_check_timer(s);
368 timer_free(s->need_check_timer);
369}
370
371static void bdrv_qed_attach_aio_context(BlockDriverState *bs,
372 AioContext *new_context)
373{
374 BDRVQEDState *s = bs->opaque;
375
376 s->need_check_timer = aio_timer_new(new_context,
377 QEMU_CLOCK_VIRTUAL, SCALE_NS,
378 qed_need_check_timer_cb, s);
379 if (s->header.features & QED_F_NEED_CHECK) {
380 qed_start_need_check_timer(s);
381 }
382}
383
015a1036
HR
384static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
385 Error **errp)
75411d23
SH
386{
387 BDRVQEDState *s = bs->opaque;
388 QEDHeader le_header;
389 int64_t file_size;
390 int ret;
391
392 s->bs = bs;
eabba580 393 QSIMPLEQ_INIT(&s->allocating_write_reqs);
75411d23
SH
394
395 ret = bdrv_pread(bs->file, 0, &le_header, sizeof(le_header));
396 if (ret < 0) {
397 return ret;
398 }
75411d23
SH
399 qed_header_le_to_cpu(&le_header, &s->header);
400
401 if (s->header.magic != QED_MAGIC) {
76abe407
PB
402 error_setg(errp, "Image not in QED format");
403 return -EINVAL;
75411d23
SH
404 }
405 if (s->header.features & ~QED_FEATURE_MASK) {
10b758e8
KW
406 /* image uses unsupported feature bits */
407 char buf[64];
408 snprintf(buf, sizeof(buf), "%" PRIx64,
409 s->header.features & ~QED_FEATURE_MASK);
0fea6b79 410 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
bfb197e0 411 bdrv_get_device_name(bs), "QED", buf);
10b758e8 412 return -ENOTSUP;
75411d23
SH
413 }
414 if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
415 return -EINVAL;
416 }
417
418 /* Round down file size to the last cluster */
419 file_size = bdrv_getlength(bs->file);
420 if (file_size < 0) {
421 return file_size;
422 }
423 s->file_size = qed_start_of_cluster(s, file_size);
424
425 if (!qed_is_table_size_valid(s->header.table_size)) {
426 return -EINVAL;
427 }
428 if (!qed_is_image_size_valid(s->header.image_size,
429 s->header.cluster_size,
430 s->header.table_size)) {
431 return -EINVAL;
432 }
433 if (!qed_check_table_offset(s, s->header.l1_table_offset)) {
434 return -EINVAL;
435 }
436
437 s->table_nelems = (s->header.cluster_size * s->header.table_size) /
438 sizeof(uint64_t);
439 s->l2_shift = ffs(s->header.cluster_size) - 1;
440 s->l2_mask = s->table_nelems - 1;
441 s->l1_shift = s->l2_shift + ffs(s->table_nelems) - 1;
442
443 if ((s->header.features & QED_F_BACKING_FILE)) {
444 if ((uint64_t)s->header.backing_filename_offset +
445 s->header.backing_filename_size >
446 s->header.cluster_size * s->header.header_size) {
447 return -EINVAL;
448 }
449
450 ret = qed_read_string(bs->file, s->header.backing_filename_offset,
451 s->header.backing_filename_size, bs->backing_file,
452 sizeof(bs->backing_file));
453 if (ret < 0) {
454 return ret;
455 }
456
457 if (s->header.features & QED_F_BACKING_FORMAT_NO_PROBE) {
458 pstrcpy(bs->backing_format, sizeof(bs->backing_format), "raw");
459 }
460 }
461
462 /* Reset unknown autoclear feature bits. This is a backwards
463 * compatibility mechanism that allows images to be opened by older
464 * programs, which "knock out" unknown feature bits. When an image is
465 * opened by a newer program again it can detect that the autoclear
466 * feature is no longer valid.
467 */
468 if ((s->header.autoclear_features & ~QED_AUTOCLEAR_FEATURE_MASK) != 0 &&
2d1f3c23 469 !bdrv_is_read_only(bs->file) && !(flags & BDRV_O_INCOMING)) {
75411d23
SH
470 s->header.autoclear_features &= QED_AUTOCLEAR_FEATURE_MASK;
471
472 ret = qed_write_header_sync(s);
473 if (ret) {
474 return ret;
475 }
476
477 /* From here on only known autoclear feature bits are valid */
478 bdrv_flush(bs->file);
479 }
480
298800ca
SH
481 s->l1_table = qed_alloc_table(s);
482 qed_init_l2_cache(&s->l2_cache);
483
484 ret = qed_read_l1_table_sync(s);
01979a98
SH
485 if (ret) {
486 goto out;
487 }
488
489 /* If image was not closed cleanly, check consistency */
058f8f16 490 if (!(flags & BDRV_O_CHECK) && (s->header.features & QED_F_NEED_CHECK)) {
01979a98
SH
491 /* Read-only images cannot be fixed. There is no risk of corruption
492 * since write operations are not possible. Therefore, allow
493 * potentially inconsistent images to be opened read-only. This can
494 * aid data recovery from an otherwise inconsistent image.
495 */
2d1f3c23
BC
496 if (!bdrv_is_read_only(bs->file) &&
497 !(flags & BDRV_O_INCOMING)) {
01979a98
SH
498 BdrvCheckResult result = {0};
499
500 ret = qed_check(s, &result, true);
6f321e93
SH
501 if (ret) {
502 goto out;
503 }
01979a98
SH
504 }
505 }
506
a8c868c3 507 bdrv_qed_attach_aio_context(bs, bdrv_get_aio_context(bs));
6f321e93 508
01979a98 509out:
298800ca
SH
510 if (ret) {
511 qed_free_l2_cache(&s->l2_cache);
512 qemu_vfree(s->l1_table);
513 }
75411d23
SH
514 return ret;
515}
516
3baca891 517static void bdrv_qed_refresh_limits(BlockDriverState *bs, Error **errp)
d34682cd
KW
518{
519 BDRVQEDState *s = bs->opaque;
520
521 bs->bl.write_zeroes_alignment = s->header.cluster_size >> BDRV_SECTOR_BITS;
d34682cd
KW
522}
523
f9cb20f1
JC
524/* We have nothing to do for QED reopen, stubs just return
525 * success */
526static int bdrv_qed_reopen_prepare(BDRVReopenState *state,
527 BlockReopenQueue *queue, Error **errp)
528{
529 return 0;
530}
531
75411d23
SH
532static void bdrv_qed_close(BlockDriverState *bs)
533{
298800ca
SH
534 BDRVQEDState *s = bs->opaque;
535
a8c868c3 536 bdrv_qed_detach_aio_context(bs);
6f321e93 537
01979a98
SH
538 /* Ensure writes reach stable storage */
539 bdrv_flush(bs->file);
540
541 /* Clean shutdown, no check required on next open */
542 if (s->header.features & QED_F_NEED_CHECK) {
543 s->header.features &= ~QED_F_NEED_CHECK;
544 qed_write_header_sync(s);
545 }
546
298800ca
SH
547 qed_free_l2_cache(&s->l2_cache);
548 qemu_vfree(s->l1_table);
75411d23
SH
549}
550
75411d23
SH
551static int qed_create(const char *filename, uint32_t cluster_size,
552 uint64_t image_size, uint32_t table_size,
0fea6b79 553 const char *backing_file, const char *backing_fmt,
4ab15590 554 QemuOpts *opts, Error **errp)
75411d23
SH
555{
556 QEDHeader header = {
557 .magic = QED_MAGIC,
558 .cluster_size = cluster_size,
559 .table_size = table_size,
560 .header_size = 1,
561 .features = 0,
562 .compat_features = 0,
563 .l1_table_offset = cluster_size,
564 .image_size = image_size,
565 };
566 QEDHeader le_header;
567 uint8_t *l1_table = NULL;
568 size_t l1_size = header.cluster_size * header.table_size;
34b5d2c6 569 Error *local_err = NULL;
75411d23 570 int ret = 0;
2e40134b 571 BlockDriverState *bs;
75411d23 572
4ab15590 573 ret = bdrv_create_file(filename, opts, &local_err);
75411d23 574 if (ret < 0) {
0fea6b79 575 error_propagate(errp, local_err);
75411d23
SH
576 return ret;
577 }
578
2e40134b
HR
579 bs = NULL;
580 ret = bdrv_open(&bs, filename, NULL, NULL,
581 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_PROTOCOL, NULL,
582 &local_err);
75411d23 583 if (ret < 0) {
0fea6b79 584 error_propagate(errp, local_err);
75411d23
SH
585 return ret;
586 }
587
c743849b
SH
588 /* File must start empty and grow, check truncate is supported */
589 ret = bdrv_truncate(bs, 0);
590 if (ret < 0) {
591 goto out;
592 }
593
75411d23
SH
594 if (backing_file) {
595 header.features |= QED_F_BACKING_FILE;
596 header.backing_filename_offset = sizeof(le_header);
597 header.backing_filename_size = strlen(backing_file);
598
599 if (qed_fmt_is_raw(backing_fmt)) {
600 header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
601 }
602 }
603
604 qed_header_cpu_to_le(&header, &le_header);
605 ret = bdrv_pwrite(bs, 0, &le_header, sizeof(le_header));
606 if (ret < 0) {
607 goto out;
608 }
609 ret = bdrv_pwrite(bs, sizeof(le_header), backing_file,
610 header.backing_filename_size);
611 if (ret < 0) {
612 goto out;
613 }
614
7267c094 615 l1_table = g_malloc0(l1_size);
75411d23
SH
616 ret = bdrv_pwrite(bs, header.l1_table_offset, l1_table, l1_size);
617 if (ret < 0) {
618 goto out;
619 }
620
621 ret = 0; /* success */
622out:
7267c094 623 g_free(l1_table);
4f6fd349 624 bdrv_unref(bs);
75411d23
SH
625 return ret;
626}
627
7ab74849 628static int bdrv_qed_create(const char *filename, QemuOpts *opts, Error **errp)
75411d23
SH
629{
630 uint64_t image_size = 0;
631 uint32_t cluster_size = QED_DEFAULT_CLUSTER_SIZE;
632 uint32_t table_size = QED_DEFAULT_TABLE_SIZE;
7ab74849
CL
633 char *backing_file = NULL;
634 char *backing_fmt = NULL;
635 int ret;
636
c2eb918e
HT
637 image_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
638 BDRV_SECTOR_SIZE);
7ab74849
CL
639 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
640 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
641 cluster_size = qemu_opt_get_size_del(opts,
642 BLOCK_OPT_CLUSTER_SIZE,
643 QED_DEFAULT_CLUSTER_SIZE);
644 table_size = qemu_opt_get_size_del(opts, BLOCK_OPT_TABLE_SIZE,
645 QED_DEFAULT_TABLE_SIZE);
75411d23
SH
646
647 if (!qed_is_cluster_size_valid(cluster_size)) {
5ff679b4
AG
648 error_setg(errp, "QED cluster size must be within range [%u, %u] "
649 "and power of 2",
650 QED_MIN_CLUSTER_SIZE, QED_MAX_CLUSTER_SIZE);
7ab74849
CL
651 ret = -EINVAL;
652 goto finish;
75411d23
SH
653 }
654 if (!qed_is_table_size_valid(table_size)) {
5ff679b4
AG
655 error_setg(errp, "QED table size must be within range [%u, %u] "
656 "and power of 2",
657 QED_MIN_TABLE_SIZE, QED_MAX_TABLE_SIZE);
7ab74849
CL
658 ret = -EINVAL;
659 goto finish;
75411d23
SH
660 }
661 if (!qed_is_image_size_valid(image_size, cluster_size, table_size)) {
5ff679b4
AG
662 error_setg(errp, "QED image size must be a non-zero multiple of "
663 "cluster size and less than %" PRIu64 " bytes",
664 qed_max_image_size(cluster_size, table_size));
7ab74849
CL
665 ret = -EINVAL;
666 goto finish;
75411d23
SH
667 }
668
7ab74849 669 ret = qed_create(filename, cluster_size, image_size, table_size,
4ab15590 670 backing_file, backing_fmt, opts, errp);
7ab74849
CL
671
672finish:
673 g_free(backing_file);
674 g_free(backing_fmt);
675 return ret;
75411d23
SH
676}
677
298800ca 678typedef struct {
4bc74be9 679 BlockDriverState *bs;
b7d5a5b8 680 Coroutine *co;
4bc74be9
PB
681 uint64_t pos;
682 int64_t status;
298800ca
SH
683 int *pnum;
684} QEDIsAllocatedCB;
685
686static void qed_is_allocated_cb(void *opaque, int ret, uint64_t offset, size_t len)
687{
688 QEDIsAllocatedCB *cb = opaque;
4bc74be9 689 BDRVQEDState *s = cb->bs->opaque;
298800ca 690 *cb->pnum = len / BDRV_SECTOR_SIZE;
4bc74be9
PB
691 switch (ret) {
692 case QED_CLUSTER_FOUND:
693 offset |= qed_offset_into_cluster(s, cb->pos);
694 cb->status = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
695 break;
696 case QED_CLUSTER_ZERO:
697 cb->status = BDRV_BLOCK_ZERO;
698 break;
699 case QED_CLUSTER_L2:
700 case QED_CLUSTER_L1:
701 cb->status = 0;
702 break;
703 default:
704 assert(ret < 0);
705 cb->status = ret;
706 break;
707 }
708
b7d5a5b8
SH
709 if (cb->co) {
710 qemu_coroutine_enter(cb->co, NULL);
711 }
298800ca
SH
712}
713
b6b8a333 714static int64_t coroutine_fn bdrv_qed_co_get_block_status(BlockDriverState *bs,
b7d5a5b8
SH
715 int64_t sector_num,
716 int nb_sectors, int *pnum)
75411d23 717{
298800ca 718 BDRVQEDState *s = bs->opaque;
298800ca
SH
719 size_t len = (size_t)nb_sectors * BDRV_SECTOR_SIZE;
720 QEDIsAllocatedCB cb = {
4bc74be9
PB
721 .bs = bs,
722 .pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE,
723 .status = BDRV_BLOCK_OFFSET_MASK,
298800ca
SH
724 .pnum = pnum,
725 };
726 QEDRequest request = { .l2_table = NULL };
727
4bc74be9 728 qed_find_cluster(s, &request, cb.pos, len, qed_is_allocated_cb, &cb);
298800ca 729
b7d5a5b8 730 /* Now sleep if the callback wasn't invoked immediately */
4bc74be9 731 while (cb.status == BDRV_BLOCK_OFFSET_MASK) {
b7d5a5b8
SH
732 cb.co = qemu_coroutine_self();
733 qemu_coroutine_yield();
298800ca
SH
734 }
735
298800ca
SH
736 qed_unref_l2_cache_entry(request.l2_table);
737
4bc74be9 738 return cb.status;
75411d23
SH
739}
740
eabba580
SH
741static BDRVQEDState *acb_to_s(QEDAIOCB *acb)
742{
743 return acb->common.bs->opaque;
744}
745
746/**
747 * Read from the backing file or zero-fill if no backing file
748 *
f06ee3d4
KW
749 * @s: QED state
750 * @pos: Byte position in device
751 * @qiov: Destination I/O vector
752 * @backing_qiov: Possibly shortened copy of qiov, to be allocated here
753 * @cb: Completion function
754 * @opaque: User data for completion function
eabba580
SH
755 *
756 * This function reads qiov->size bytes starting at pos from the backing file.
757 * If there is no backing file then zeroes are read.
758 */
759static void qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
760 QEMUIOVector *qiov,
f06ee3d4 761 QEMUIOVector **backing_qiov,
097310b5 762 BlockCompletionFunc *cb, void *opaque)
eabba580 763{
eabba580
SH
764 uint64_t backing_length = 0;
765 size_t size;
766
767 /* If there is a backing file, get its length. Treat the absence of a
768 * backing file like a zero length backing file.
769 */
770 if (s->bs->backing_hd) {
771 int64_t l = bdrv_getlength(s->bs->backing_hd);
772 if (l < 0) {
773 cb(opaque, l);
774 return;
775 }
776 backing_length = l;
777 }
778
779 /* Zero all sectors if reading beyond the end of the backing file */
780 if (pos >= backing_length ||
781 pos + qiov->size > backing_length) {
3d9b4925 782 qemu_iovec_memset(qiov, 0, 0, qiov->size);
eabba580
SH
783 }
784
785 /* Complete now if there are no backing file sectors to read */
786 if (pos >= backing_length) {
787 cb(opaque, 0);
788 return;
789 }
790
791 /* If the read straddles the end of the backing file, shorten it */
792 size = MIN((uint64_t)backing_length - pos, qiov->size);
793
f06ee3d4
KW
794 assert(*backing_qiov == NULL);
795 *backing_qiov = g_new(QEMUIOVector, 1);
796 qemu_iovec_init(*backing_qiov, qiov->niov);
797 qemu_iovec_concat(*backing_qiov, qiov, 0, size);
798
820100fd 799 BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);
ad54ae80 800 bdrv_aio_readv(s->bs->backing_hd, pos / BDRV_SECTOR_SIZE,
f06ee3d4 801 *backing_qiov, size / BDRV_SECTOR_SIZE, cb, opaque);
eabba580
SH
802}
803
804typedef struct {
805 GenericCB gencb;
806 BDRVQEDState *s;
807 QEMUIOVector qiov;
f06ee3d4 808 QEMUIOVector *backing_qiov;
eabba580
SH
809 struct iovec iov;
810 uint64_t offset;
811} CopyFromBackingFileCB;
812
813static void qed_copy_from_backing_file_cb(void *opaque, int ret)
814{
815 CopyFromBackingFileCB *copy_cb = opaque;
816 qemu_vfree(copy_cb->iov.iov_base);
817 gencb_complete(&copy_cb->gencb, ret);
818}
819
820static void qed_copy_from_backing_file_write(void *opaque, int ret)
821{
822 CopyFromBackingFileCB *copy_cb = opaque;
823 BDRVQEDState *s = copy_cb->s;
eabba580 824
f06ee3d4
KW
825 if (copy_cb->backing_qiov) {
826 qemu_iovec_destroy(copy_cb->backing_qiov);
827 g_free(copy_cb->backing_qiov);
828 copy_cb->backing_qiov = NULL;
829 }
830
eabba580
SH
831 if (ret) {
832 qed_copy_from_backing_file_cb(copy_cb, ret);
833 return;
834 }
835
836 BLKDBG_EVENT(s->bs->file, BLKDBG_COW_WRITE);
ad54ae80
PB
837 bdrv_aio_writev(s->bs->file, copy_cb->offset / BDRV_SECTOR_SIZE,
838 &copy_cb->qiov, copy_cb->qiov.size / BDRV_SECTOR_SIZE,
839 qed_copy_from_backing_file_cb, copy_cb);
eabba580
SH
840}
841
842/**
843 * Copy data from backing file into the image
844 *
845 * @s: QED state
846 * @pos: Byte position in device
847 * @len: Number of bytes
848 * @offset: Byte offset in image file
849 * @cb: Completion function
850 * @opaque: User data for completion function
851 */
852static void qed_copy_from_backing_file(BDRVQEDState *s, uint64_t pos,
853 uint64_t len, uint64_t offset,
097310b5 854 BlockCompletionFunc *cb,
eabba580
SH
855 void *opaque)
856{
857 CopyFromBackingFileCB *copy_cb;
858
859 /* Skip copy entirely if there is no work to do */
860 if (len == 0) {
861 cb(opaque, 0);
862 return;
863 }
864
865 copy_cb = gencb_alloc(sizeof(*copy_cb), cb, opaque);
866 copy_cb->s = s;
867 copy_cb->offset = offset;
f06ee3d4 868 copy_cb->backing_qiov = NULL;
eabba580
SH
869 copy_cb->iov.iov_base = qemu_blockalign(s->bs, len);
870 copy_cb->iov.iov_len = len;
871 qemu_iovec_init_external(&copy_cb->qiov, &copy_cb->iov, 1);
872
f06ee3d4 873 qed_read_backing_file(s, pos, &copy_cb->qiov, &copy_cb->backing_qiov,
eabba580
SH
874 qed_copy_from_backing_file_write, copy_cb);
875}
876
877/**
878 * Link one or more contiguous clusters into a table
879 *
880 * @s: QED state
881 * @table: L2 table
882 * @index: First cluster index
883 * @n: Number of contiguous clusters
21df65b6
AL
884 * @cluster: First cluster offset
885 *
886 * The cluster offset may be an allocated byte offset in the image file, the
887 * zero cluster marker, or the unallocated cluster marker.
eabba580
SH
888 */
889static void qed_update_l2_table(BDRVQEDState *s, QEDTable *table, int index,
890 unsigned int n, uint64_t cluster)
891{
892 int i;
893 for (i = index; i < index + n; i++) {
894 table->offsets[i] = cluster;
21df65b6
AL
895 if (!qed_offset_is_unalloc_cluster(cluster) &&
896 !qed_offset_is_zero_cluster(cluster)) {
897 cluster += s->header.cluster_size;
898 }
eabba580
SH
899 }
900}
901
902static void qed_aio_complete_bh(void *opaque)
903{
904 QEDAIOCB *acb = opaque;
097310b5 905 BlockCompletionFunc *cb = acb->common.cb;
eabba580
SH
906 void *user_opaque = acb->common.opaque;
907 int ret = acb->bh_ret;
eabba580
SH
908
909 qemu_bh_delete(acb->bh);
8007429a 910 qemu_aio_unref(acb);
eabba580
SH
911
912 /* Invoke callback */
913 cb(user_opaque, ret);
eabba580
SH
914}
915
916static void qed_aio_complete(QEDAIOCB *acb, int ret)
917{
918 BDRVQEDState *s = acb_to_s(acb);
919
920 trace_qed_aio_complete(s, acb, ret);
921
922 /* Free resources */
923 qemu_iovec_destroy(&acb->cur_qiov);
924 qed_unref_l2_cache_entry(acb->request.l2_table);
925
0e71be19
SH
926 /* Free the buffer we may have allocated for zero writes */
927 if (acb->flags & QED_AIOCB_ZERO) {
928 qemu_vfree(acb->qiov->iov[0].iov_base);
929 acb->qiov->iov[0].iov_base = NULL;
930 }
931
eabba580
SH
932 /* Arrange for a bh to invoke the completion function */
933 acb->bh_ret = ret;
a8c868c3
SH
934 acb->bh = aio_bh_new(bdrv_get_aio_context(acb->common.bs),
935 qed_aio_complete_bh, acb);
eabba580
SH
936 qemu_bh_schedule(acb->bh);
937
938 /* Start next allocating write request waiting behind this one. Note that
939 * requests enqueue themselves when they first hit an unallocated cluster
940 * but they wait until the entire request is finished before waking up the
941 * next request in the queue. This ensures that we don't cycle through
942 * requests multiple times but rather finish one at a time completely.
943 */
944 if (acb == QSIMPLEQ_FIRST(&s->allocating_write_reqs)) {
945 QSIMPLEQ_REMOVE_HEAD(&s->allocating_write_reqs, next);
946 acb = QSIMPLEQ_FIRST(&s->allocating_write_reqs);
947 if (acb) {
948 qed_aio_next_io(acb, 0);
6f321e93
SH
949 } else if (s->header.features & QED_F_NEED_CHECK) {
950 qed_start_need_check_timer(s);
eabba580
SH
951 }
952 }
953}
954
955/**
956 * Commit the current L2 table to the cache
957 */
958static void qed_commit_l2_update(void *opaque, int ret)
959{
960 QEDAIOCB *acb = opaque;
961 BDRVQEDState *s = acb_to_s(acb);
962 CachedL2Table *l2_table = acb->request.l2_table;
e4fc8781 963 uint64_t l2_offset = l2_table->offset;
eabba580
SH
964
965 qed_commit_l2_cache_entry(&s->l2_cache, l2_table);
966
967 /* This is guaranteed to succeed because we just committed the entry to the
968 * cache.
969 */
e4fc8781 970 acb->request.l2_table = qed_find_l2_cache_entry(&s->l2_cache, l2_offset);
eabba580
SH
971 assert(acb->request.l2_table != NULL);
972
973 qed_aio_next_io(opaque, ret);
974}
975
976/**
977 * Update L1 table with new L2 table offset and write it out
978 */
979static void qed_aio_write_l1_update(void *opaque, int ret)
980{
981 QEDAIOCB *acb = opaque;
982 BDRVQEDState *s = acb_to_s(acb);
983 int index;
984
985 if (ret) {
986 qed_aio_complete(acb, ret);
987 return;
988 }
989
990 index = qed_l1_index(s, acb->cur_pos);
991 s->l1_table->offsets[index] = acb->request.l2_table->offset;
992
993 qed_write_l1_table(s, index, 1, qed_commit_l2_update, acb);
994}
995
996/**
997 * Update L2 table with new cluster offsets and write them out
998 */
0e71be19 999static void qed_aio_write_l2_update(QEDAIOCB *acb, int ret, uint64_t offset)
eabba580 1000{
eabba580
SH
1001 BDRVQEDState *s = acb_to_s(acb);
1002 bool need_alloc = acb->find_cluster_ret == QED_CLUSTER_L1;
1003 int index;
1004
1005 if (ret) {
1006 goto err;
1007 }
1008
1009 if (need_alloc) {
1010 qed_unref_l2_cache_entry(acb->request.l2_table);
1011 acb->request.l2_table = qed_new_l2_table(s);
1012 }
1013
1014 index = qed_l2_index(s, acb->cur_pos);
1015 qed_update_l2_table(s, acb->request.l2_table->table, index, acb->cur_nclusters,
0e71be19 1016 offset);
eabba580
SH
1017
1018 if (need_alloc) {
1019 /* Write out the whole new L2 table */
1020 qed_write_l2_table(s, &acb->request, 0, s->table_nelems, true,
1021 qed_aio_write_l1_update, acb);
1022 } else {
1023 /* Write out only the updated part of the L2 table */
1024 qed_write_l2_table(s, &acb->request, index, acb->cur_nclusters, false,
1025 qed_aio_next_io, acb);
1026 }
1027 return;
1028
1029err:
1030 qed_aio_complete(acb, ret);
1031}
1032
0e71be19
SH
1033static void qed_aio_write_l2_update_cb(void *opaque, int ret)
1034{
1035 QEDAIOCB *acb = opaque;
1036 qed_aio_write_l2_update(acb, ret, acb->cur_cluster);
1037}
1038
eabba580
SH
1039/**
1040 * Flush new data clusters before updating the L2 table
1041 *
1042 * This flush is necessary when a backing file is in use. A crash during an
1043 * allocating write could result in empty clusters in the image. If the write
1044 * only touched a subregion of the cluster, then backing image sectors have
1045 * been lost in the untouched region. The solution is to flush after writing a
1046 * new data cluster and before updating the L2 table.
1047 */
1048static void qed_aio_write_flush_before_l2_update(void *opaque, int ret)
1049{
1050 QEDAIOCB *acb = opaque;
1051 BDRVQEDState *s = acb_to_s(acb);
1052
0e71be19 1053 if (!bdrv_aio_flush(s->bs->file, qed_aio_write_l2_update_cb, opaque)) {
eabba580
SH
1054 qed_aio_complete(acb, -EIO);
1055 }
1056}
1057
1058/**
1059 * Write data to the image file
1060 */
1061static void qed_aio_write_main(void *opaque, int ret)
1062{
1063 QEDAIOCB *acb = opaque;
1064 BDRVQEDState *s = acb_to_s(acb);
1065 uint64_t offset = acb->cur_cluster +
1066 qed_offset_into_cluster(s, acb->cur_pos);
097310b5 1067 BlockCompletionFunc *next_fn;
eabba580
SH
1068
1069 trace_qed_aio_write_main(s, acb, ret, offset, acb->cur_qiov.size);
1070
1071 if (ret) {
1072 qed_aio_complete(acb, ret);
1073 return;
1074 }
1075
1076 if (acb->find_cluster_ret == QED_CLUSTER_FOUND) {
1077 next_fn = qed_aio_next_io;
1078 } else {
1079 if (s->bs->backing_hd) {
1080 next_fn = qed_aio_write_flush_before_l2_update;
1081 } else {
0e71be19 1082 next_fn = qed_aio_write_l2_update_cb;
eabba580
SH
1083 }
1084 }
1085
1086 BLKDBG_EVENT(s->bs->file, BLKDBG_WRITE_AIO);
ad54ae80
PB
1087 bdrv_aio_writev(s->bs->file, offset / BDRV_SECTOR_SIZE,
1088 &acb->cur_qiov, acb->cur_qiov.size / BDRV_SECTOR_SIZE,
1089 next_fn, acb);
eabba580
SH
1090}
1091
1092/**
1093 * Populate back untouched region of new data cluster
1094 */
1095static void qed_aio_write_postfill(void *opaque, int ret)
1096{
1097 QEDAIOCB *acb = opaque;
1098 BDRVQEDState *s = acb_to_s(acb);
1099 uint64_t start = acb->cur_pos + acb->cur_qiov.size;
1100 uint64_t len =
1101 qed_start_of_cluster(s, start + s->header.cluster_size - 1) - start;
1102 uint64_t offset = acb->cur_cluster +
1103 qed_offset_into_cluster(s, acb->cur_pos) +
1104 acb->cur_qiov.size;
1105
1106 if (ret) {
1107 qed_aio_complete(acb, ret);
1108 return;
1109 }
1110
1111 trace_qed_aio_write_postfill(s, acb, start, len, offset);
1112 qed_copy_from_backing_file(s, start, len, offset,
1113 qed_aio_write_main, acb);
1114}
1115
1116/**
1117 * Populate front untouched region of new data cluster
1118 */
1119static void qed_aio_write_prefill(void *opaque, int ret)
1120{
1121 QEDAIOCB *acb = opaque;
1122 BDRVQEDState *s = acb_to_s(acb);
1123 uint64_t start = qed_start_of_cluster(s, acb->cur_pos);
1124 uint64_t len = qed_offset_into_cluster(s, acb->cur_pos);
1125
1126 trace_qed_aio_write_prefill(s, acb, start, len, acb->cur_cluster);
1127 qed_copy_from_backing_file(s, start, len, acb->cur_cluster,
1128 qed_aio_write_postfill, acb);
1129}
1130
0d09c797
SH
1131/**
1132 * Check if the QED_F_NEED_CHECK bit should be set during allocating write
1133 */
1134static bool qed_should_set_need_check(BDRVQEDState *s)
1135{
1136 /* The flush before L2 update path ensures consistency */
1137 if (s->bs->backing_hd) {
1138 return false;
1139 }
1140
1141 return !(s->header.features & QED_F_NEED_CHECK);
1142}
1143
0e71be19
SH
1144static void qed_aio_write_zero_cluster(void *opaque, int ret)
1145{
1146 QEDAIOCB *acb = opaque;
1147
1148 if (ret) {
1149 qed_aio_complete(acb, ret);
1150 return;
1151 }
1152
1153 qed_aio_write_l2_update(acb, 0, 1);
1154}
1155
eabba580
SH
1156/**
1157 * Write new data cluster
1158 *
1159 * @acb: Write request
1160 * @len: Length in bytes
1161 *
1162 * This path is taken when writing to previously unallocated clusters.
1163 */
1164static void qed_aio_write_alloc(QEDAIOCB *acb, size_t len)
1165{
1166 BDRVQEDState *s = acb_to_s(acb);
097310b5 1167 BlockCompletionFunc *cb;
eabba580 1168
6f321e93
SH
1169 /* Cancel timer when the first allocating request comes in */
1170 if (QSIMPLEQ_EMPTY(&s->allocating_write_reqs)) {
1171 qed_cancel_need_check_timer(s);
1172 }
1173
eabba580
SH
1174 /* Freeze this request if another allocating write is in progress */
1175 if (acb != QSIMPLEQ_FIRST(&s->allocating_write_reqs)) {
1176 QSIMPLEQ_INSERT_TAIL(&s->allocating_write_reqs, acb, next);
1177 }
6f321e93
SH
1178 if (acb != QSIMPLEQ_FIRST(&s->allocating_write_reqs) ||
1179 s->allocating_write_reqs_plugged) {
eabba580
SH
1180 return; /* wait for existing request to finish */
1181 }
1182
1183 acb->cur_nclusters = qed_bytes_to_clusters(s,
1184 qed_offset_into_cluster(s, acb->cur_pos) + len);
1b093c48 1185 qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
eabba580 1186
0e71be19
SH
1187 if (acb->flags & QED_AIOCB_ZERO) {
1188 /* Skip ahead if the clusters are already zero */
1189 if (acb->find_cluster_ret == QED_CLUSTER_ZERO) {
1190 qed_aio_next_io(acb, 0);
1191 return;
1192 }
1193
1194 cb = qed_aio_write_zero_cluster;
1195 } else {
1196 cb = qed_aio_write_prefill;
1197 acb->cur_cluster = qed_alloc_clusters(s, acb->cur_nclusters);
1198 }
1199
0d09c797
SH
1200 if (qed_should_set_need_check(s)) {
1201 s->header.features |= QED_F_NEED_CHECK;
0e71be19 1202 qed_write_header(s, cb, acb);
0d09c797 1203 } else {
0e71be19 1204 cb(acb, 0);
01979a98 1205 }
eabba580
SH
1206}
1207
1208/**
1209 * Write data cluster in place
1210 *
1211 * @acb: Write request
1212 * @offset: Cluster offset in bytes
1213 * @len: Length in bytes
1214 *
1215 * This path is taken when writing to already allocated clusters.
1216 */
1217static void qed_aio_write_inplace(QEDAIOCB *acb, uint64_t offset, size_t len)
1218{
0e71be19
SH
1219 /* Allocate buffer for zero writes */
1220 if (acb->flags & QED_AIOCB_ZERO) {
1221 struct iovec *iov = acb->qiov->iov;
1222
1223 if (!iov->iov_base) {
4f4896db
KW
1224 iov->iov_base = qemu_try_blockalign(acb->common.bs, iov->iov_len);
1225 if (iov->iov_base == NULL) {
1226 qed_aio_complete(acb, -ENOMEM);
1227 return;
1228 }
0e71be19
SH
1229 memset(iov->iov_base, 0, iov->iov_len);
1230 }
1231 }
1232
eabba580
SH
1233 /* Calculate the I/O vector */
1234 acb->cur_cluster = offset;
1b093c48 1235 qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
eabba580
SH
1236
1237 /* Do the actual write */
1238 qed_aio_write_main(acb, 0);
1239}
1240
1241/**
1242 * Write data cluster
1243 *
1244 * @opaque: Write request
1245 * @ret: QED_CLUSTER_FOUND, QED_CLUSTER_L2, QED_CLUSTER_L1,
1246 * or -errno
1247 * @offset: Cluster offset in bytes
1248 * @len: Length in bytes
1249 *
1250 * Callback from qed_find_cluster().
1251 */
1252static void qed_aio_write_data(void *opaque, int ret,
1253 uint64_t offset, size_t len)
1254{
1255 QEDAIOCB *acb = opaque;
1256
1257 trace_qed_aio_write_data(acb_to_s(acb), acb, ret, offset, len);
1258
1259 acb->find_cluster_ret = ret;
1260
1261 switch (ret) {
1262 case QED_CLUSTER_FOUND:
1263 qed_aio_write_inplace(acb, offset, len);
1264 break;
1265
1266 case QED_CLUSTER_L2:
1267 case QED_CLUSTER_L1:
21df65b6 1268 case QED_CLUSTER_ZERO:
eabba580
SH
1269 qed_aio_write_alloc(acb, len);
1270 break;
1271
1272 default:
1273 qed_aio_complete(acb, ret);
1274 break;
1275 }
1276}
1277
1278/**
1279 * Read data cluster
1280 *
1281 * @opaque: Read request
1282 * @ret: QED_CLUSTER_FOUND, QED_CLUSTER_L2, QED_CLUSTER_L1,
1283 * or -errno
1284 * @offset: Cluster offset in bytes
1285 * @len: Length in bytes
1286 *
1287 * Callback from qed_find_cluster().
1288 */
1289static void qed_aio_read_data(void *opaque, int ret,
1290 uint64_t offset, size_t len)
1291{
1292 QEDAIOCB *acb = opaque;
1293 BDRVQEDState *s = acb_to_s(acb);
1294 BlockDriverState *bs = acb->common.bs;
eabba580
SH
1295
1296 /* Adjust offset into cluster */
1297 offset += qed_offset_into_cluster(s, acb->cur_pos);
1298
1299 trace_qed_aio_read_data(s, acb, ret, offset, len);
1300
1301 if (ret < 0) {
1302 goto err;
1303 }
1304
1b093c48 1305 qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
eabba580 1306
21df65b6
AL
1307 /* Handle zero cluster and backing file reads */
1308 if (ret == QED_CLUSTER_ZERO) {
3d9b4925 1309 qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
21df65b6
AL
1310 qed_aio_next_io(acb, 0);
1311 return;
1312 } else if (ret != QED_CLUSTER_FOUND) {
eabba580 1313 qed_read_backing_file(s, acb->cur_pos, &acb->cur_qiov,
f06ee3d4 1314 &acb->backing_qiov, qed_aio_next_io, acb);
eabba580
SH
1315 return;
1316 }
1317
1318 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
ad54ae80
PB
1319 bdrv_aio_readv(bs->file, offset / BDRV_SECTOR_SIZE,
1320 &acb->cur_qiov, acb->cur_qiov.size / BDRV_SECTOR_SIZE,
1321 qed_aio_next_io, acb);
eabba580
SH
1322 return;
1323
1324err:
1325 qed_aio_complete(acb, ret);
1326}
1327
1328/**
1329 * Begin next I/O or complete the request
1330 */
1331static void qed_aio_next_io(void *opaque, int ret)
1332{
1333 QEDAIOCB *acb = opaque;
1334 BDRVQEDState *s = acb_to_s(acb);
6e4f59bd
SH
1335 QEDFindClusterFunc *io_fn = (acb->flags & QED_AIOCB_WRITE) ?
1336 qed_aio_write_data : qed_aio_read_data;
eabba580
SH
1337
1338 trace_qed_aio_next_io(s, acb, ret, acb->cur_pos + acb->cur_qiov.size);
1339
f06ee3d4
KW
1340 if (acb->backing_qiov) {
1341 qemu_iovec_destroy(acb->backing_qiov);
1342 g_free(acb->backing_qiov);
1343 acb->backing_qiov = NULL;
1344 }
1345
eabba580
SH
1346 /* Handle I/O error */
1347 if (ret) {
1348 qed_aio_complete(acb, ret);
1349 return;
1350 }
1351
1352 acb->qiov_offset += acb->cur_qiov.size;
1353 acb->cur_pos += acb->cur_qiov.size;
1354 qemu_iovec_reset(&acb->cur_qiov);
1355
1356 /* Complete request */
1357 if (acb->cur_pos >= acb->end_pos) {
1358 qed_aio_complete(acb, 0);
1359 return;
1360 }
1361
1362 /* Find next cluster and start I/O */
1363 qed_find_cluster(s, &acb->request,
1364 acb->cur_pos, acb->end_pos - acb->cur_pos,
1365 io_fn, acb);
1366}
1367
7c84b1b8
MA
1368static BlockAIOCB *qed_aio_setup(BlockDriverState *bs,
1369 int64_t sector_num,
1370 QEMUIOVector *qiov, int nb_sectors,
097310b5 1371 BlockCompletionFunc *cb,
7c84b1b8 1372 void *opaque, int flags)
eabba580 1373{
d7331bed 1374 QEDAIOCB *acb = qemu_aio_get(&qed_aiocb_info, bs, cb, opaque);
eabba580
SH
1375
1376 trace_qed_aio_setup(bs->opaque, acb, sector_num, nb_sectors,
6e4f59bd 1377 opaque, flags);
eabba580 1378
6e4f59bd 1379 acb->flags = flags;
eabba580
SH
1380 acb->qiov = qiov;
1381 acb->qiov_offset = 0;
1382 acb->cur_pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE;
1383 acb->end_pos = acb->cur_pos + nb_sectors * BDRV_SECTOR_SIZE;
f06ee3d4 1384 acb->backing_qiov = NULL;
eabba580
SH
1385 acb->request.l2_table = NULL;
1386 qemu_iovec_init(&acb->cur_qiov, qiov->niov);
1387
1388 /* Start request */
1389 qed_aio_next_io(acb, 0);
1390 return &acb->common;
1391}
1392
7c84b1b8
MA
1393static BlockAIOCB *bdrv_qed_aio_readv(BlockDriverState *bs,
1394 int64_t sector_num,
1395 QEMUIOVector *qiov, int nb_sectors,
097310b5 1396 BlockCompletionFunc *cb,
7c84b1b8 1397 void *opaque)
75411d23 1398{
6e4f59bd 1399 return qed_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
75411d23
SH
1400}
1401
7c84b1b8
MA
1402static BlockAIOCB *bdrv_qed_aio_writev(BlockDriverState *bs,
1403 int64_t sector_num,
1404 QEMUIOVector *qiov, int nb_sectors,
097310b5 1405 BlockCompletionFunc *cb,
7c84b1b8 1406 void *opaque)
75411d23 1407{
6e4f59bd
SH
1408 return qed_aio_setup(bs, sector_num, qiov, nb_sectors, cb,
1409 opaque, QED_AIOCB_WRITE);
75411d23
SH
1410}
1411
0e71be19
SH
1412typedef struct {
1413 Coroutine *co;
1414 int ret;
1415 bool done;
1416} QEDWriteZeroesCB;
1417
1418static void coroutine_fn qed_co_write_zeroes_cb(void *opaque, int ret)
1419{
1420 QEDWriteZeroesCB *cb = opaque;
1421
1422 cb->done = true;
1423 cb->ret = ret;
1424 if (cb->co) {
1425 qemu_coroutine_enter(cb->co, NULL);
1426 }
1427}
1428
1429static int coroutine_fn bdrv_qed_co_write_zeroes(BlockDriverState *bs,
1430 int64_t sector_num,
aa7bfbff
PL
1431 int nb_sectors,
1432 BdrvRequestFlags flags)
0e71be19 1433{
7c84b1b8 1434 BlockAIOCB *blockacb;
ef72f76e 1435 BDRVQEDState *s = bs->opaque;
0e71be19
SH
1436 QEDWriteZeroesCB cb = { .done = false };
1437 QEMUIOVector qiov;
1438 struct iovec iov;
1439
ef72f76e
SH
1440 /* Refuse if there are untouched backing file sectors */
1441 if (bs->backing_hd) {
1442 if (qed_offset_into_cluster(s, sector_num * BDRV_SECTOR_SIZE) != 0) {
1443 return -ENOTSUP;
1444 }
1445 if (qed_offset_into_cluster(s, nb_sectors * BDRV_SECTOR_SIZE) != 0) {
1446 return -ENOTSUP;
1447 }
1448 }
1449
0e71be19
SH
1450 /* Zero writes start without an I/O buffer. If a buffer becomes necessary
1451 * then it will be allocated during request processing.
1452 */
1453 iov.iov_base = NULL,
1454 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1455
1456 qemu_iovec_init_external(&qiov, &iov, 1);
1457 blockacb = qed_aio_setup(bs, sector_num, &qiov, nb_sectors,
1458 qed_co_write_zeroes_cb, &cb,
1459 QED_AIOCB_WRITE | QED_AIOCB_ZERO);
1460 if (!blockacb) {
1461 return -EIO;
1462 }
1463 if (!cb.done) {
1464 cb.co = qemu_coroutine_self();
1465 qemu_coroutine_yield();
1466 }
1467 assert(cb.done);
1468 return cb.ret;
1469}
1470
75411d23
SH
1471static int bdrv_qed_truncate(BlockDriverState *bs, int64_t offset)
1472{
77a5a000
SH
1473 BDRVQEDState *s = bs->opaque;
1474 uint64_t old_image_size;
1475 int ret;
1476
1477 if (!qed_is_image_size_valid(offset, s->header.cluster_size,
1478 s->header.table_size)) {
1479 return -EINVAL;
1480 }
1481
1482 /* Shrinking is currently not supported */
1483 if ((uint64_t)offset < s->header.image_size) {
1484 return -ENOTSUP;
1485 }
1486
1487 old_image_size = s->header.image_size;
1488 s->header.image_size = offset;
1489 ret = qed_write_header_sync(s);
1490 if (ret < 0) {
1491 s->header.image_size = old_image_size;
1492 }
1493 return ret;
75411d23
SH
1494}
1495
1496static int64_t bdrv_qed_getlength(BlockDriverState *bs)
1497{
1498 BDRVQEDState *s = bs->opaque;
1499 return s->header.image_size;
1500}
1501
1502static int bdrv_qed_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1503{
1504 BDRVQEDState *s = bs->opaque;
1505
1506 memset(bdi, 0, sizeof(*bdi));
1507 bdi->cluster_size = s->header.cluster_size;
d68dbee8 1508 bdi->is_dirty = s->header.features & QED_F_NEED_CHECK;
95de6d70
PB
1509 bdi->unallocated_blocks_are_zero = true;
1510 bdi->can_write_zeroes_with_unmap = true;
75411d23
SH
1511 return 0;
1512}
1513
1514static int bdrv_qed_change_backing_file(BlockDriverState *bs,
1515 const char *backing_file,
1516 const char *backing_fmt)
1517{
1518 BDRVQEDState *s = bs->opaque;
1519 QEDHeader new_header, le_header;
1520 void *buffer;
1521 size_t buffer_len, backing_file_len;
1522 int ret;
1523
1524 /* Refuse to set backing filename if unknown compat feature bits are
1525 * active. If the image uses an unknown compat feature then we may not
1526 * know the layout of data following the header structure and cannot safely
1527 * add a new string.
1528 */
1529 if (backing_file && (s->header.compat_features &
1530 ~QED_COMPAT_FEATURE_MASK)) {
1531 return -ENOTSUP;
1532 }
1533
1534 memcpy(&new_header, &s->header, sizeof(new_header));
1535
1536 new_header.features &= ~(QED_F_BACKING_FILE |
1537 QED_F_BACKING_FORMAT_NO_PROBE);
1538
1539 /* Adjust feature flags */
1540 if (backing_file) {
1541 new_header.features |= QED_F_BACKING_FILE;
1542
1543 if (qed_fmt_is_raw(backing_fmt)) {
1544 new_header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
1545 }
1546 }
1547
1548 /* Calculate new header size */
1549 backing_file_len = 0;
1550
1551 if (backing_file) {
1552 backing_file_len = strlen(backing_file);
1553 }
1554
1555 buffer_len = sizeof(new_header);
1556 new_header.backing_filename_offset = buffer_len;
1557 new_header.backing_filename_size = backing_file_len;
1558 buffer_len += backing_file_len;
1559
1560 /* Make sure we can rewrite header without failing */
1561 if (buffer_len > new_header.header_size * new_header.cluster_size) {
1562 return -ENOSPC;
1563 }
1564
1565 /* Prepare new header */
7267c094 1566 buffer = g_malloc(buffer_len);
75411d23
SH
1567
1568 qed_header_cpu_to_le(&new_header, &le_header);
1569 memcpy(buffer, &le_header, sizeof(le_header));
1570 buffer_len = sizeof(le_header);
1571
feba23b1
PB
1572 if (backing_file) {
1573 memcpy(buffer + buffer_len, backing_file, backing_file_len);
1574 buffer_len += backing_file_len;
1575 }
75411d23
SH
1576
1577 /* Write new header */
1578 ret = bdrv_pwrite_sync(bs->file, 0, buffer, buffer_len);
7267c094 1579 g_free(buffer);
75411d23
SH
1580 if (ret == 0) {
1581 memcpy(&s->header, &new_header, sizeof(new_header));
1582 }
1583 return ret;
1584}
1585
5a8a30db 1586static void bdrv_qed_invalidate_cache(BlockDriverState *bs, Error **errp)
c82954e5
BC
1587{
1588 BDRVQEDState *s = bs->opaque;
5a8a30db
KW
1589 Error *local_err = NULL;
1590 int ret;
c82954e5
BC
1591
1592 bdrv_qed_close(bs);
3456a8d1 1593
5a8a30db
KW
1594 bdrv_invalidate_cache(bs->file, &local_err);
1595 if (local_err) {
1596 error_propagate(errp, local_err);
1597 return;
1598 }
3456a8d1 1599
c82954e5 1600 memset(s, 0, sizeof(BDRVQEDState));
5a8a30db
KW
1601 ret = bdrv_qed_open(bs, NULL, bs->open_flags, &local_err);
1602 if (local_err) {
1603 error_setg(errp, "Could not reopen qed layer: %s",
1604 error_get_pretty(local_err));
1605 error_free(local_err);
1606 return;
1607 } else if (ret < 0) {
1608 error_setg_errno(errp, -ret, "Could not reopen qed layer");
1609 return;
1610 }
c82954e5
BC
1611}
1612
4534ff54
KW
1613static int bdrv_qed_check(BlockDriverState *bs, BdrvCheckResult *result,
1614 BdrvCheckMode fix)
75411d23 1615{
01979a98
SH
1616 BDRVQEDState *s = bs->opaque;
1617
4534ff54 1618 return qed_check(s, result, !!fix);
75411d23
SH
1619}
1620
7ab74849
CL
1621static QemuOptsList qed_create_opts = {
1622 .name = "qed-create-opts",
1623 .head = QTAILQ_HEAD_INITIALIZER(qed_create_opts.head),
1624 .desc = {
1625 {
1626 .name = BLOCK_OPT_SIZE,
1627 .type = QEMU_OPT_SIZE,
1628 .help = "Virtual disk size"
1629 },
1630 {
1631 .name = BLOCK_OPT_BACKING_FILE,
1632 .type = QEMU_OPT_STRING,
1633 .help = "File name of a base image"
1634 },
1635 {
1636 .name = BLOCK_OPT_BACKING_FMT,
1637 .type = QEMU_OPT_STRING,
1638 .help = "Image format of the base image"
1639 },
1640 {
1641 .name = BLOCK_OPT_CLUSTER_SIZE,
1642 .type = QEMU_OPT_SIZE,
1643 .help = "Cluster size (in bytes)",
1644 .def_value_str = stringify(QED_DEFAULT_CLUSTER_SIZE)
1645 },
1646 {
1647 .name = BLOCK_OPT_TABLE_SIZE,
1648 .type = QEMU_OPT_SIZE,
1649 .help = "L1/L2 table size (in clusters)"
1650 },
1651 { /* end of list */ }
1652 }
75411d23
SH
1653};
1654
1655static BlockDriver bdrv_qed = {
1656 .format_name = "qed",
1657 .instance_size = sizeof(BDRVQEDState),
7ab74849 1658 .create_opts = &qed_create_opts,
8ee79e70 1659 .supports_backing = true,
75411d23
SH
1660
1661 .bdrv_probe = bdrv_qed_probe,
e023b2e2 1662 .bdrv_rebind = bdrv_qed_rebind,
75411d23
SH
1663 .bdrv_open = bdrv_qed_open,
1664 .bdrv_close = bdrv_qed_close,
f9cb20f1 1665 .bdrv_reopen_prepare = bdrv_qed_reopen_prepare,
c282e1fd 1666 .bdrv_create = bdrv_qed_create,
3ac21627 1667 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 1668 .bdrv_co_get_block_status = bdrv_qed_co_get_block_status,
75411d23
SH
1669 .bdrv_aio_readv = bdrv_qed_aio_readv,
1670 .bdrv_aio_writev = bdrv_qed_aio_writev,
0e71be19 1671 .bdrv_co_write_zeroes = bdrv_qed_co_write_zeroes,
75411d23
SH
1672 .bdrv_truncate = bdrv_qed_truncate,
1673 .bdrv_getlength = bdrv_qed_getlength,
1674 .bdrv_get_info = bdrv_qed_get_info,
d34682cd 1675 .bdrv_refresh_limits = bdrv_qed_refresh_limits,
75411d23 1676 .bdrv_change_backing_file = bdrv_qed_change_backing_file,
c82954e5 1677 .bdrv_invalidate_cache = bdrv_qed_invalidate_cache,
75411d23 1678 .bdrv_check = bdrv_qed_check,
a8c868c3
SH
1679 .bdrv_detach_aio_context = bdrv_qed_detach_aio_context,
1680 .bdrv_attach_aio_context = bdrv_qed_attach_aio_context,
75411d23
SH
1681};
1682
1683static void bdrv_qed_init(void)
1684{
1685 bdrv_register(&bdrv_qed);
1686}
1687
1688block_init(bdrv_qed_init);