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