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