]> git.proxmox.com Git - mirror_qemu.git/blame - block/nvme.c
block/nvme: Change size and alignment of prp_list_pages
[mirror_qemu.git] / block / nvme.c
CommitLineData
bdd6a90a
FZ
1/*
2 * NVMe block driver based on vfio
3 *
4 * Copyright 2016 - 2018 Red Hat, Inc.
5 *
6 * Authors:
7 * Fam Zheng <famz@redhat.com>
8 * Paolo Bonzini <pbonzini@redhat.com>
9 *
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
12 */
13
14#include "qemu/osdep.h"
15#include <linux/vfio.h>
16#include "qapi/error.h"
17#include "qapi/qmp/qdict.h"
18#include "qapi/qmp/qstring.h"
19#include "qemu/error-report.h"
db725815 20#include "qemu/main-loop.h"
0b8fa32f 21#include "qemu/module.h"
bdd6a90a 22#include "qemu/cutils.h"
922a01a0 23#include "qemu/option.h"
bdd6a90a
FZ
24#include "qemu/vfio-helpers.h"
25#include "block/block_int.h"
e4ec5ad4 26#include "sysemu/replay.h"
bdd6a90a
FZ
27#include "trace.h"
28
a3d9a352 29#include "block/nvme.h"
bdd6a90a
FZ
30
31#define NVME_SQ_ENTRY_BYTES 64
32#define NVME_CQ_ENTRY_BYTES 16
33#define NVME_QUEUE_SIZE 128
f6845323 34#define NVME_DOORBELL_SIZE 4096
bdd6a90a 35
1086e95d
SH
36/*
37 * We have to leave one slot empty as that is the full queue case where
38 * head == tail + 1.
39 */
40#define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
41
b75fd5f5
SH
42typedef struct BDRVNVMeState BDRVNVMeState;
43
3214b0f0
PMD
44/* Same index is used for queues and IRQs */
45#define INDEX_ADMIN 0
46#define INDEX_IO(n) (1 + n)
47
48/* This driver shares a single MSIX IRQ for the admin and I/O queues */
49enum {
50 MSIX_SHARED_IRQ_IDX = 0,
51 MSIX_IRQ_COUNT = 1
52};
53
bdd6a90a
FZ
54typedef struct {
55 int32_t head, tail;
56 uint8_t *queue;
57 uint64_t iova;
58 /* Hardware MMIO register */
59 volatile uint32_t *doorbell;
60} NVMeQueue;
61
62typedef struct {
63 BlockCompletionFunc *cb;
64 void *opaque;
65 int cid;
66 void *prp_list_page;
67 uint64_t prp_list_iova;
1086e95d 68 int free_req_next; /* q->reqs[] index of next free req */
bdd6a90a
FZ
69} NVMeRequest;
70
71typedef struct {
bdd6a90a
FZ
72 QemuMutex lock;
73
b75fd5f5
SH
74 /* Read from I/O code path, initialized under BQL */
75 BDRVNVMeState *s;
76 int index;
77
bdd6a90a 78 /* Fields protected by BQL */
bdd6a90a
FZ
79 uint8_t *prp_list_pages;
80
81 /* Fields protected by @lock */
a5db74f3 82 CoQueue free_req_queue;
bdd6a90a
FZ
83 NVMeQueue sq, cq;
84 int cq_phase;
1086e95d
SH
85 int free_req_head;
86 NVMeRequest reqs[NVME_NUM_REQS];
bdd6a90a
FZ
87 int need_kick;
88 int inflight;
7838c67f
SH
89
90 /* Thread-safe, no lock necessary */
91 QEMUBH *completion_bh;
bdd6a90a
FZ
92} NVMeQueuePair;
93
b75fd5f5 94struct BDRVNVMeState {
bdd6a90a
FZ
95 AioContext *aio_context;
96 QEMUVFIOState *vfio;
f6845323
PMD
97 /* Memory mapped registers */
98 volatile struct {
99 uint32_t sq_tail;
100 uint32_t cq_head;
101 } *doorbells;
bdd6a90a
FZ
102 /* The submission/completion queue pairs.
103 * [0]: admin queue.
104 * [1..]: io queues.
105 */
106 NVMeQueuePair **queues;
1b539bd6 107 unsigned queue_count;
bdd6a90a
FZ
108 size_t page_size;
109 /* How many uint32_t elements does each doorbell entry take. */
110 size_t doorbell_scale;
111 bool write_cache_supported;
b111b3fc 112 EventNotifier irq_notifier[MSIX_IRQ_COUNT];
118d1b6a 113
bdd6a90a
FZ
114 uint64_t nsze; /* Namespace size reported by identify command */
115 int nsid; /* The namespace id to read/write data. */
1120407b 116 int blkshift;
118d1b6a 117
bdd6a90a 118 uint64_t max_transfer;
2f0d8947 119 bool plugged;
bdd6a90a 120
e0dd95e3 121 bool supports_write_zeroes;
e87a09d6 122 bool supports_discard;
e0dd95e3 123
bdd6a90a
FZ
124 CoMutex dma_map_lock;
125 CoQueue dma_flush_queue;
126
127 /* Total size of mapped qiov, accessed under dma_map_lock */
128 int dma_map_count;
cc61b074
HR
129
130 /* PCI address (required for nvme_refresh_filename()) */
131 char *device;
f25e7ab2
PMD
132
133 struct {
134 uint64_t completion_errors;
135 uint64_t aligned_accesses;
136 uint64_t unaligned_accesses;
137 } stats;
b75fd5f5 138};
bdd6a90a
FZ
139
140#define NVME_BLOCK_OPT_DEVICE "device"
141#define NVME_BLOCK_OPT_NAMESPACE "namespace"
142
7838c67f
SH
143static void nvme_process_completion_bh(void *opaque);
144
bdd6a90a
FZ
145static QemuOptsList runtime_opts = {
146 .name = "nvme",
147 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
148 .desc = {
149 {
150 .name = NVME_BLOCK_OPT_DEVICE,
151 .type = QEMU_OPT_STRING,
152 .help = "NVMe PCI device address",
153 },
154 {
155 .name = NVME_BLOCK_OPT_NAMESPACE,
156 .type = QEMU_OPT_NUMBER,
157 .help = "NVMe namespace",
158 },
159 { /* end of list */ }
160 },
161};
162
dfa9c6c6
PMD
163/* Returns true on success, false on failure. */
164static bool nvme_init_queue(BDRVNVMeState *s, NVMeQueue *q,
1b539bd6 165 unsigned nentries, size_t entry_bytes, Error **errp)
bdd6a90a 166{
bdd6a90a
FZ
167 size_t bytes;
168 int r;
169
2387aace 170 bytes = ROUND_UP(nentries * entry_bytes, qemu_real_host_page_size);
bdd6a90a 171 q->head = q->tail = 0;
2387aace 172 q->queue = qemu_try_memalign(qemu_real_host_page_size, bytes);
bdd6a90a
FZ
173 if (!q->queue) {
174 error_setg(errp, "Cannot allocate queue");
dfa9c6c6 175 return false;
bdd6a90a 176 }
2ed84693 177 memset(q->queue, 0, bytes);
bdd6a90a
FZ
178 r = qemu_vfio_dma_map(s->vfio, q->queue, bytes, false, &q->iova);
179 if (r) {
180 error_setg(errp, "Cannot map queue");
dfa9c6c6 181 return false;
bdd6a90a 182 }
dfa9c6c6 183 return true;
bdd6a90a
FZ
184}
185
b75fd5f5 186static void nvme_free_queue_pair(NVMeQueuePair *q)
bdd6a90a 187{
6e1e9ff2 188 trace_nvme_free_queue_pair(q->index, q);
7838c67f
SH
189 if (q->completion_bh) {
190 qemu_bh_delete(q->completion_bh);
191 }
bdd6a90a
FZ
192 qemu_vfree(q->prp_list_pages);
193 qemu_vfree(q->sq.queue);
194 qemu_vfree(q->cq.queue);
195 qemu_mutex_destroy(&q->lock);
196 g_free(q);
197}
198
199static void nvme_free_req_queue_cb(void *opaque)
200{
201 NVMeQueuePair *q = opaque;
202
203 qemu_mutex_lock(&q->lock);
204 while (qemu_co_enter_next(&q->free_req_queue, &q->lock)) {
205 /* Retry all pending requests */
206 }
207 qemu_mutex_unlock(&q->lock);
208}
209
0a28b02e
PMD
210static NVMeQueuePair *nvme_create_queue_pair(BDRVNVMeState *s,
211 AioContext *aio_context,
1b539bd6 212 unsigned idx, size_t size,
bdd6a90a
FZ
213 Error **errp)
214{
215 int i, r;
0ea45f76 216 NVMeQueuePair *q;
bdd6a90a 217 uint64_t prp_list_iova;
f8fd3eba 218 size_t bytes;
bdd6a90a 219
0ea45f76
PMD
220 q = g_try_new0(NVMeQueuePair, 1);
221 if (!q) {
222 return NULL;
223 }
6e1e9ff2
PMD
224 trace_nvme_create_queue_pair(idx, q, size, aio_context,
225 event_notifier_get_fd(s->irq_notifier));
f8fd3eba
EA
226 bytes = QEMU_ALIGN_UP(s->page_size * NVME_NUM_REQS,
227 qemu_real_host_page_size);
228 q->prp_list_pages = qemu_try_memalign(qemu_real_host_page_size, bytes);
0ea45f76
PMD
229 if (!q->prp_list_pages) {
230 goto fail;
231 }
f8fd3eba 232 memset(q->prp_list_pages, 0, bytes);
bdd6a90a 233 qemu_mutex_init(&q->lock);
b75fd5f5 234 q->s = s;
bdd6a90a
FZ
235 q->index = idx;
236 qemu_co_queue_init(&q->free_req_queue);
0a28b02e 237 q->completion_bh = aio_bh_new(aio_context, nvme_process_completion_bh, q);
f8fd3eba 238 r = qemu_vfio_dma_map(s->vfio, q->prp_list_pages, bytes,
bdd6a90a
FZ
239 false, &prp_list_iova);
240 if (r) {
241 goto fail;
242 }
1086e95d
SH
243 q->free_req_head = -1;
244 for (i = 0; i < NVME_NUM_REQS; i++) {
bdd6a90a
FZ
245 NVMeRequest *req = &q->reqs[i];
246 req->cid = i + 1;
1086e95d
SH
247 req->free_req_next = q->free_req_head;
248 q->free_req_head = i;
bdd6a90a
FZ
249 req->prp_list_page = q->prp_list_pages + i * s->page_size;
250 req->prp_list_iova = prp_list_iova + i * s->page_size;
251 }
1086e95d 252
dfa9c6c6 253 if (!nvme_init_queue(s, &q->sq, size, NVME_SQ_ENTRY_BYTES, errp)) {
bdd6a90a
FZ
254 goto fail;
255 }
f6845323 256 q->sq.doorbell = &s->doorbells[idx * s->doorbell_scale].sq_tail;
bdd6a90a 257
dfa9c6c6 258 if (!nvme_init_queue(s, &q->cq, size, NVME_CQ_ENTRY_BYTES, errp)) {
bdd6a90a
FZ
259 goto fail;
260 }
f6845323 261 q->cq.doorbell = &s->doorbells[idx * s->doorbell_scale].cq_head;
bdd6a90a
FZ
262
263 return q;
264fail:
b75fd5f5 265 nvme_free_queue_pair(q);
bdd6a90a
FZ
266 return NULL;
267}
268
269/* With q->lock */
b75fd5f5 270static void nvme_kick(NVMeQueuePair *q)
bdd6a90a 271{
b75fd5f5
SH
272 BDRVNVMeState *s = q->s;
273
bdd6a90a
FZ
274 if (s->plugged || !q->need_kick) {
275 return;
276 }
277 trace_nvme_kick(s, q->index);
278 assert(!(q->sq.tail & 0xFF00));
279 /* Fence the write to submission queue entry before notifying the device. */
280 smp_wmb();
281 *q->sq.doorbell = cpu_to_le32(q->sq.tail);
282 q->inflight += q->need_kick;
283 q->need_kick = 0;
284}
285
286/* Find a free request element if any, otherwise:
287 * a) if in coroutine context, try to wait for one to become available;
288 * b) if not in coroutine, return NULL;
289 */
290static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
291{
1086e95d 292 NVMeRequest *req;
bdd6a90a
FZ
293
294 qemu_mutex_lock(&q->lock);
1086e95d
SH
295
296 while (q->free_req_head == -1) {
bdd6a90a 297 if (qemu_in_coroutine()) {
51e98b6d 298 trace_nvme_free_req_queue_wait(q->s, q->index);
bdd6a90a
FZ
299 qemu_co_queue_wait(&q->free_req_queue, &q->lock);
300 } else {
301 qemu_mutex_unlock(&q->lock);
302 return NULL;
303 }
304 }
1086e95d
SH
305
306 req = &q->reqs[q->free_req_head];
307 q->free_req_head = req->free_req_next;
308 req->free_req_next = -1;
309
bdd6a90a
FZ
310 qemu_mutex_unlock(&q->lock);
311 return req;
312}
313
1086e95d
SH
314/* With q->lock */
315static void nvme_put_free_req_locked(NVMeQueuePair *q, NVMeRequest *req)
316{
317 req->free_req_next = q->free_req_head;
318 q->free_req_head = req - q->reqs;
319}
320
321/* With q->lock */
b75fd5f5 322static void nvme_wake_free_req_locked(NVMeQueuePair *q)
1086e95d
SH
323{
324 if (!qemu_co_queue_empty(&q->free_req_queue)) {
b75fd5f5 325 replay_bh_schedule_oneshot_event(q->s->aio_context,
1086e95d
SH
326 nvme_free_req_queue_cb, q);
327 }
328}
329
330/* Insert a request in the freelist and wake waiters */
b75fd5f5 331static void nvme_put_free_req_and_wake(NVMeQueuePair *q, NVMeRequest *req)
1086e95d
SH
332{
333 qemu_mutex_lock(&q->lock);
334 nvme_put_free_req_locked(q, req);
b75fd5f5 335 nvme_wake_free_req_locked(q);
1086e95d
SH
336 qemu_mutex_unlock(&q->lock);
337}
338
bdd6a90a
FZ
339static inline int nvme_translate_error(const NvmeCqe *c)
340{
341 uint16_t status = (le16_to_cpu(c->status) >> 1) & 0xFF;
342 if (status) {
343 trace_nvme_error(le32_to_cpu(c->result),
344 le16_to_cpu(c->sq_head),
345 le16_to_cpu(c->sq_id),
346 le16_to_cpu(c->cid),
347 le16_to_cpu(status));
348 }
349 switch (status) {
350 case 0:
351 return 0;
352 case 1:
353 return -ENOSYS;
354 case 2:
355 return -EINVAL;
356 default:
357 return -EIO;
358 }
359}
360
361/* With q->lock */
b75fd5f5 362static bool nvme_process_completion(NVMeQueuePair *q)
bdd6a90a 363{
b75fd5f5 364 BDRVNVMeState *s = q->s;
bdd6a90a
FZ
365 bool progress = false;
366 NVMeRequest *preq;
367 NVMeRequest req;
368 NvmeCqe *c;
369
370 trace_nvme_process_completion(s, q->index, q->inflight);
7838c67f
SH
371 if (s->plugged) {
372 trace_nvme_process_completion_queue_plugged(s, q->index);
bdd6a90a
FZ
373 return false;
374 }
7838c67f
SH
375
376 /*
377 * Support re-entrancy when a request cb() function invokes aio_poll().
378 * Pending completions must be visible to aio_poll() so that a cb()
379 * function can wait for the completion of another request.
380 *
381 * The aio_poll() loop will execute our BH and we'll resume completion
382 * processing there.
383 */
384 qemu_bh_schedule(q->completion_bh);
385
bdd6a90a
FZ
386 assert(q->inflight >= 0);
387 while (q->inflight) {
04b3fb39 388 int ret;
bdd6a90a 389 int16_t cid;
04b3fb39 390
bdd6a90a 391 c = (NvmeCqe *)&q->cq.queue[q->cq.head * NVME_CQ_ENTRY_BYTES];
258867d1 392 if ((le16_to_cpu(c->status) & 0x1) == q->cq_phase) {
bdd6a90a
FZ
393 break;
394 }
04b3fb39 395 ret = nvme_translate_error(c);
f25e7ab2
PMD
396 if (ret) {
397 s->stats.completion_errors++;
398 }
bdd6a90a
FZ
399 q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
400 if (!q->cq.head) {
401 q->cq_phase = !q->cq_phase;
402 }
403 cid = le16_to_cpu(c->cid);
404 if (cid == 0 || cid > NVME_QUEUE_SIZE) {
58ad6ae0
PMD
405 warn_report("NVMe: Unexpected CID in completion queue: %"PRIu32", "
406 "queue size: %u", cid, NVME_QUEUE_SIZE);
bdd6a90a
FZ
407 continue;
408 }
bdd6a90a
FZ
409 trace_nvme_complete_command(s, q->index, cid);
410 preq = &q->reqs[cid - 1];
411 req = *preq;
412 assert(req.cid == cid);
413 assert(req.cb);
1086e95d 414 nvme_put_free_req_locked(q, preq);
bdd6a90a 415 preq->cb = preq->opaque = NULL;
7838c67f 416 q->inflight--;
bdd6a90a 417 qemu_mutex_unlock(&q->lock);
04b3fb39 418 req.cb(req.opaque, ret);
bdd6a90a 419 qemu_mutex_lock(&q->lock);
bdd6a90a
FZ
420 progress = true;
421 }
422 if (progress) {
423 /* Notify the device so it can post more completions. */
424 smp_mb_release();
425 *q->cq.doorbell = cpu_to_le32(q->cq.head);
b75fd5f5 426 nvme_wake_free_req_locked(q);
bdd6a90a 427 }
7838c67f
SH
428
429 qemu_bh_cancel(q->completion_bh);
430
bdd6a90a
FZ
431 return progress;
432}
433
7838c67f
SH
434static void nvme_process_completion_bh(void *opaque)
435{
436 NVMeQueuePair *q = opaque;
437
438 /*
439 * We're being invoked because a nvme_process_completion() cb() function
440 * called aio_poll(). The callback may be waiting for further completions
441 * so notify the device that it has space to fill in more completions now.
442 */
443 smp_mb_release();
444 *q->cq.doorbell = cpu_to_le32(q->cq.head);
445 nvme_wake_free_req_locked(q);
446
447 nvme_process_completion(q);
448}
449
bdd6a90a
FZ
450static void nvme_trace_command(const NvmeCmd *cmd)
451{
452 int i;
453
e266f52c
PMD
454 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW)) {
455 return;
456 }
bdd6a90a
FZ
457 for (i = 0; i < 8; ++i) {
458 uint8_t *cmdp = (uint8_t *)cmd + i * 8;
459 trace_nvme_submit_command_raw(cmdp[0], cmdp[1], cmdp[2], cmdp[3],
460 cmdp[4], cmdp[5], cmdp[6], cmdp[7]);
461 }
462}
463
b75fd5f5 464static void nvme_submit_command(NVMeQueuePair *q, NVMeRequest *req,
bdd6a90a
FZ
465 NvmeCmd *cmd, BlockCompletionFunc cb,
466 void *opaque)
467{
468 assert(!req->cb);
469 req->cb = cb;
470 req->opaque = opaque;
471 cmd->cid = cpu_to_le32(req->cid);
472
b75fd5f5 473 trace_nvme_submit_command(q->s, q->index, req->cid);
bdd6a90a
FZ
474 nvme_trace_command(cmd);
475 qemu_mutex_lock(&q->lock);
476 memcpy((uint8_t *)q->sq.queue +
477 q->sq.tail * NVME_SQ_ENTRY_BYTES, cmd, sizeof(*cmd));
478 q->sq.tail = (q->sq.tail + 1) % NVME_QUEUE_SIZE;
479 q->need_kick++;
b75fd5f5
SH
480 nvme_kick(q);
481 nvme_process_completion(q);
bdd6a90a
FZ
482 qemu_mutex_unlock(&q->lock);
483}
484
08d54067 485static void nvme_admin_cmd_sync_cb(void *opaque, int ret)
bdd6a90a
FZ
486{
487 int *pret = opaque;
488 *pret = ret;
4720cbee 489 aio_wait_kick();
bdd6a90a
FZ
490}
491
08d54067 492static int nvme_admin_cmd_sync(BlockDriverState *bs, NvmeCmd *cmd)
bdd6a90a 493{
08d54067
PMD
494 BDRVNVMeState *s = bs->opaque;
495 NVMeQueuePair *q = s->queues[INDEX_ADMIN];
073a0697 496 AioContext *aio_context = bdrv_get_aio_context(bs);
bdd6a90a 497 NVMeRequest *req;
bdd6a90a
FZ
498 int ret = -EINPROGRESS;
499 req = nvme_get_free_req(q);
500 if (!req) {
501 return -EBUSY;
502 }
08d54067 503 nvme_submit_command(q, req, cmd, nvme_admin_cmd_sync_cb, &ret);
bdd6a90a 504
073a0697 505 AIO_WAIT_WHILE(aio_context, ret == -EINPROGRESS);
bdd6a90a
FZ
506 return ret;
507}
508
7a5f00dd
PMD
509/* Returns true on success, false on failure. */
510static bool nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
bdd6a90a
FZ
511{
512 BDRVNVMeState *s = bs->opaque;
7a5f00dd 513 bool ret = false;
7d3b214a
PMD
514 union {
515 NvmeIdCtrl ctrl;
516 NvmeIdNs ns;
517 } *id;
118d1b6a 518 NvmeLBAF *lbaf;
e0dd95e3 519 uint16_t oncs;
1120407b 520 int r;
bdd6a90a
FZ
521 uint64_t iova;
522 NvmeCmd cmd = {
523 .opcode = NVME_ADM_CMD_IDENTIFY,
524 .cdw10 = cpu_to_le32(0x1),
525 };
0aecd060 526 size_t id_size = QEMU_ALIGN_UP(sizeof(*id), qemu_real_host_page_size);
bdd6a90a 527
0aecd060 528 id = qemu_try_memalign(qemu_real_host_page_size, id_size);
4d980939 529 if (!id) {
bdd6a90a
FZ
530 error_setg(errp, "Cannot allocate buffer for identify response");
531 goto out;
532 }
0aecd060 533 r = qemu_vfio_dma_map(s->vfio, id, id_size, true, &iova);
bdd6a90a
FZ
534 if (r) {
535 error_setg(errp, "Cannot map buffer for DMA");
536 goto out;
537 }
bdd6a90a 538
0aecd060 539 memset(id, 0, id_size);
2ed84693 540 cmd.dptr.prp1 = cpu_to_le64(iova);
08d54067 541 if (nvme_admin_cmd_sync(bs, &cmd)) {
bdd6a90a
FZ
542 error_setg(errp, "Failed to identify controller");
543 goto out;
544 }
545
7d3b214a 546 if (le32_to_cpu(id->ctrl.nn) < namespace) {
bdd6a90a
FZ
547 error_setg(errp, "Invalid namespace");
548 goto out;
549 }
7d3b214a
PMD
550 s->write_cache_supported = le32_to_cpu(id->ctrl.vwc) & 0x1;
551 s->max_transfer = (id->ctrl.mdts ? 1 << id->ctrl.mdts : 0) * s->page_size;
bdd6a90a
FZ
552 /* For now the page list buffer per command is one page, to hold at most
553 * s->page_size / sizeof(uint64_t) entries. */
554 s->max_transfer = MIN_NON_ZERO(s->max_transfer,
555 s->page_size / sizeof(uint64_t) * s->page_size);
556
7d3b214a 557 oncs = le16_to_cpu(id->ctrl.oncs);
69265150 558 s->supports_write_zeroes = !!(oncs & NVME_ONCS_WRITE_ZEROES);
e87a09d6 559 s->supports_discard = !!(oncs & NVME_ONCS_DSM);
e0dd95e3 560
0aecd060 561 memset(id, 0, id_size);
bdd6a90a
FZ
562 cmd.cdw10 = 0;
563 cmd.nsid = cpu_to_le32(namespace);
08d54067 564 if (nvme_admin_cmd_sync(bs, &cmd)) {
bdd6a90a
FZ
565 error_setg(errp, "Failed to identify namespace");
566 goto out;
567 }
568
7d3b214a
PMD
569 s->nsze = le64_to_cpu(id->ns.nsze);
570 lbaf = &id->ns.lbaf[NVME_ID_NS_FLBAS_INDEX(id->ns.flbas)];
118d1b6a 571
7d3b214a
PMD
572 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id->ns.dlfeat) &&
573 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id->ns.dlfeat) ==
e0dd95e3
ML
574 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES) {
575 bs->supported_write_flags |= BDRV_REQ_MAY_UNMAP;
576 }
577
118d1b6a
ML
578 if (lbaf->ms) {
579 error_setg(errp, "Namespaces with metadata are not yet supported");
580 goto out;
581 }
582
1120407b
HR
583 if (lbaf->ds < BDRV_SECTOR_BITS || lbaf->ds > 12 ||
584 (1 << lbaf->ds) > s->page_size)
585 {
586 error_setg(errp, "Namespace has unsupported block size (2^%d)",
587 lbaf->ds);
118d1b6a
ML
588 goto out;
589 }
bdd6a90a 590
7a5f00dd 591 ret = true;
118d1b6a 592 s->blkshift = lbaf->ds;
bdd6a90a 593out:
4d980939
PMD
594 qemu_vfio_dma_unmap(s->vfio, id);
595 qemu_vfree(id);
7a5f00dd
PMD
596
597 return ret;
bdd6a90a
FZ
598}
599
7a1fb2ef
PMD
600static bool nvme_poll_queue(NVMeQueuePair *q)
601{
602 bool progress = false;
603
604 const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
605 NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
606
1c914cd1 607 trace_nvme_poll_queue(q->s, q->index);
7a1fb2ef
PMD
608 /*
609 * Do an early check for completions. q->lock isn't needed because
610 * nvme_process_completion() only runs in the event loop thread and
611 * cannot race with itself.
612 */
613 if ((le16_to_cpu(cqe->status) & 0x1) == q->cq_phase) {
614 return false;
615 }
616
617 qemu_mutex_lock(&q->lock);
618 while (nvme_process_completion(q)) {
619 /* Keep polling */
620 progress = true;
621 }
622 qemu_mutex_unlock(&q->lock);
623
624 return progress;
625}
626
bdd6a90a
FZ
627static bool nvme_poll_queues(BDRVNVMeState *s)
628{
629 bool progress = false;
630 int i;
631
1b539bd6 632 for (i = 0; i < s->queue_count; i++) {
7a1fb2ef 633 if (nvme_poll_queue(s->queues[i])) {
bdd6a90a
FZ
634 progress = true;
635 }
bdd6a90a
FZ
636 }
637 return progress;
638}
639
640static void nvme_handle_event(EventNotifier *n)
641{
b111b3fc
PMD
642 BDRVNVMeState *s = container_of(n, BDRVNVMeState,
643 irq_notifier[MSIX_SHARED_IRQ_IDX]);
bdd6a90a
FZ
644
645 trace_nvme_handle_event(s);
bdd6a90a
FZ
646 event_notifier_test_and_clear(n);
647 nvme_poll_queues(s);
bdd6a90a
FZ
648}
649
650static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
651{
652 BDRVNVMeState *s = bs->opaque;
1b539bd6 653 unsigned n = s->queue_count;
bdd6a90a
FZ
654 NVMeQueuePair *q;
655 NvmeCmd cmd;
1b539bd6 656 unsigned queue_size = NVME_QUEUE_SIZE;
bdd6a90a 657
76a24781 658 assert(n <= UINT16_MAX);
0a28b02e
PMD
659 q = nvme_create_queue_pair(s, bdrv_get_aio_context(bs),
660 n, queue_size, errp);
bdd6a90a
FZ
661 if (!q) {
662 return false;
663 }
664 cmd = (NvmeCmd) {
665 .opcode = NVME_ADM_CMD_CREATE_CQ,
c26f2173 666 .dptr.prp1 = cpu_to_le64(q->cq.iova),
76a24781
PMD
667 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
668 .cdw11 = cpu_to_le32(NVME_CQ_IEN | NVME_CQ_PC),
bdd6a90a 669 };
08d54067 670 if (nvme_admin_cmd_sync(bs, &cmd)) {
1b539bd6 671 error_setg(errp, "Failed to create CQ io queue [%u]", n);
c8edbfb2 672 goto out_error;
bdd6a90a
FZ
673 }
674 cmd = (NvmeCmd) {
675 .opcode = NVME_ADM_CMD_CREATE_SQ,
c26f2173 676 .dptr.prp1 = cpu_to_le64(q->sq.iova),
76a24781
PMD
677 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
678 .cdw11 = cpu_to_le32(NVME_SQ_PC | (n << 16)),
bdd6a90a 679 };
08d54067 680 if (nvme_admin_cmd_sync(bs, &cmd)) {
1b539bd6 681 error_setg(errp, "Failed to create SQ io queue [%u]", n);
c8edbfb2 682 goto out_error;
bdd6a90a
FZ
683 }
684 s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
685 s->queues[n] = q;
1b539bd6 686 s->queue_count++;
bdd6a90a 687 return true;
c8edbfb2
PMD
688out_error:
689 nvme_free_queue_pair(q);
690 return false;
bdd6a90a
FZ
691}
692
693static bool nvme_poll_cb(void *opaque)
694{
695 EventNotifier *e = opaque;
b111b3fc
PMD
696 BDRVNVMeState *s = container_of(e, BDRVNVMeState,
697 irq_notifier[MSIX_SHARED_IRQ_IDX]);
bdd6a90a 698
b3ac2b94 699 return nvme_poll_queues(s);
bdd6a90a
FZ
700}
701
702static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
703 Error **errp)
704{
705 BDRVNVMeState *s = bs->opaque;
52b75ea8 706 NVMeQueuePair *q;
0a28b02e 707 AioContext *aio_context = bdrv_get_aio_context(bs);
bdd6a90a
FZ
708 int ret;
709 uint64_t cap;
710 uint64_t timeout_ms;
711 uint64_t deadline, now;
9406e0d9 712 volatile NvmeBar *regs = NULL;
bdd6a90a
FZ
713
714 qemu_co_mutex_init(&s->dma_map_lock);
715 qemu_co_queue_init(&s->dma_flush_queue);
cc61b074 716 s->device = g_strdup(device);
bdd6a90a
FZ
717 s->nsid = namespace;
718 s->aio_context = bdrv_get_aio_context(bs);
b111b3fc 719 ret = event_notifier_init(&s->irq_notifier[MSIX_SHARED_IRQ_IDX], 0);
bdd6a90a
FZ
720 if (ret) {
721 error_setg(errp, "Failed to init event notifier");
722 return ret;
723 }
724
725 s->vfio = qemu_vfio_open_pci(device, errp);
726 if (!s->vfio) {
727 ret = -EINVAL;
9582f357 728 goto out;
bdd6a90a
FZ
729 }
730
37d7a45a
PMD
731 regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, sizeof(NvmeBar),
732 PROT_READ | PROT_WRITE, errp);
733 if (!regs) {
bdd6a90a 734 ret = -EINVAL;
9582f357 735 goto out;
bdd6a90a 736 }
bdd6a90a
FZ
737 /* Perform initialize sequence as described in NVMe spec "7.6.1
738 * Initialization". */
739
9406e0d9 740 cap = le64_to_cpu(regs->cap);
15b2260b
PMD
741 trace_nvme_controller_capability_raw(cap);
742 trace_nvme_controller_capability("Maximum Queue Entries Supported",
743 1 + NVME_CAP_MQES(cap));
744 trace_nvme_controller_capability("Contiguous Queues Required",
745 NVME_CAP_CQR(cap));
746 trace_nvme_controller_capability("Doorbell Stride",
747 2 << (2 + NVME_CAP_DSTRD(cap)));
748 trace_nvme_controller_capability("Subsystem Reset Supported",
749 NVME_CAP_NSSRS(cap));
750 trace_nvme_controller_capability("Memory Page Size Minimum",
751 1 << (12 + NVME_CAP_MPSMIN(cap)));
752 trace_nvme_controller_capability("Memory Page Size Maximum",
753 1 << (12 + NVME_CAP_MPSMAX(cap)));
fad1eb68 754 if (!NVME_CAP_CSS(cap)) {
bdd6a90a
FZ
755 error_setg(errp, "Device doesn't support NVMe command set");
756 ret = -EINVAL;
9582f357 757 goto out;
bdd6a90a
FZ
758 }
759
a652a3ec 760 s->page_size = 1u << (12 + NVME_CAP_MPSMIN(cap));
fad1eb68 761 s->doorbell_scale = (4 << NVME_CAP_DSTRD(cap)) / sizeof(uint32_t);
bdd6a90a 762 bs->bl.opt_mem_alignment = s->page_size;
c8228ac3 763 bs->bl.request_alignment = s->page_size;
fad1eb68 764 timeout_ms = MIN(500 * NVME_CAP_TO(cap), 30000);
bdd6a90a
FZ
765
766 /* Reset device to get a clean state. */
9406e0d9 767 regs->cc = cpu_to_le32(le32_to_cpu(regs->cc) & 0xFE);
bdd6a90a 768 /* Wait for CSTS.RDY = 0. */
e4f310fe 769 deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * SCALE_MS;
fad1eb68 770 while (NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
bdd6a90a
FZ
771 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
772 error_setg(errp, "Timeout while waiting for device to reset (%"
773 PRId64 " ms)",
774 timeout_ms);
775 ret = -ETIMEDOUT;
9582f357 776 goto out;
bdd6a90a
FZ
777 }
778 }
779
f6845323
PMD
780 s->doorbells = qemu_vfio_pci_map_bar(s->vfio, 0, sizeof(NvmeBar),
781 NVME_DOORBELL_SIZE, PROT_WRITE, errp);
782 if (!s->doorbells) {
783 ret = -EINVAL;
784 goto out;
785 }
786
bdd6a90a
FZ
787 /* Set up admin queue. */
788 s->queues = g_new(NVMeQueuePair *, 1);
52b75ea8
PMD
789 q = nvme_create_queue_pair(s, aio_context, 0, NVME_QUEUE_SIZE, errp);
790 if (!q) {
bdd6a90a 791 ret = -EINVAL;
9582f357 792 goto out;
bdd6a90a 793 }
52b75ea8 794 s->queues[INDEX_ADMIN] = q;
1b539bd6 795 s->queue_count = 1;
3c363c07
PMD
796 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE - 1) & 0xF000);
797 regs->aqa = cpu_to_le32(((NVME_QUEUE_SIZE - 1) << AQA_ACQS_SHIFT) |
798 ((NVME_QUEUE_SIZE - 1) << AQA_ASQS_SHIFT));
52b75ea8
PMD
799 regs->asq = cpu_to_le64(q->sq.iova);
800 regs->acq = cpu_to_le64(q->cq.iova);
bdd6a90a
FZ
801
802 /* After setting up all control registers we can enable device now. */
fad1eb68
PMD
803 regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << CC_IOCQES_SHIFT) |
804 (ctz32(NVME_SQ_ENTRY_BYTES) << CC_IOSQES_SHIFT) |
805 CC_EN_MASK);
bdd6a90a
FZ
806 /* Wait for CSTS.RDY = 1. */
807 now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
eefffb02 808 deadline = now + timeout_ms * SCALE_MS;
fad1eb68 809 while (!NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
bdd6a90a
FZ
810 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
811 error_setg(errp, "Timeout while waiting for device to start (%"
812 PRId64 " ms)",
813 timeout_ms);
814 ret = -ETIMEDOUT;
9582f357 815 goto out;
bdd6a90a
FZ
816 }
817 }
818
b111b3fc 819 ret = qemu_vfio_pci_init_irq(s->vfio, s->irq_notifier,
bdd6a90a
FZ
820 VFIO_PCI_MSIX_IRQ_INDEX, errp);
821 if (ret) {
9582f357 822 goto out;
bdd6a90a 823 }
b111b3fc
PMD
824 aio_set_event_notifier(bdrv_get_aio_context(bs),
825 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
bdd6a90a
FZ
826 false, nvme_handle_event, nvme_poll_cb);
827
7a5f00dd 828 if (!nvme_identify(bs, namespace, errp)) {
bdd6a90a 829 ret = -EIO;
9582f357 830 goto out;
bdd6a90a
FZ
831 }
832
833 /* Set up command queues. */
834 if (!nvme_add_io_queue(bs, errp)) {
835 ret = -EIO;
bdd6a90a 836 }
9582f357 837out:
37d7a45a
PMD
838 if (regs) {
839 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)regs, 0, sizeof(NvmeBar));
840 }
841
9582f357 842 /* Cleaning up is done in nvme_file_open() upon error. */
bdd6a90a
FZ
843 return ret;
844}
845
846/* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
847 *
848 * nvme://0000:44:00.0/1
849 *
850 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
851 * is the PCI address, and the last part is the namespace number starting from
852 * 1 according to the NVMe spec. */
853static void nvme_parse_filename(const char *filename, QDict *options,
854 Error **errp)
855{
856 int pref = strlen("nvme://");
857
858 if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
859 const char *tmp = filename + pref;
860 char *device;
861 const char *namespace;
862 unsigned long ns;
863 const char *slash = strchr(tmp, '/');
864 if (!slash) {
625eaca9 865 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
bdd6a90a
FZ
866 return;
867 }
868 device = g_strndup(tmp, slash - tmp);
625eaca9 869 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
bdd6a90a
FZ
870 g_free(device);
871 namespace = slash + 1;
872 if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
873 error_setg(errp, "Invalid namespace '%s', positive number expected",
874 namespace);
875 return;
876 }
625eaca9
LV
877 qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
878 *namespace ? namespace : "1");
bdd6a90a
FZ
879 }
880}
881
882static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
883 Error **errp)
884{
885 int ret;
886 BDRVNVMeState *s = bs->opaque;
887 NvmeCmd cmd = {
888 .opcode = NVME_ADM_CMD_SET_FEATURES,
889 .nsid = cpu_to_le32(s->nsid),
890 .cdw10 = cpu_to_le32(0x06),
891 .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
892 };
893
08d54067 894 ret = nvme_admin_cmd_sync(bs, &cmd);
bdd6a90a
FZ
895 if (ret) {
896 error_setg(errp, "Failed to configure NVMe write cache");
897 }
898 return ret;
899}
900
901static void nvme_close(BlockDriverState *bs)
902{
bdd6a90a
FZ
903 BDRVNVMeState *s = bs->opaque;
904
1b539bd6 905 for (unsigned i = 0; i < s->queue_count; ++i) {
b75fd5f5 906 nvme_free_queue_pair(s->queues[i]);
bdd6a90a 907 }
9582f357 908 g_free(s->queues);
b111b3fc
PMD
909 aio_set_event_notifier(bdrv_get_aio_context(bs),
910 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
bdd6a90a 911 false, NULL, NULL);
b111b3fc 912 event_notifier_cleanup(&s->irq_notifier[MSIX_SHARED_IRQ_IDX]);
f6845323
PMD
913 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)s->doorbells,
914 sizeof(NvmeBar), NVME_DOORBELL_SIZE);
bdd6a90a 915 qemu_vfio_close(s->vfio);
cc61b074
HR
916
917 g_free(s->device);
bdd6a90a
FZ
918}
919
920static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
921 Error **errp)
922{
923 const char *device;
924 QemuOpts *opts;
925 int namespace;
926 int ret;
927 BDRVNVMeState *s = bs->opaque;
928
e0dd95e3
ML
929 bs->supported_write_flags = BDRV_REQ_FUA;
930
bdd6a90a
FZ
931 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
932 qemu_opts_absorb_qdict(opts, options, &error_abort);
933 device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
934 if (!device) {
935 error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
936 qemu_opts_del(opts);
937 return -EINVAL;
938 }
939
940 namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
941 ret = nvme_init(bs, device, namespace, errp);
942 qemu_opts_del(opts);
943 if (ret) {
944 goto fail;
945 }
946 if (flags & BDRV_O_NOCACHE) {
947 if (!s->write_cache_supported) {
948 error_setg(errp,
949 "NVMe controller doesn't support write cache configuration");
950 ret = -EINVAL;
951 } else {
952 ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
953 errp);
954 }
955 if (ret) {
956 goto fail;
957 }
958 }
bdd6a90a
FZ
959 return 0;
960fail:
961 nvme_close(bs);
962 return ret;
963}
964
965static int64_t nvme_getlength(BlockDriverState *bs)
966{
967 BDRVNVMeState *s = bs->opaque;
118d1b6a
ML
968 return s->nsze << s->blkshift;
969}
bdd6a90a 970
1120407b 971static uint32_t nvme_get_blocksize(BlockDriverState *bs)
118d1b6a
ML
972{
973 BDRVNVMeState *s = bs->opaque;
1120407b
HR
974 assert(s->blkshift >= BDRV_SECTOR_BITS && s->blkshift <= 12);
975 return UINT32_C(1) << s->blkshift;
118d1b6a
ML
976}
977
978static int nvme_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
979{
1120407b 980 uint32_t blocksize = nvme_get_blocksize(bs);
118d1b6a
ML
981 bsz->phys = blocksize;
982 bsz->log = blocksize;
983 return 0;
bdd6a90a
FZ
984}
985
986/* Called with s->dma_map_lock */
987static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
988 QEMUIOVector *qiov)
989{
990 int r = 0;
991 BDRVNVMeState *s = bs->opaque;
992
993 s->dma_map_count -= qiov->size;
994 if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
995 r = qemu_vfio_dma_reset_temporary(s->vfio);
996 if (!r) {
997 qemu_co_queue_restart_all(&s->dma_flush_queue);
998 }
999 }
1000 return r;
1001}
1002
1003/* Called with s->dma_map_lock */
1004static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
1005 NVMeRequest *req, QEMUIOVector *qiov)
1006{
1007 BDRVNVMeState *s = bs->opaque;
1008 uint64_t *pagelist = req->prp_list_page;
1009 int i, j, r;
1010 int entries = 0;
1011
1012 assert(qiov->size);
1013 assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
1014 assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
1015 for (i = 0; i < qiov->niov; ++i) {
1016 bool retry = true;
1017 uint64_t iova;
1018try_map:
1019 r = qemu_vfio_dma_map(s->vfio,
1020 qiov->iov[i].iov_base,
1021 qiov->iov[i].iov_len,
1022 true, &iova);
1023 if (r == -ENOMEM && retry) {
1024 retry = false;
1025 trace_nvme_dma_flush_queue_wait(s);
1026 if (s->dma_map_count) {
1027 trace_nvme_dma_map_flush(s);
1028 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
1029 } else {
1030 r = qemu_vfio_dma_reset_temporary(s->vfio);
1031 if (r) {
1032 goto fail;
1033 }
1034 }
1035 goto try_map;
1036 }
1037 if (r) {
1038 goto fail;
1039 }
1040
1041 for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
2916405a 1042 pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
bdd6a90a
FZ
1043 }
1044 trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
1045 qiov->iov[i].iov_len / s->page_size);
1046 }
1047
1048 s->dma_map_count += qiov->size;
1049
1050 assert(entries <= s->page_size / sizeof(uint64_t));
1051 switch (entries) {
1052 case 0:
1053 abort();
1054 case 1:
c26f2173
KJ
1055 cmd->dptr.prp1 = pagelist[0];
1056 cmd->dptr.prp2 = 0;
bdd6a90a
FZ
1057 break;
1058 case 2:
c26f2173
KJ
1059 cmd->dptr.prp1 = pagelist[0];
1060 cmd->dptr.prp2 = pagelist[1];
bdd6a90a
FZ
1061 break;
1062 default:
c26f2173
KJ
1063 cmd->dptr.prp1 = pagelist[0];
1064 cmd->dptr.prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
bdd6a90a
FZ
1065 break;
1066 }
1067 trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
1068 for (i = 0; i < entries; ++i) {
1069 trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
1070 }
1071 return 0;
1072fail:
1073 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1074 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1075 * because they are already mapped before calling this function; for
1076 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1077 * calling qemu_vfio_dma_reset_temporary when necessary. */
1078 return r;
1079}
1080
1081typedef struct {
1082 Coroutine *co;
1083 int ret;
1084 AioContext *ctx;
1085} NVMeCoData;
1086
1087static void nvme_rw_cb_bh(void *opaque)
1088{
1089 NVMeCoData *data = opaque;
1090 qemu_coroutine_enter(data->co);
1091}
1092
1093static void nvme_rw_cb(void *opaque, int ret)
1094{
1095 NVMeCoData *data = opaque;
1096 data->ret = ret;
1097 if (!data->co) {
1098 /* The rw coroutine hasn't yielded, don't try to enter. */
1099 return;
1100 }
e4ec5ad4 1101 replay_bh_schedule_oneshot_event(data->ctx, nvme_rw_cb_bh, data);
bdd6a90a
FZ
1102}
1103
1104static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
1105 uint64_t offset, uint64_t bytes,
1106 QEMUIOVector *qiov,
1107 bool is_write,
1108 int flags)
1109{
1110 int r;
1111 BDRVNVMeState *s = bs->opaque;
73159e52 1112 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
bdd6a90a 1113 NVMeRequest *req;
118d1b6a
ML
1114
1115 uint32_t cdw12 = (((bytes >> s->blkshift) - 1) & 0xFFFF) |
bdd6a90a
FZ
1116 (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
1117 NvmeCmd cmd = {
1118 .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
1119 .nsid = cpu_to_le32(s->nsid),
118d1b6a
ML
1120 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1121 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
bdd6a90a
FZ
1122 .cdw12 = cpu_to_le32(cdw12),
1123 };
1124 NVMeCoData data = {
1125 .ctx = bdrv_get_aio_context(bs),
1126 .ret = -EINPROGRESS,
1127 };
1128
1129 trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
1b539bd6 1130 assert(s->queue_count > 1);
bdd6a90a
FZ
1131 req = nvme_get_free_req(ioq);
1132 assert(req);
1133
1134 qemu_co_mutex_lock(&s->dma_map_lock);
1135 r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
1136 qemu_co_mutex_unlock(&s->dma_map_lock);
1137 if (r) {
b75fd5f5 1138 nvme_put_free_req_and_wake(ioq, req);
bdd6a90a
FZ
1139 return r;
1140 }
b75fd5f5 1141 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
bdd6a90a
FZ
1142
1143 data.co = qemu_coroutine_self();
1144 while (data.ret == -EINPROGRESS) {
1145 qemu_coroutine_yield();
1146 }
1147
1148 qemu_co_mutex_lock(&s->dma_map_lock);
1149 r = nvme_cmd_unmap_qiov(bs, qiov);
1150 qemu_co_mutex_unlock(&s->dma_map_lock);
1151 if (r) {
1152 return r;
1153 }
1154
1155 trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
1156 return data.ret;
1157}
1158
1159static inline bool nvme_qiov_aligned(BlockDriverState *bs,
1160 const QEMUIOVector *qiov)
1161{
1162 int i;
1163 BDRVNVMeState *s = bs->opaque;
1164
1165 for (i = 0; i < qiov->niov; ++i) {
1166 if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base, s->page_size) ||
1167 !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, s->page_size)) {
1168 trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
1169 qiov->iov[i].iov_len, s->page_size);
1170 return false;
1171 }
1172 }
1173 return true;
1174}
1175
1176static int nvme_co_prw(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1177 QEMUIOVector *qiov, bool is_write, int flags)
1178{
1179 BDRVNVMeState *s = bs->opaque;
1180 int r;
1181 uint8_t *buf = NULL;
1182 QEMUIOVector local_qiov;
1183
1184 assert(QEMU_IS_ALIGNED(offset, s->page_size));
1185 assert(QEMU_IS_ALIGNED(bytes, s->page_size));
1186 assert(bytes <= s->max_transfer);
1187 if (nvme_qiov_aligned(bs, qiov)) {
f25e7ab2 1188 s->stats.aligned_accesses++;
bdd6a90a
FZ
1189 return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
1190 }
f25e7ab2 1191 s->stats.unaligned_accesses++;
bdd6a90a 1192 trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
38e1f818 1193 buf = qemu_try_memalign(s->page_size, bytes);
bdd6a90a
FZ
1194
1195 if (!buf) {
1196 return -ENOMEM;
1197 }
1198 qemu_iovec_init(&local_qiov, 1);
1199 if (is_write) {
1200 qemu_iovec_to_buf(qiov, 0, buf, bytes);
1201 }
1202 qemu_iovec_add(&local_qiov, buf, bytes);
1203 r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
1204 qemu_iovec_destroy(&local_qiov);
1205 if (!r && !is_write) {
1206 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1207 }
1208 qemu_vfree(buf);
1209 return r;
1210}
1211
1212static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1213 uint64_t offset, uint64_t bytes,
1214 QEMUIOVector *qiov, int flags)
1215{
1216 return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1217}
1218
1219static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1220 uint64_t offset, uint64_t bytes,
1221 QEMUIOVector *qiov, int flags)
1222{
1223 return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1224}
1225
1226static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1227{
1228 BDRVNVMeState *s = bs->opaque;
73159e52 1229 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
bdd6a90a
FZ
1230 NVMeRequest *req;
1231 NvmeCmd cmd = {
1232 .opcode = NVME_CMD_FLUSH,
1233 .nsid = cpu_to_le32(s->nsid),
1234 };
1235 NVMeCoData data = {
1236 .ctx = bdrv_get_aio_context(bs),
1237 .ret = -EINPROGRESS,
1238 };
1239
1b539bd6 1240 assert(s->queue_count > 1);
bdd6a90a
FZ
1241 req = nvme_get_free_req(ioq);
1242 assert(req);
b75fd5f5 1243 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
bdd6a90a
FZ
1244
1245 data.co = qemu_coroutine_self();
1246 if (data.ret == -EINPROGRESS) {
1247 qemu_coroutine_yield();
1248 }
1249
1250 return data.ret;
1251}
1252
1253
e0dd95e3
ML
1254static coroutine_fn int nvme_co_pwrite_zeroes(BlockDriverState *bs,
1255 int64_t offset,
1256 int bytes,
1257 BdrvRequestFlags flags)
1258{
1259 BDRVNVMeState *s = bs->opaque;
73159e52 1260 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
e0dd95e3
ML
1261 NVMeRequest *req;
1262
1263 uint32_t cdw12 = ((bytes >> s->blkshift) - 1) & 0xFFFF;
1264
1265 if (!s->supports_write_zeroes) {
1266 return -ENOTSUP;
1267 }
1268
1269 NvmeCmd cmd = {
69265150 1270 .opcode = NVME_CMD_WRITE_ZEROES,
e0dd95e3
ML
1271 .nsid = cpu_to_le32(s->nsid),
1272 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1273 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1274 };
1275
1276 NVMeCoData data = {
1277 .ctx = bdrv_get_aio_context(bs),
1278 .ret = -EINPROGRESS,
1279 };
1280
1281 if (flags & BDRV_REQ_MAY_UNMAP) {
1282 cdw12 |= (1 << 25);
1283 }
1284
1285 if (flags & BDRV_REQ_FUA) {
1286 cdw12 |= (1 << 30);
1287 }
1288
1289 cmd.cdw12 = cpu_to_le32(cdw12);
1290
1291 trace_nvme_write_zeroes(s, offset, bytes, flags);
1b539bd6 1292 assert(s->queue_count > 1);
e0dd95e3
ML
1293 req = nvme_get_free_req(ioq);
1294 assert(req);
1295
b75fd5f5 1296 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
e0dd95e3
ML
1297
1298 data.co = qemu_coroutine_self();
1299 while (data.ret == -EINPROGRESS) {
1300 qemu_coroutine_yield();
1301 }
1302
1303 trace_nvme_rw_done(s, true, offset, bytes, data.ret);
1304 return data.ret;
1305}
1306
1307
e87a09d6
ML
1308static int coroutine_fn nvme_co_pdiscard(BlockDriverState *bs,
1309 int64_t offset,
1310 int bytes)
1311{
1312 BDRVNVMeState *s = bs->opaque;
73159e52 1313 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
e87a09d6
ML
1314 NVMeRequest *req;
1315 NvmeDsmRange *buf;
1316 QEMUIOVector local_qiov;
1317 int ret;
1318
1319 NvmeCmd cmd = {
1320 .opcode = NVME_CMD_DSM,
1321 .nsid = cpu_to_le32(s->nsid),
1322 .cdw10 = cpu_to_le32(0), /*number of ranges - 0 based*/
1323 .cdw11 = cpu_to_le32(1 << 2), /*deallocate bit*/
1324 };
1325
1326 NVMeCoData data = {
1327 .ctx = bdrv_get_aio_context(bs),
1328 .ret = -EINPROGRESS,
1329 };
1330
1331 if (!s->supports_discard) {
1332 return -ENOTSUP;
1333 }
1334
1b539bd6 1335 assert(s->queue_count > 1);
e87a09d6 1336
38e1f818 1337 buf = qemu_try_memalign(s->page_size, s->page_size);
e87a09d6
ML
1338 if (!buf) {
1339 return -ENOMEM;
1340 }
2ed84693 1341 memset(buf, 0, s->page_size);
e87a09d6
ML
1342 buf->nlb = cpu_to_le32(bytes >> s->blkshift);
1343 buf->slba = cpu_to_le64(offset >> s->blkshift);
1344 buf->cattr = 0;
1345
1346 qemu_iovec_init(&local_qiov, 1);
1347 qemu_iovec_add(&local_qiov, buf, 4096);
1348
1349 req = nvme_get_free_req(ioq);
1350 assert(req);
1351
1352 qemu_co_mutex_lock(&s->dma_map_lock);
1353 ret = nvme_cmd_map_qiov(bs, &cmd, req, &local_qiov);
1354 qemu_co_mutex_unlock(&s->dma_map_lock);
1355
1356 if (ret) {
b75fd5f5 1357 nvme_put_free_req_and_wake(ioq, req);
e87a09d6
ML
1358 goto out;
1359 }
1360
1361 trace_nvme_dsm(s, offset, bytes);
1362
b75fd5f5 1363 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
e87a09d6
ML
1364
1365 data.co = qemu_coroutine_self();
1366 while (data.ret == -EINPROGRESS) {
1367 qemu_coroutine_yield();
1368 }
1369
1370 qemu_co_mutex_lock(&s->dma_map_lock);
1371 ret = nvme_cmd_unmap_qiov(bs, &local_qiov);
1372 qemu_co_mutex_unlock(&s->dma_map_lock);
1373
1374 if (ret) {
1375 goto out;
1376 }
1377
1378 ret = data.ret;
1379 trace_nvme_dsm_done(s, offset, bytes, ret);
1380out:
1381 qemu_iovec_destroy(&local_qiov);
1382 qemu_vfree(buf);
1383 return ret;
1384
1385}
1386
1387
bdd6a90a
FZ
1388static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1389 BlockReopenQueue *queue, Error **errp)
1390{
1391 return 0;
1392}
1393
998b3a1e 1394static void nvme_refresh_filename(BlockDriverState *bs)
bdd6a90a 1395{
cc61b074 1396 BDRVNVMeState *s = bs->opaque;
bdd6a90a 1397
cc61b074
HR
1398 snprintf(bs->exact_filename, sizeof(bs->exact_filename), "nvme://%s/%i",
1399 s->device, s->nsid);
bdd6a90a
FZ
1400}
1401
1402static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1403{
1404 BDRVNVMeState *s = bs->opaque;
1405
1406 bs->bl.opt_mem_alignment = s->page_size;
1407 bs->bl.request_alignment = s->page_size;
1408 bs->bl.max_transfer = s->max_transfer;
1409}
1410
1411static void nvme_detach_aio_context(BlockDriverState *bs)
1412{
1413 BDRVNVMeState *s = bs->opaque;
1414
1b539bd6 1415 for (unsigned i = 0; i < s->queue_count; i++) {
7838c67f
SH
1416 NVMeQueuePair *q = s->queues[i];
1417
1418 qemu_bh_delete(q->completion_bh);
1419 q->completion_bh = NULL;
1420 }
1421
b111b3fc
PMD
1422 aio_set_event_notifier(bdrv_get_aio_context(bs),
1423 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
bdd6a90a
FZ
1424 false, NULL, NULL);
1425}
1426
1427static void nvme_attach_aio_context(BlockDriverState *bs,
1428 AioContext *new_context)
1429{
1430 BDRVNVMeState *s = bs->opaque;
1431
1432 s->aio_context = new_context;
b111b3fc 1433 aio_set_event_notifier(new_context, &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
bdd6a90a 1434 false, nvme_handle_event, nvme_poll_cb);
7838c67f 1435
1b539bd6 1436 for (unsigned i = 0; i < s->queue_count; i++) {
7838c67f
SH
1437 NVMeQueuePair *q = s->queues[i];
1438
1439 q->completion_bh =
1440 aio_bh_new(new_context, nvme_process_completion_bh, q);
1441 }
bdd6a90a
FZ
1442}
1443
1444static void nvme_aio_plug(BlockDriverState *bs)
1445{
1446 BDRVNVMeState *s = bs->opaque;
2f0d8947
PB
1447 assert(!s->plugged);
1448 s->plugged = true;
bdd6a90a
FZ
1449}
1450
1451static void nvme_aio_unplug(BlockDriverState *bs)
1452{
bdd6a90a
FZ
1453 BDRVNVMeState *s = bs->opaque;
1454 assert(s->plugged);
2f0d8947 1455 s->plugged = false;
1b539bd6 1456 for (unsigned i = INDEX_IO(0); i < s->queue_count; i++) {
2f0d8947
PB
1457 NVMeQueuePair *q = s->queues[i];
1458 qemu_mutex_lock(&q->lock);
b75fd5f5
SH
1459 nvme_kick(q);
1460 nvme_process_completion(q);
2f0d8947 1461 qemu_mutex_unlock(&q->lock);
bdd6a90a
FZ
1462 }
1463}
1464
9ed61612
FZ
1465static void nvme_register_buf(BlockDriverState *bs, void *host, size_t size)
1466{
1467 int ret;
1468 BDRVNVMeState *s = bs->opaque;
1469
1470 ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL);
1471 if (ret) {
1472 /* FIXME: we may run out of IOVA addresses after repeated
1473 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1474 * doesn't reclaim addresses for fixed mappings. */
1475 error_report("nvme_register_buf failed: %s", strerror(-ret));
1476 }
1477}
1478
1479static void nvme_unregister_buf(BlockDriverState *bs, void *host)
1480{
1481 BDRVNVMeState *s = bs->opaque;
1482
1483 qemu_vfio_dma_unmap(s->vfio, host);
1484}
1485
f25e7ab2
PMD
1486static BlockStatsSpecific *nvme_get_specific_stats(BlockDriverState *bs)
1487{
1488 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
1489 BDRVNVMeState *s = bs->opaque;
1490
1491 stats->driver = BLOCKDEV_DRIVER_NVME;
1492 stats->u.nvme = (BlockStatsSpecificNvme) {
1493 .completion_errors = s->stats.completion_errors,
1494 .aligned_accesses = s->stats.aligned_accesses,
1495 .unaligned_accesses = s->stats.unaligned_accesses,
1496 };
1497
1498 return stats;
1499}
1500
2654267c
HR
1501static const char *const nvme_strong_runtime_opts[] = {
1502 NVME_BLOCK_OPT_DEVICE,
1503 NVME_BLOCK_OPT_NAMESPACE,
1504
1505 NULL
1506};
1507
bdd6a90a
FZ
1508static BlockDriver bdrv_nvme = {
1509 .format_name = "nvme",
1510 .protocol_name = "nvme",
1511 .instance_size = sizeof(BDRVNVMeState),
1512
5a5e7f8c
ML
1513 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
1514 .create_opts = &bdrv_create_opts_simple,
1515
bdd6a90a
FZ
1516 .bdrv_parse_filename = nvme_parse_filename,
1517 .bdrv_file_open = nvme_file_open,
1518 .bdrv_close = nvme_close,
1519 .bdrv_getlength = nvme_getlength,
118d1b6a 1520 .bdrv_probe_blocksizes = nvme_probe_blocksizes,
bdd6a90a
FZ
1521
1522 .bdrv_co_preadv = nvme_co_preadv,
1523 .bdrv_co_pwritev = nvme_co_pwritev,
e0dd95e3
ML
1524
1525 .bdrv_co_pwrite_zeroes = nvme_co_pwrite_zeroes,
e87a09d6 1526 .bdrv_co_pdiscard = nvme_co_pdiscard,
e0dd95e3 1527
bdd6a90a
FZ
1528 .bdrv_co_flush_to_disk = nvme_co_flush,
1529 .bdrv_reopen_prepare = nvme_reopen_prepare,
1530
bdd6a90a
FZ
1531 .bdrv_refresh_filename = nvme_refresh_filename,
1532 .bdrv_refresh_limits = nvme_refresh_limits,
2654267c 1533 .strong_runtime_opts = nvme_strong_runtime_opts,
f25e7ab2 1534 .bdrv_get_specific_stats = nvme_get_specific_stats,
bdd6a90a
FZ
1535
1536 .bdrv_detach_aio_context = nvme_detach_aio_context,
1537 .bdrv_attach_aio_context = nvme_attach_aio_context,
1538
1539 .bdrv_io_plug = nvme_aio_plug,
1540 .bdrv_io_unplug = nvme_aio_unplug,
9ed61612
FZ
1541
1542 .bdrv_register_buf = nvme_register_buf,
1543 .bdrv_unregister_buf = nvme_unregister_buf,
bdd6a90a
FZ
1544};
1545
1546static void bdrv_nvme_init(void)
1547{
1548 bdrv_register(&bdrv_nvme);
1549}
1550
1551block_init(bdrv_nvme_init);