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