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