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