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