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