block/nvme: Simplify nvme_cmd_sync()
[qemu/ar7.git] / block / nvme.c
blobcd875555cafbf02e81723181c0f16a2a1e2b4315
1 /*
2 * NVMe block driver based on vfio
4 * Copyright 2016 - 2018 Red Hat, Inc.
6 * Authors:
7 * Fam Zheng <famz@redhat.com>
8 * Paolo Bonzini <pbonzini@redhat.com>
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.
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"
20 #include "qemu/main-loop.h"
21 #include "qemu/module.h"
22 #include "qemu/cutils.h"
23 #include "qemu/option.h"
24 #include "qemu/vfio-helpers.h"
25 #include "block/block_int.h"
26 #include "sysemu/replay.h"
27 #include "trace.h"
29 #include "block/nvme.h"
31 #define NVME_SQ_ENTRY_BYTES 64
32 #define NVME_CQ_ENTRY_BYTES 16
33 #define NVME_QUEUE_SIZE 128
34 #define NVME_DOORBELL_SIZE 4096
37 * We have to leave one slot empty as that is the full queue case where
38 * head == tail + 1.
40 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
42 typedef struct BDRVNVMeState BDRVNVMeState;
44 /* Same index is used for queues and IRQs */
45 #define INDEX_ADMIN 0
46 #define INDEX_IO(n) (1 + n)
48 /* This driver shares a single MSIX IRQ for the admin and I/O queues */
49 enum {
50 MSIX_SHARED_IRQ_IDX = 0,
51 MSIX_IRQ_COUNT = 1
54 typedef 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;
62 typedef struct {
63 BlockCompletionFunc *cb;
64 void *opaque;
65 int cid;
66 void *prp_list_page;
67 uint64_t prp_list_iova;
68 int free_req_next; /* q->reqs[] index of next free req */
69 } NVMeRequest;
71 typedef struct {
72 QemuMutex lock;
74 /* Read from I/O code path, initialized under BQL */
75 BDRVNVMeState *s;
76 int index;
78 /* Fields protected by BQL */
79 uint8_t *prp_list_pages;
81 /* Fields protected by @lock */
82 CoQueue free_req_queue;
83 NVMeQueue sq, cq;
84 int cq_phase;
85 int free_req_head;
86 NVMeRequest reqs[NVME_NUM_REQS];
87 int need_kick;
88 int inflight;
90 /* Thread-safe, no lock necessary */
91 QEMUBH *completion_bh;
92 } NVMeQueuePair;
94 struct BDRVNVMeState {
95 AioContext *aio_context;
96 QEMUVFIOState *vfio;
97 /* Memory mapped registers */
98 volatile struct {
99 uint32_t sq_tail;
100 uint32_t cq_head;
101 } *doorbells;
102 /* The submission/completion queue pairs.
103 * [0]: admin queue.
104 * [1..]: io queues.
106 NVMeQueuePair **queues;
107 unsigned queue_count;
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;
112 EventNotifier irq_notifier[MSIX_IRQ_COUNT];
114 uint64_t nsze; /* Namespace size reported by identify command */
115 int nsid; /* The namespace id to read/write data. */
116 int blkshift;
118 uint64_t max_transfer;
119 bool plugged;
121 bool supports_write_zeroes;
122 bool supports_discard;
124 CoMutex dma_map_lock;
125 CoQueue dma_flush_queue;
127 /* Total size of mapped qiov, accessed under dma_map_lock */
128 int dma_map_count;
130 /* PCI address (required for nvme_refresh_filename()) */
131 char *device;
133 struct {
134 uint64_t completion_errors;
135 uint64_t aligned_accesses;
136 uint64_t unaligned_accesses;
137 } stats;
140 #define NVME_BLOCK_OPT_DEVICE "device"
141 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
143 static void nvme_process_completion_bh(void *opaque);
145 static QemuOptsList runtime_opts = {
146 .name = "nvme",
147 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
148 .desc = {
150 .name = NVME_BLOCK_OPT_DEVICE,
151 .type = QEMU_OPT_STRING,
152 .help = "NVMe PCI device address",
155 .name = NVME_BLOCK_OPT_NAMESPACE,
156 .type = QEMU_OPT_NUMBER,
157 .help = "NVMe namespace",
159 { /* end of list */ }
163 /* Returns true on success, false on failure. */
164 static bool nvme_init_queue(BDRVNVMeState *s, NVMeQueue *q,
165 unsigned nentries, size_t entry_bytes, Error **errp)
167 size_t bytes;
168 int r;
170 bytes = ROUND_UP(nentries * entry_bytes, s->page_size);
171 q->head = q->tail = 0;
172 q->queue = qemu_try_memalign(s->page_size, bytes);
173 if (!q->queue) {
174 error_setg(errp, "Cannot allocate queue");
175 return false;
177 memset(q->queue, 0, bytes);
178 r = qemu_vfio_dma_map(s->vfio, q->queue, bytes, false, &q->iova);
179 if (r) {
180 error_setg(errp, "Cannot map queue");
181 return false;
183 return true;
186 static void nvme_free_queue_pair(NVMeQueuePair *q)
188 trace_nvme_free_queue_pair(q->index, q);
189 if (q->completion_bh) {
190 qemu_bh_delete(q->completion_bh);
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);
199 static void nvme_free_req_queue_cb(void *opaque)
201 NVMeQueuePair *q = opaque;
203 qemu_mutex_lock(&q->lock);
204 while (qemu_co_enter_next(&q->free_req_queue, &q->lock)) {
205 /* Retry all pending requests */
207 qemu_mutex_unlock(&q->lock);
210 static NVMeQueuePair *nvme_create_queue_pair(BDRVNVMeState *s,
211 AioContext *aio_context,
212 unsigned idx, size_t size,
213 Error **errp)
215 int i, r;
216 NVMeQueuePair *q;
217 uint64_t prp_list_iova;
219 q = g_try_new0(NVMeQueuePair, 1);
220 if (!q) {
221 return NULL;
223 trace_nvme_create_queue_pair(idx, q, size, aio_context,
224 event_notifier_get_fd(s->irq_notifier));
225 q->prp_list_pages = qemu_try_memalign(s->page_size,
226 s->page_size * NVME_NUM_REQS);
227 if (!q->prp_list_pages) {
228 goto fail;
230 memset(q->prp_list_pages, 0, s->page_size * NVME_NUM_REQS);
231 qemu_mutex_init(&q->lock);
232 q->s = s;
233 q->index = idx;
234 qemu_co_queue_init(&q->free_req_queue);
235 q->completion_bh = aio_bh_new(aio_context, nvme_process_completion_bh, q);
236 r = qemu_vfio_dma_map(s->vfio, q->prp_list_pages,
237 s->page_size * NVME_NUM_REQS,
238 false, &prp_list_iova);
239 if (r) {
240 goto fail;
242 q->free_req_head = -1;
243 for (i = 0; i < NVME_NUM_REQS; i++) {
244 NVMeRequest *req = &q->reqs[i];
245 req->cid = i + 1;
246 req->free_req_next = q->free_req_head;
247 q->free_req_head = i;
248 req->prp_list_page = q->prp_list_pages + i * s->page_size;
249 req->prp_list_iova = prp_list_iova + i * s->page_size;
252 if (!nvme_init_queue(s, &q->sq, size, NVME_SQ_ENTRY_BYTES, errp)) {
253 goto fail;
255 q->sq.doorbell = &s->doorbells[idx * s->doorbell_scale].sq_tail;
257 if (!nvme_init_queue(s, &q->cq, size, NVME_CQ_ENTRY_BYTES, errp)) {
258 goto fail;
260 q->cq.doorbell = &s->doorbells[idx * s->doorbell_scale].cq_head;
262 return q;
263 fail:
264 nvme_free_queue_pair(q);
265 return NULL;
268 /* With q->lock */
269 static void nvme_kick(NVMeQueuePair *q)
271 BDRVNVMeState *s = q->s;
273 if (s->plugged || !q->need_kick) {
274 return;
276 trace_nvme_kick(s, q->index);
277 assert(!(q->sq.tail & 0xFF00));
278 /* Fence the write to submission queue entry before notifying the device. */
279 smp_wmb();
280 *q->sq.doorbell = cpu_to_le32(q->sq.tail);
281 q->inflight += q->need_kick;
282 q->need_kick = 0;
285 /* Find a free request element if any, otherwise:
286 * a) if in coroutine context, try to wait for one to become available;
287 * b) if not in coroutine, return NULL;
289 static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
291 NVMeRequest *req;
293 qemu_mutex_lock(&q->lock);
295 while (q->free_req_head == -1) {
296 if (qemu_in_coroutine()) {
297 trace_nvme_free_req_queue_wait(q->s, q->index);
298 qemu_co_queue_wait(&q->free_req_queue, &q->lock);
299 } else {
300 qemu_mutex_unlock(&q->lock);
301 return NULL;
305 req = &q->reqs[q->free_req_head];
306 q->free_req_head = req->free_req_next;
307 req->free_req_next = -1;
309 qemu_mutex_unlock(&q->lock);
310 return req;
313 /* With q->lock */
314 static void nvme_put_free_req_locked(NVMeQueuePair *q, NVMeRequest *req)
316 req->free_req_next = q->free_req_head;
317 q->free_req_head = req - q->reqs;
320 /* With q->lock */
321 static void nvme_wake_free_req_locked(NVMeQueuePair *q)
323 if (!qemu_co_queue_empty(&q->free_req_queue)) {
324 replay_bh_schedule_oneshot_event(q->s->aio_context,
325 nvme_free_req_queue_cb, q);
329 /* Insert a request in the freelist and wake waiters */
330 static void nvme_put_free_req_and_wake(NVMeQueuePair *q, NVMeRequest *req)
332 qemu_mutex_lock(&q->lock);
333 nvme_put_free_req_locked(q, req);
334 nvme_wake_free_req_locked(q);
335 qemu_mutex_unlock(&q->lock);
338 static inline int nvme_translate_error(const NvmeCqe *c)
340 uint16_t status = (le16_to_cpu(c->status) >> 1) & 0xFF;
341 if (status) {
342 trace_nvme_error(le32_to_cpu(c->result),
343 le16_to_cpu(c->sq_head),
344 le16_to_cpu(c->sq_id),
345 le16_to_cpu(c->cid),
346 le16_to_cpu(status));
348 switch (status) {
349 case 0:
350 return 0;
351 case 1:
352 return -ENOSYS;
353 case 2:
354 return -EINVAL;
355 default:
356 return -EIO;
360 /* With q->lock */
361 static bool nvme_process_completion(NVMeQueuePair *q)
363 BDRVNVMeState *s = q->s;
364 bool progress = false;
365 NVMeRequest *preq;
366 NVMeRequest req;
367 NvmeCqe *c;
369 trace_nvme_process_completion(s, q->index, q->inflight);
370 if (s->plugged) {
371 trace_nvme_process_completion_queue_plugged(s, q->index);
372 return false;
376 * Support re-entrancy when a request cb() function invokes aio_poll().
377 * Pending completions must be visible to aio_poll() so that a cb()
378 * function can wait for the completion of another request.
380 * The aio_poll() loop will execute our BH and we'll resume completion
381 * processing there.
383 qemu_bh_schedule(q->completion_bh);
385 assert(q->inflight >= 0);
386 while (q->inflight) {
387 int ret;
388 int16_t cid;
390 c = (NvmeCqe *)&q->cq.queue[q->cq.head * NVME_CQ_ENTRY_BYTES];
391 if ((le16_to_cpu(c->status) & 0x1) == q->cq_phase) {
392 break;
394 ret = nvme_translate_error(c);
395 if (ret) {
396 s->stats.completion_errors++;
398 q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
399 if (!q->cq.head) {
400 q->cq_phase = !q->cq_phase;
402 cid = le16_to_cpu(c->cid);
403 if (cid == 0 || cid > NVME_QUEUE_SIZE) {
404 warn_report("NVMe: Unexpected CID in completion queue: %"PRIu32", "
405 "queue size: %u", cid, NVME_QUEUE_SIZE);
406 continue;
408 trace_nvme_complete_command(s, q->index, cid);
409 preq = &q->reqs[cid - 1];
410 req = *preq;
411 assert(req.cid == cid);
412 assert(req.cb);
413 nvme_put_free_req_locked(q, preq);
414 preq->cb = preq->opaque = NULL;
415 q->inflight--;
416 qemu_mutex_unlock(&q->lock);
417 req.cb(req.opaque, ret);
418 qemu_mutex_lock(&q->lock);
419 progress = true;
421 if (progress) {
422 /* Notify the device so it can post more completions. */
423 smp_mb_release();
424 *q->cq.doorbell = cpu_to_le32(q->cq.head);
425 nvme_wake_free_req_locked(q);
428 qemu_bh_cancel(q->completion_bh);
430 return progress;
433 static void nvme_process_completion_bh(void *opaque)
435 NVMeQueuePair *q = opaque;
438 * We're being invoked because a nvme_process_completion() cb() function
439 * called aio_poll(). The callback may be waiting for further completions
440 * so notify the device that it has space to fill in more completions now.
442 smp_mb_release();
443 *q->cq.doorbell = cpu_to_le32(q->cq.head);
444 nvme_wake_free_req_locked(q);
446 nvme_process_completion(q);
449 static void nvme_trace_command(const NvmeCmd *cmd)
451 int i;
453 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW)) {
454 return;
456 for (i = 0; i < 8; ++i) {
457 uint8_t *cmdp = (uint8_t *)cmd + i * 8;
458 trace_nvme_submit_command_raw(cmdp[0], cmdp[1], cmdp[2], cmdp[3],
459 cmdp[4], cmdp[5], cmdp[6], cmdp[7]);
463 static void nvme_submit_command(NVMeQueuePair *q, NVMeRequest *req,
464 NvmeCmd *cmd, BlockCompletionFunc cb,
465 void *opaque)
467 assert(!req->cb);
468 req->cb = cb;
469 req->opaque = opaque;
470 cmd->cid = cpu_to_le32(req->cid);
472 trace_nvme_submit_command(q->s, q->index, req->cid);
473 nvme_trace_command(cmd);
474 qemu_mutex_lock(&q->lock);
475 memcpy((uint8_t *)q->sq.queue +
476 q->sq.tail * NVME_SQ_ENTRY_BYTES, cmd, sizeof(*cmd));
477 q->sq.tail = (q->sq.tail + 1) % NVME_QUEUE_SIZE;
478 q->need_kick++;
479 nvme_kick(q);
480 nvme_process_completion(q);
481 qemu_mutex_unlock(&q->lock);
484 static void nvme_admin_cmd_sync_cb(void *opaque, int ret)
486 int *pret = opaque;
487 *pret = ret;
488 aio_wait_kick();
491 static int nvme_admin_cmd_sync(BlockDriverState *bs, NvmeCmd *cmd)
493 BDRVNVMeState *s = bs->opaque;
494 NVMeQueuePair *q = s->queues[INDEX_ADMIN];
495 AioContext *aio_context = bdrv_get_aio_context(bs);
496 NVMeRequest *req;
497 int ret = -EINPROGRESS;
498 req = nvme_get_free_req(q);
499 if (!req) {
500 return -EBUSY;
502 nvme_submit_command(q, req, cmd, nvme_admin_cmd_sync_cb, &ret);
504 AIO_WAIT_WHILE(aio_context, ret == -EINPROGRESS);
505 return ret;
508 /* Returns true on success, false on failure. */
509 static bool nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
511 BDRVNVMeState *s = bs->opaque;
512 bool ret = false;
513 union {
514 NvmeIdCtrl ctrl;
515 NvmeIdNs ns;
516 } *id;
517 NvmeLBAF *lbaf;
518 uint16_t oncs;
519 int r;
520 uint64_t iova;
521 NvmeCmd cmd = {
522 .opcode = NVME_ADM_CMD_IDENTIFY,
523 .cdw10 = cpu_to_le32(0x1),
526 id = qemu_try_memalign(s->page_size, sizeof(*id));
527 if (!id) {
528 error_setg(errp, "Cannot allocate buffer for identify response");
529 goto out;
531 r = qemu_vfio_dma_map(s->vfio, id, sizeof(*id), true, &iova);
532 if (r) {
533 error_setg(errp, "Cannot map buffer for DMA");
534 goto out;
537 memset(id, 0, sizeof(*id));
538 cmd.dptr.prp1 = cpu_to_le64(iova);
539 if (nvme_admin_cmd_sync(bs, &cmd)) {
540 error_setg(errp, "Failed to identify controller");
541 goto out;
544 if (le32_to_cpu(id->ctrl.nn) < namespace) {
545 error_setg(errp, "Invalid namespace");
546 goto out;
548 s->write_cache_supported = le32_to_cpu(id->ctrl.vwc) & 0x1;
549 s->max_transfer = (id->ctrl.mdts ? 1 << id->ctrl.mdts : 0) * s->page_size;
550 /* For now the page list buffer per command is one page, to hold at most
551 * s->page_size / sizeof(uint64_t) entries. */
552 s->max_transfer = MIN_NON_ZERO(s->max_transfer,
553 s->page_size / sizeof(uint64_t) * s->page_size);
555 oncs = le16_to_cpu(id->ctrl.oncs);
556 s->supports_write_zeroes = !!(oncs & NVME_ONCS_WRITE_ZEROES);
557 s->supports_discard = !!(oncs & NVME_ONCS_DSM);
559 memset(id, 0, sizeof(*id));
560 cmd.cdw10 = 0;
561 cmd.nsid = cpu_to_le32(namespace);
562 if (nvme_admin_cmd_sync(bs, &cmd)) {
563 error_setg(errp, "Failed to identify namespace");
564 goto out;
567 s->nsze = le64_to_cpu(id->ns.nsze);
568 lbaf = &id->ns.lbaf[NVME_ID_NS_FLBAS_INDEX(id->ns.flbas)];
570 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id->ns.dlfeat) &&
571 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id->ns.dlfeat) ==
572 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES) {
573 bs->supported_write_flags |= BDRV_REQ_MAY_UNMAP;
576 if (lbaf->ms) {
577 error_setg(errp, "Namespaces with metadata are not yet supported");
578 goto out;
581 if (lbaf->ds < BDRV_SECTOR_BITS || lbaf->ds > 12 ||
582 (1 << lbaf->ds) > s->page_size)
584 error_setg(errp, "Namespace has unsupported block size (2^%d)",
585 lbaf->ds);
586 goto out;
589 ret = true;
590 s->blkshift = lbaf->ds;
591 out:
592 qemu_vfio_dma_unmap(s->vfio, id);
593 qemu_vfree(id);
595 return ret;
598 static bool nvme_poll_queue(NVMeQueuePair *q)
600 bool progress = false;
602 const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
603 NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
605 trace_nvme_poll_queue(q->s, q->index);
607 * Do an early check for completions. q->lock isn't needed because
608 * nvme_process_completion() only runs in the event loop thread and
609 * cannot race with itself.
611 if ((le16_to_cpu(cqe->status) & 0x1) == q->cq_phase) {
612 return false;
615 qemu_mutex_lock(&q->lock);
616 while (nvme_process_completion(q)) {
617 /* Keep polling */
618 progress = true;
620 qemu_mutex_unlock(&q->lock);
622 return progress;
625 static bool nvme_poll_queues(BDRVNVMeState *s)
627 bool progress = false;
628 int i;
630 for (i = 0; i < s->queue_count; i++) {
631 if (nvme_poll_queue(s->queues[i])) {
632 progress = true;
635 return progress;
638 static void nvme_handle_event(EventNotifier *n)
640 BDRVNVMeState *s = container_of(n, BDRVNVMeState,
641 irq_notifier[MSIX_SHARED_IRQ_IDX]);
643 trace_nvme_handle_event(s);
644 event_notifier_test_and_clear(n);
645 nvme_poll_queues(s);
648 static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
650 BDRVNVMeState *s = bs->opaque;
651 unsigned n = s->queue_count;
652 NVMeQueuePair *q;
653 NvmeCmd cmd;
654 unsigned queue_size = NVME_QUEUE_SIZE;
656 assert(n <= UINT16_MAX);
657 q = nvme_create_queue_pair(s, bdrv_get_aio_context(bs),
658 n, queue_size, errp);
659 if (!q) {
660 return false;
662 cmd = (NvmeCmd) {
663 .opcode = NVME_ADM_CMD_CREATE_CQ,
664 .dptr.prp1 = cpu_to_le64(q->cq.iova),
665 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
666 .cdw11 = cpu_to_le32(NVME_CQ_IEN | NVME_CQ_PC),
668 if (nvme_admin_cmd_sync(bs, &cmd)) {
669 error_setg(errp, "Failed to create CQ io queue [%u]", n);
670 goto out_error;
672 cmd = (NvmeCmd) {
673 .opcode = NVME_ADM_CMD_CREATE_SQ,
674 .dptr.prp1 = cpu_to_le64(q->sq.iova),
675 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
676 .cdw11 = cpu_to_le32(NVME_SQ_PC | (n << 16)),
678 if (nvme_admin_cmd_sync(bs, &cmd)) {
679 error_setg(errp, "Failed to create SQ io queue [%u]", n);
680 goto out_error;
682 s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
683 s->queues[n] = q;
684 s->queue_count++;
685 return true;
686 out_error:
687 nvme_free_queue_pair(q);
688 return false;
691 static bool nvme_poll_cb(void *opaque)
693 EventNotifier *e = opaque;
694 BDRVNVMeState *s = container_of(e, BDRVNVMeState,
695 irq_notifier[MSIX_SHARED_IRQ_IDX]);
697 return nvme_poll_queues(s);
700 static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
701 Error **errp)
703 BDRVNVMeState *s = bs->opaque;
704 NVMeQueuePair *q;
705 AioContext *aio_context = bdrv_get_aio_context(bs);
706 int ret;
707 uint64_t cap;
708 uint64_t timeout_ms;
709 uint64_t deadline, now;
710 volatile NvmeBar *regs = NULL;
712 qemu_co_mutex_init(&s->dma_map_lock);
713 qemu_co_queue_init(&s->dma_flush_queue);
714 s->device = g_strdup(device);
715 s->nsid = namespace;
716 s->aio_context = bdrv_get_aio_context(bs);
717 ret = event_notifier_init(&s->irq_notifier[MSIX_SHARED_IRQ_IDX], 0);
718 if (ret) {
719 error_setg(errp, "Failed to init event notifier");
720 return ret;
723 s->vfio = qemu_vfio_open_pci(device, errp);
724 if (!s->vfio) {
725 ret = -EINVAL;
726 goto out;
729 regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, sizeof(NvmeBar),
730 PROT_READ | PROT_WRITE, errp);
731 if (!regs) {
732 ret = -EINVAL;
733 goto out;
735 /* Perform initialize sequence as described in NVMe spec "7.6.1
736 * Initialization". */
738 cap = le64_to_cpu(regs->cap);
739 trace_nvme_controller_capability_raw(cap);
740 trace_nvme_controller_capability("Maximum Queue Entries Supported",
741 1 + NVME_CAP_MQES(cap));
742 trace_nvme_controller_capability("Contiguous Queues Required",
743 NVME_CAP_CQR(cap));
744 trace_nvme_controller_capability("Doorbell Stride",
745 2 << (2 + NVME_CAP_DSTRD(cap)));
746 trace_nvme_controller_capability("Subsystem Reset Supported",
747 NVME_CAP_NSSRS(cap));
748 trace_nvme_controller_capability("Memory Page Size Minimum",
749 1 << (12 + NVME_CAP_MPSMIN(cap)));
750 trace_nvme_controller_capability("Memory Page Size Maximum",
751 1 << (12 + NVME_CAP_MPSMAX(cap)));
752 if (!NVME_CAP_CSS(cap)) {
753 error_setg(errp, "Device doesn't support NVMe command set");
754 ret = -EINVAL;
755 goto out;
758 s->page_size = MAX(4096, 1 << NVME_CAP_MPSMIN(cap));
759 s->doorbell_scale = (4 << NVME_CAP_DSTRD(cap)) / sizeof(uint32_t);
760 bs->bl.opt_mem_alignment = s->page_size;
761 timeout_ms = MIN(500 * NVME_CAP_TO(cap), 30000);
763 /* Reset device to get a clean state. */
764 regs->cc = cpu_to_le32(le32_to_cpu(regs->cc) & 0xFE);
765 /* Wait for CSTS.RDY = 0. */
766 deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * SCALE_MS;
767 while (NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
768 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
769 error_setg(errp, "Timeout while waiting for device to reset (%"
770 PRId64 " ms)",
771 timeout_ms);
772 ret = -ETIMEDOUT;
773 goto out;
777 s->doorbells = qemu_vfio_pci_map_bar(s->vfio, 0, sizeof(NvmeBar),
778 NVME_DOORBELL_SIZE, PROT_WRITE, errp);
779 if (!s->doorbells) {
780 ret = -EINVAL;
781 goto out;
784 /* Set up admin queue. */
785 s->queues = g_new(NVMeQueuePair *, 1);
786 q = nvme_create_queue_pair(s, aio_context, 0, NVME_QUEUE_SIZE, errp);
787 if (!q) {
788 ret = -EINVAL;
789 goto out;
791 s->queues[INDEX_ADMIN] = q;
792 s->queue_count = 1;
793 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE - 1) & 0xF000);
794 regs->aqa = cpu_to_le32(((NVME_QUEUE_SIZE - 1) << AQA_ACQS_SHIFT) |
795 ((NVME_QUEUE_SIZE - 1) << AQA_ASQS_SHIFT));
796 regs->asq = cpu_to_le64(q->sq.iova);
797 regs->acq = cpu_to_le64(q->cq.iova);
799 /* After setting up all control registers we can enable device now. */
800 regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << CC_IOCQES_SHIFT) |
801 (ctz32(NVME_SQ_ENTRY_BYTES) << CC_IOSQES_SHIFT) |
802 CC_EN_MASK);
803 /* Wait for CSTS.RDY = 1. */
804 now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
805 deadline = now + timeout_ms * SCALE_MS;
806 while (!NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
807 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
808 error_setg(errp, "Timeout while waiting for device to start (%"
809 PRId64 " ms)",
810 timeout_ms);
811 ret = -ETIMEDOUT;
812 goto out;
816 ret = qemu_vfio_pci_init_irq(s->vfio, s->irq_notifier,
817 VFIO_PCI_MSIX_IRQ_INDEX, errp);
818 if (ret) {
819 goto out;
821 aio_set_event_notifier(bdrv_get_aio_context(bs),
822 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
823 false, nvme_handle_event, nvme_poll_cb);
825 if (!nvme_identify(bs, namespace, errp)) {
826 ret = -EIO;
827 goto out;
830 /* Set up command queues. */
831 if (!nvme_add_io_queue(bs, errp)) {
832 ret = -EIO;
834 out:
835 if (regs) {
836 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)regs, 0, sizeof(NvmeBar));
839 /* Cleaning up is done in nvme_file_open() upon error. */
840 return ret;
843 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
845 * nvme://0000:44:00.0/1
847 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
848 * is the PCI address, and the last part is the namespace number starting from
849 * 1 according to the NVMe spec. */
850 static void nvme_parse_filename(const char *filename, QDict *options,
851 Error **errp)
853 int pref = strlen("nvme://");
855 if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
856 const char *tmp = filename + pref;
857 char *device;
858 const char *namespace;
859 unsigned long ns;
860 const char *slash = strchr(tmp, '/');
861 if (!slash) {
862 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
863 return;
865 device = g_strndup(tmp, slash - tmp);
866 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
867 g_free(device);
868 namespace = slash + 1;
869 if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
870 error_setg(errp, "Invalid namespace '%s', positive number expected",
871 namespace);
872 return;
874 qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
875 *namespace ? namespace : "1");
879 static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
880 Error **errp)
882 int ret;
883 BDRVNVMeState *s = bs->opaque;
884 NvmeCmd cmd = {
885 .opcode = NVME_ADM_CMD_SET_FEATURES,
886 .nsid = cpu_to_le32(s->nsid),
887 .cdw10 = cpu_to_le32(0x06),
888 .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
891 ret = nvme_admin_cmd_sync(bs, &cmd);
892 if (ret) {
893 error_setg(errp, "Failed to configure NVMe write cache");
895 return ret;
898 static void nvme_close(BlockDriverState *bs)
900 BDRVNVMeState *s = bs->opaque;
902 for (unsigned i = 0; i < s->queue_count; ++i) {
903 nvme_free_queue_pair(s->queues[i]);
905 g_free(s->queues);
906 aio_set_event_notifier(bdrv_get_aio_context(bs),
907 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
908 false, NULL, NULL);
909 event_notifier_cleanup(&s->irq_notifier[MSIX_SHARED_IRQ_IDX]);
910 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)s->doorbells,
911 sizeof(NvmeBar), NVME_DOORBELL_SIZE);
912 qemu_vfio_close(s->vfio);
914 g_free(s->device);
917 static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
918 Error **errp)
920 const char *device;
921 QemuOpts *opts;
922 int namespace;
923 int ret;
924 BDRVNVMeState *s = bs->opaque;
926 bs->supported_write_flags = BDRV_REQ_FUA;
928 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
929 qemu_opts_absorb_qdict(opts, options, &error_abort);
930 device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
931 if (!device) {
932 error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
933 qemu_opts_del(opts);
934 return -EINVAL;
937 namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
938 ret = nvme_init(bs, device, namespace, errp);
939 qemu_opts_del(opts);
940 if (ret) {
941 goto fail;
943 if (flags & BDRV_O_NOCACHE) {
944 if (!s->write_cache_supported) {
945 error_setg(errp,
946 "NVMe controller doesn't support write cache configuration");
947 ret = -EINVAL;
948 } else {
949 ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
950 errp);
952 if (ret) {
953 goto fail;
956 return 0;
957 fail:
958 nvme_close(bs);
959 return ret;
962 static int64_t nvme_getlength(BlockDriverState *bs)
964 BDRVNVMeState *s = bs->opaque;
965 return s->nsze << s->blkshift;
968 static uint32_t nvme_get_blocksize(BlockDriverState *bs)
970 BDRVNVMeState *s = bs->opaque;
971 assert(s->blkshift >= BDRV_SECTOR_BITS && s->blkshift <= 12);
972 return UINT32_C(1) << s->blkshift;
975 static int nvme_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
977 uint32_t blocksize = nvme_get_blocksize(bs);
978 bsz->phys = blocksize;
979 bsz->log = blocksize;
980 return 0;
983 /* Called with s->dma_map_lock */
984 static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
985 QEMUIOVector *qiov)
987 int r = 0;
988 BDRVNVMeState *s = bs->opaque;
990 s->dma_map_count -= qiov->size;
991 if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
992 r = qemu_vfio_dma_reset_temporary(s->vfio);
993 if (!r) {
994 qemu_co_queue_restart_all(&s->dma_flush_queue);
997 return r;
1000 /* Called with s->dma_map_lock */
1001 static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
1002 NVMeRequest *req, QEMUIOVector *qiov)
1004 BDRVNVMeState *s = bs->opaque;
1005 uint64_t *pagelist = req->prp_list_page;
1006 int i, j, r;
1007 int entries = 0;
1009 assert(qiov->size);
1010 assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
1011 assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
1012 for (i = 0; i < qiov->niov; ++i) {
1013 bool retry = true;
1014 uint64_t iova;
1015 try_map:
1016 r = qemu_vfio_dma_map(s->vfio,
1017 qiov->iov[i].iov_base,
1018 qiov->iov[i].iov_len,
1019 true, &iova);
1020 if (r == -ENOMEM && retry) {
1021 retry = false;
1022 trace_nvme_dma_flush_queue_wait(s);
1023 if (s->dma_map_count) {
1024 trace_nvme_dma_map_flush(s);
1025 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
1026 } else {
1027 r = qemu_vfio_dma_reset_temporary(s->vfio);
1028 if (r) {
1029 goto fail;
1032 goto try_map;
1034 if (r) {
1035 goto fail;
1038 for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
1039 pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
1041 trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
1042 qiov->iov[i].iov_len / s->page_size);
1045 s->dma_map_count += qiov->size;
1047 assert(entries <= s->page_size / sizeof(uint64_t));
1048 switch (entries) {
1049 case 0:
1050 abort();
1051 case 1:
1052 cmd->dptr.prp1 = pagelist[0];
1053 cmd->dptr.prp2 = 0;
1054 break;
1055 case 2:
1056 cmd->dptr.prp1 = pagelist[0];
1057 cmd->dptr.prp2 = pagelist[1];
1058 break;
1059 default:
1060 cmd->dptr.prp1 = pagelist[0];
1061 cmd->dptr.prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
1062 break;
1064 trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
1065 for (i = 0; i < entries; ++i) {
1066 trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
1068 return 0;
1069 fail:
1070 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1071 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1072 * because they are already mapped before calling this function; for
1073 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1074 * calling qemu_vfio_dma_reset_temporary when necessary. */
1075 return r;
1078 typedef struct {
1079 Coroutine *co;
1080 int ret;
1081 AioContext *ctx;
1082 } NVMeCoData;
1084 static void nvme_rw_cb_bh(void *opaque)
1086 NVMeCoData *data = opaque;
1087 qemu_coroutine_enter(data->co);
1090 static void nvme_rw_cb(void *opaque, int ret)
1092 NVMeCoData *data = opaque;
1093 data->ret = ret;
1094 if (!data->co) {
1095 /* The rw coroutine hasn't yielded, don't try to enter. */
1096 return;
1098 replay_bh_schedule_oneshot_event(data->ctx, nvme_rw_cb_bh, data);
1101 static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
1102 uint64_t offset, uint64_t bytes,
1103 QEMUIOVector *qiov,
1104 bool is_write,
1105 int flags)
1107 int r;
1108 BDRVNVMeState *s = bs->opaque;
1109 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1110 NVMeRequest *req;
1112 uint32_t cdw12 = (((bytes >> s->blkshift) - 1) & 0xFFFF) |
1113 (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
1114 NvmeCmd cmd = {
1115 .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
1116 .nsid = cpu_to_le32(s->nsid),
1117 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1118 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1119 .cdw12 = cpu_to_le32(cdw12),
1121 NVMeCoData data = {
1122 .ctx = bdrv_get_aio_context(bs),
1123 .ret = -EINPROGRESS,
1126 trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
1127 assert(s->queue_count > 1);
1128 req = nvme_get_free_req(ioq);
1129 assert(req);
1131 qemu_co_mutex_lock(&s->dma_map_lock);
1132 r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
1133 qemu_co_mutex_unlock(&s->dma_map_lock);
1134 if (r) {
1135 nvme_put_free_req_and_wake(ioq, req);
1136 return r;
1138 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1140 data.co = qemu_coroutine_self();
1141 while (data.ret == -EINPROGRESS) {
1142 qemu_coroutine_yield();
1145 qemu_co_mutex_lock(&s->dma_map_lock);
1146 r = nvme_cmd_unmap_qiov(bs, qiov);
1147 qemu_co_mutex_unlock(&s->dma_map_lock);
1148 if (r) {
1149 return r;
1152 trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
1153 return data.ret;
1156 static inline bool nvme_qiov_aligned(BlockDriverState *bs,
1157 const QEMUIOVector *qiov)
1159 int i;
1160 BDRVNVMeState *s = bs->opaque;
1162 for (i = 0; i < qiov->niov; ++i) {
1163 if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base, s->page_size) ||
1164 !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, s->page_size)) {
1165 trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
1166 qiov->iov[i].iov_len, s->page_size);
1167 return false;
1170 return true;
1173 static int nvme_co_prw(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1174 QEMUIOVector *qiov, bool is_write, int flags)
1176 BDRVNVMeState *s = bs->opaque;
1177 int r;
1178 uint8_t *buf = NULL;
1179 QEMUIOVector local_qiov;
1181 assert(QEMU_IS_ALIGNED(offset, s->page_size));
1182 assert(QEMU_IS_ALIGNED(bytes, s->page_size));
1183 assert(bytes <= s->max_transfer);
1184 if (nvme_qiov_aligned(bs, qiov)) {
1185 s->stats.aligned_accesses++;
1186 return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
1188 s->stats.unaligned_accesses++;
1189 trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
1190 buf = qemu_try_memalign(s->page_size, bytes);
1192 if (!buf) {
1193 return -ENOMEM;
1195 qemu_iovec_init(&local_qiov, 1);
1196 if (is_write) {
1197 qemu_iovec_to_buf(qiov, 0, buf, bytes);
1199 qemu_iovec_add(&local_qiov, buf, bytes);
1200 r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
1201 qemu_iovec_destroy(&local_qiov);
1202 if (!r && !is_write) {
1203 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1205 qemu_vfree(buf);
1206 return r;
1209 static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1210 uint64_t offset, uint64_t bytes,
1211 QEMUIOVector *qiov, int flags)
1213 return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1216 static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1217 uint64_t offset, uint64_t bytes,
1218 QEMUIOVector *qiov, int flags)
1220 return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1223 static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1225 BDRVNVMeState *s = bs->opaque;
1226 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1227 NVMeRequest *req;
1228 NvmeCmd cmd = {
1229 .opcode = NVME_CMD_FLUSH,
1230 .nsid = cpu_to_le32(s->nsid),
1232 NVMeCoData data = {
1233 .ctx = bdrv_get_aio_context(bs),
1234 .ret = -EINPROGRESS,
1237 assert(s->queue_count > 1);
1238 req = nvme_get_free_req(ioq);
1239 assert(req);
1240 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1242 data.co = qemu_coroutine_self();
1243 if (data.ret == -EINPROGRESS) {
1244 qemu_coroutine_yield();
1247 return data.ret;
1251 static coroutine_fn int nvme_co_pwrite_zeroes(BlockDriverState *bs,
1252 int64_t offset,
1253 int bytes,
1254 BdrvRequestFlags flags)
1256 BDRVNVMeState *s = bs->opaque;
1257 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1258 NVMeRequest *req;
1260 uint32_t cdw12 = ((bytes >> s->blkshift) - 1) & 0xFFFF;
1262 if (!s->supports_write_zeroes) {
1263 return -ENOTSUP;
1266 NvmeCmd cmd = {
1267 .opcode = NVME_CMD_WRITE_ZEROES,
1268 .nsid = cpu_to_le32(s->nsid),
1269 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1270 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1273 NVMeCoData data = {
1274 .ctx = bdrv_get_aio_context(bs),
1275 .ret = -EINPROGRESS,
1278 if (flags & BDRV_REQ_MAY_UNMAP) {
1279 cdw12 |= (1 << 25);
1282 if (flags & BDRV_REQ_FUA) {
1283 cdw12 |= (1 << 30);
1286 cmd.cdw12 = cpu_to_le32(cdw12);
1288 trace_nvme_write_zeroes(s, offset, bytes, flags);
1289 assert(s->queue_count > 1);
1290 req = nvme_get_free_req(ioq);
1291 assert(req);
1293 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1295 data.co = qemu_coroutine_self();
1296 while (data.ret == -EINPROGRESS) {
1297 qemu_coroutine_yield();
1300 trace_nvme_rw_done(s, true, offset, bytes, data.ret);
1301 return data.ret;
1305 static int coroutine_fn nvme_co_pdiscard(BlockDriverState *bs,
1306 int64_t offset,
1307 int bytes)
1309 BDRVNVMeState *s = bs->opaque;
1310 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1311 NVMeRequest *req;
1312 NvmeDsmRange *buf;
1313 QEMUIOVector local_qiov;
1314 int ret;
1316 NvmeCmd cmd = {
1317 .opcode = NVME_CMD_DSM,
1318 .nsid = cpu_to_le32(s->nsid),
1319 .cdw10 = cpu_to_le32(0), /*number of ranges - 0 based*/
1320 .cdw11 = cpu_to_le32(1 << 2), /*deallocate bit*/
1323 NVMeCoData data = {
1324 .ctx = bdrv_get_aio_context(bs),
1325 .ret = -EINPROGRESS,
1328 if (!s->supports_discard) {
1329 return -ENOTSUP;
1332 assert(s->queue_count > 1);
1334 buf = qemu_try_memalign(s->page_size, s->page_size);
1335 if (!buf) {
1336 return -ENOMEM;
1338 memset(buf, 0, s->page_size);
1339 buf->nlb = cpu_to_le32(bytes >> s->blkshift);
1340 buf->slba = cpu_to_le64(offset >> s->blkshift);
1341 buf->cattr = 0;
1343 qemu_iovec_init(&local_qiov, 1);
1344 qemu_iovec_add(&local_qiov, buf, 4096);
1346 req = nvme_get_free_req(ioq);
1347 assert(req);
1349 qemu_co_mutex_lock(&s->dma_map_lock);
1350 ret = nvme_cmd_map_qiov(bs, &cmd, req, &local_qiov);
1351 qemu_co_mutex_unlock(&s->dma_map_lock);
1353 if (ret) {
1354 nvme_put_free_req_and_wake(ioq, req);
1355 goto out;
1358 trace_nvme_dsm(s, offset, bytes);
1360 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1362 data.co = qemu_coroutine_self();
1363 while (data.ret == -EINPROGRESS) {
1364 qemu_coroutine_yield();
1367 qemu_co_mutex_lock(&s->dma_map_lock);
1368 ret = nvme_cmd_unmap_qiov(bs, &local_qiov);
1369 qemu_co_mutex_unlock(&s->dma_map_lock);
1371 if (ret) {
1372 goto out;
1375 ret = data.ret;
1376 trace_nvme_dsm_done(s, offset, bytes, ret);
1377 out:
1378 qemu_iovec_destroy(&local_qiov);
1379 qemu_vfree(buf);
1380 return ret;
1385 static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1386 BlockReopenQueue *queue, Error **errp)
1388 return 0;
1391 static void nvme_refresh_filename(BlockDriverState *bs)
1393 BDRVNVMeState *s = bs->opaque;
1395 snprintf(bs->exact_filename, sizeof(bs->exact_filename), "nvme://%s/%i",
1396 s->device, s->nsid);
1399 static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1401 BDRVNVMeState *s = bs->opaque;
1403 bs->bl.opt_mem_alignment = s->page_size;
1404 bs->bl.request_alignment = s->page_size;
1405 bs->bl.max_transfer = s->max_transfer;
1408 static void nvme_detach_aio_context(BlockDriverState *bs)
1410 BDRVNVMeState *s = bs->opaque;
1412 for (unsigned i = 0; i < s->queue_count; i++) {
1413 NVMeQueuePair *q = s->queues[i];
1415 qemu_bh_delete(q->completion_bh);
1416 q->completion_bh = NULL;
1419 aio_set_event_notifier(bdrv_get_aio_context(bs),
1420 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1421 false, NULL, NULL);
1424 static void nvme_attach_aio_context(BlockDriverState *bs,
1425 AioContext *new_context)
1427 BDRVNVMeState *s = bs->opaque;
1429 s->aio_context = new_context;
1430 aio_set_event_notifier(new_context, &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1431 false, nvme_handle_event, nvme_poll_cb);
1433 for (unsigned i = 0; i < s->queue_count; i++) {
1434 NVMeQueuePair *q = s->queues[i];
1436 q->completion_bh =
1437 aio_bh_new(new_context, nvme_process_completion_bh, q);
1441 static void nvme_aio_plug(BlockDriverState *bs)
1443 BDRVNVMeState *s = bs->opaque;
1444 assert(!s->plugged);
1445 s->plugged = true;
1448 static void nvme_aio_unplug(BlockDriverState *bs)
1450 BDRVNVMeState *s = bs->opaque;
1451 assert(s->plugged);
1452 s->plugged = false;
1453 for (unsigned i = INDEX_IO(0); i < s->queue_count; i++) {
1454 NVMeQueuePair *q = s->queues[i];
1455 qemu_mutex_lock(&q->lock);
1456 nvme_kick(q);
1457 nvme_process_completion(q);
1458 qemu_mutex_unlock(&q->lock);
1462 static void nvme_register_buf(BlockDriverState *bs, void *host, size_t size)
1464 int ret;
1465 BDRVNVMeState *s = bs->opaque;
1467 ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL);
1468 if (ret) {
1469 /* FIXME: we may run out of IOVA addresses after repeated
1470 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1471 * doesn't reclaim addresses for fixed mappings. */
1472 error_report("nvme_register_buf failed: %s", strerror(-ret));
1476 static void nvme_unregister_buf(BlockDriverState *bs, void *host)
1478 BDRVNVMeState *s = bs->opaque;
1480 qemu_vfio_dma_unmap(s->vfio, host);
1483 static BlockStatsSpecific *nvme_get_specific_stats(BlockDriverState *bs)
1485 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
1486 BDRVNVMeState *s = bs->opaque;
1488 stats->driver = BLOCKDEV_DRIVER_NVME;
1489 stats->u.nvme = (BlockStatsSpecificNvme) {
1490 .completion_errors = s->stats.completion_errors,
1491 .aligned_accesses = s->stats.aligned_accesses,
1492 .unaligned_accesses = s->stats.unaligned_accesses,
1495 return stats;
1498 static const char *const nvme_strong_runtime_opts[] = {
1499 NVME_BLOCK_OPT_DEVICE,
1500 NVME_BLOCK_OPT_NAMESPACE,
1502 NULL
1505 static BlockDriver bdrv_nvme = {
1506 .format_name = "nvme",
1507 .protocol_name = "nvme",
1508 .instance_size = sizeof(BDRVNVMeState),
1510 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
1511 .create_opts = &bdrv_create_opts_simple,
1513 .bdrv_parse_filename = nvme_parse_filename,
1514 .bdrv_file_open = nvme_file_open,
1515 .bdrv_close = nvme_close,
1516 .bdrv_getlength = nvme_getlength,
1517 .bdrv_probe_blocksizes = nvme_probe_blocksizes,
1519 .bdrv_co_preadv = nvme_co_preadv,
1520 .bdrv_co_pwritev = nvme_co_pwritev,
1522 .bdrv_co_pwrite_zeroes = nvme_co_pwrite_zeroes,
1523 .bdrv_co_pdiscard = nvme_co_pdiscard,
1525 .bdrv_co_flush_to_disk = nvme_co_flush,
1526 .bdrv_reopen_prepare = nvme_reopen_prepare,
1528 .bdrv_refresh_filename = nvme_refresh_filename,
1529 .bdrv_refresh_limits = nvme_refresh_limits,
1530 .strong_runtime_opts = nvme_strong_runtime_opts,
1531 .bdrv_get_specific_stats = nvme_get_specific_stats,
1533 .bdrv_detach_aio_context = nvme_detach_aio_context,
1534 .bdrv_attach_aio_context = nvme_attach_aio_context,
1536 .bdrv_io_plug = nvme_aio_plug,
1537 .bdrv_io_unplug = nvme_aio_unplug,
1539 .bdrv_register_buf = nvme_register_buf,
1540 .bdrv_unregister_buf = nvme_unregister_buf,
1543 static void bdrv_nvme_init(void)
1545 bdrv_register(&bdrv_nvme);
1548 block_init(bdrv_nvme_init);