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