2 * NVMe block driver based on vfio
4 * Copyright 2016 - 2018 Red Hat, Inc.
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"
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
40 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
42 typedef struct BDRVNVMeState BDRVNVMeState
;
48 /* Hardware MMIO register */
49 volatile uint32_t *doorbell
;
53 BlockCompletionFunc
*cb
;
57 uint64_t prp_list_iova
;
58 int free_req_next
; /* q->reqs[] index of next free req */
64 /* Read from I/O code path, initialized under BQL */
68 /* Fields protected by BQL */
69 uint8_t *prp_list_pages
;
71 /* Fields protected by @lock */
72 CoQueue free_req_queue
;
76 NVMeRequest reqs
[NVME_NUM_REQS
];
80 /* Thread-safe, no lock necessary */
81 QEMUBH
*completion_bh
;
85 #define INDEX_IO(n) (1 + n)
87 /* This driver shares a single MSIX IRQ for the admin and I/O queues */
89 MSIX_SHARED_IRQ_IDX
= 0,
93 struct BDRVNVMeState
{
94 AioContext
*aio_context
;
96 /* Memory mapped registers */
101 /* The submission/completion queue pairs.
105 NVMeQueuePair
**queues
;
108 /* How many uint32_t elements does each doorbell entry take. */
109 size_t doorbell_scale
;
110 bool write_cache_supported
;
111 EventNotifier irq_notifier
[MSIX_IRQ_COUNT
];
113 uint64_t nsze
; /* Namespace size reported by identify command */
114 int nsid
; /* The namespace id to read/write data. */
117 uint64_t max_transfer
;
120 bool supports_write_zeroes
;
121 bool supports_discard
;
123 CoMutex dma_map_lock
;
124 CoQueue dma_flush_queue
;
126 /* Total size of mapped qiov, accessed under dma_map_lock */
129 /* PCI address (required for nvme_refresh_filename()) */
133 #define NVME_BLOCK_OPT_DEVICE "device"
134 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
136 static void nvme_process_completion_bh(void *opaque
);
138 static QemuOptsList runtime_opts
= {
140 .head
= QTAILQ_HEAD_INITIALIZER(runtime_opts
.head
),
143 .name
= NVME_BLOCK_OPT_DEVICE
,
144 .type
= QEMU_OPT_STRING
,
145 .help
= "NVMe PCI device address",
148 .name
= NVME_BLOCK_OPT_NAMESPACE
,
149 .type
= QEMU_OPT_NUMBER
,
150 .help
= "NVMe namespace",
152 { /* end of list */ }
156 static void nvme_init_queue(BDRVNVMeState
*s
, NVMeQueue
*q
,
157 int nentries
, int entry_bytes
, Error
**errp
)
162 bytes
= ROUND_UP(nentries
* entry_bytes
, s
->page_size
);
163 q
->head
= q
->tail
= 0;
164 q
->queue
= qemu_try_memalign(s
->page_size
, bytes
);
166 error_setg(errp
, "Cannot allocate queue");
169 memset(q
->queue
, 0, bytes
);
170 r
= qemu_vfio_dma_map(s
->vfio
, q
->queue
, bytes
, false, &q
->iova
);
172 error_setg(errp
, "Cannot map queue");
176 static void nvme_free_queue_pair(NVMeQueuePair
*q
)
178 if (q
->completion_bh
) {
179 qemu_bh_delete(q
->completion_bh
);
181 qemu_vfree(q
->prp_list_pages
);
182 qemu_vfree(q
->sq
.queue
);
183 qemu_vfree(q
->cq
.queue
);
184 qemu_mutex_destroy(&q
->lock
);
188 static void nvme_free_req_queue_cb(void *opaque
)
190 NVMeQueuePair
*q
= opaque
;
192 qemu_mutex_lock(&q
->lock
);
193 while (qemu_co_enter_next(&q
->free_req_queue
, &q
->lock
)) {
194 /* Retry all pending requests */
196 qemu_mutex_unlock(&q
->lock
);
199 static NVMeQueuePair
*nvme_create_queue_pair(BDRVNVMeState
*s
,
200 AioContext
*aio_context
,
205 Error
*local_err
= NULL
;
207 uint64_t prp_list_iova
;
209 q
= g_try_new0(NVMeQueuePair
, 1);
213 q
->prp_list_pages
= qemu_try_memalign(s
->page_size
,
214 s
->page_size
* NVME_NUM_REQS
);
215 if (!q
->prp_list_pages
) {
218 memset(q
->prp_list_pages
, 0, s
->page_size
* NVME_NUM_REQS
);
219 qemu_mutex_init(&q
->lock
);
222 qemu_co_queue_init(&q
->free_req_queue
);
223 q
->completion_bh
= aio_bh_new(aio_context
, nvme_process_completion_bh
, q
);
224 r
= qemu_vfio_dma_map(s
->vfio
, q
->prp_list_pages
,
225 s
->page_size
* NVME_NUM_REQS
,
226 false, &prp_list_iova
);
230 q
->free_req_head
= -1;
231 for (i
= 0; i
< NVME_NUM_REQS
; i
++) {
232 NVMeRequest
*req
= &q
->reqs
[i
];
234 req
->free_req_next
= q
->free_req_head
;
235 q
->free_req_head
= i
;
236 req
->prp_list_page
= q
->prp_list_pages
+ i
* s
->page_size
;
237 req
->prp_list_iova
= prp_list_iova
+ i
* s
->page_size
;
240 nvme_init_queue(s
, &q
->sq
, size
, NVME_SQ_ENTRY_BYTES
, &local_err
);
242 error_propagate(errp
, local_err
);
245 q
->sq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].sq_tail
;
247 nvme_init_queue(s
, &q
->cq
, size
, NVME_CQ_ENTRY_BYTES
, &local_err
);
249 error_propagate(errp
, local_err
);
252 q
->cq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].cq_head
;
256 nvme_free_queue_pair(q
);
261 static void nvme_kick(NVMeQueuePair
*q
)
263 BDRVNVMeState
*s
= q
->s
;
265 if (s
->plugged
|| !q
->need_kick
) {
268 trace_nvme_kick(s
, q
->index
);
269 assert(!(q
->sq
.tail
& 0xFF00));
270 /* Fence the write to submission queue entry before notifying the device. */
272 *q
->sq
.doorbell
= cpu_to_le32(q
->sq
.tail
);
273 q
->inflight
+= q
->need_kick
;
277 /* Find a free request element if any, otherwise:
278 * a) if in coroutine context, try to wait for one to become available;
279 * b) if not in coroutine, return NULL;
281 static NVMeRequest
*nvme_get_free_req(NVMeQueuePair
*q
)
285 qemu_mutex_lock(&q
->lock
);
287 while (q
->free_req_head
== -1) {
288 if (qemu_in_coroutine()) {
289 trace_nvme_free_req_queue_wait(q
);
290 qemu_co_queue_wait(&q
->free_req_queue
, &q
->lock
);
292 qemu_mutex_unlock(&q
->lock
);
297 req
= &q
->reqs
[q
->free_req_head
];
298 q
->free_req_head
= req
->free_req_next
;
299 req
->free_req_next
= -1;
301 qemu_mutex_unlock(&q
->lock
);
306 static void nvme_put_free_req_locked(NVMeQueuePair
*q
, NVMeRequest
*req
)
308 req
->free_req_next
= q
->free_req_head
;
309 q
->free_req_head
= req
- q
->reqs
;
313 static void nvme_wake_free_req_locked(NVMeQueuePair
*q
)
315 if (!qemu_co_queue_empty(&q
->free_req_queue
)) {
316 replay_bh_schedule_oneshot_event(q
->s
->aio_context
,
317 nvme_free_req_queue_cb
, q
);
321 /* Insert a request in the freelist and wake waiters */
322 static void nvme_put_free_req_and_wake(NVMeQueuePair
*q
, NVMeRequest
*req
)
324 qemu_mutex_lock(&q
->lock
);
325 nvme_put_free_req_locked(q
, req
);
326 nvme_wake_free_req_locked(q
);
327 qemu_mutex_unlock(&q
->lock
);
330 static inline int nvme_translate_error(const NvmeCqe
*c
)
332 uint16_t status
= (le16_to_cpu(c
->status
) >> 1) & 0xFF;
334 trace_nvme_error(le32_to_cpu(c
->result
),
335 le16_to_cpu(c
->sq_head
),
336 le16_to_cpu(c
->sq_id
),
338 le16_to_cpu(status
));
353 static bool nvme_process_completion(NVMeQueuePair
*q
)
355 BDRVNVMeState
*s
= q
->s
;
356 bool progress
= false;
361 trace_nvme_process_completion(s
, q
->index
, q
->inflight
);
363 trace_nvme_process_completion_queue_plugged(s
, q
->index
);
368 * Support re-entrancy when a request cb() function invokes aio_poll().
369 * Pending completions must be visible to aio_poll() so that a cb()
370 * function can wait for the completion of another request.
372 * The aio_poll() loop will execute our BH and we'll resume completion
375 qemu_bh_schedule(q
->completion_bh
);
377 assert(q
->inflight
>= 0);
378 while (q
->inflight
) {
382 c
= (NvmeCqe
*)&q
->cq
.queue
[q
->cq
.head
* NVME_CQ_ENTRY_BYTES
];
383 if ((le16_to_cpu(c
->status
) & 0x1) == q
->cq_phase
) {
386 ret
= nvme_translate_error(c
);
387 q
->cq
.head
= (q
->cq
.head
+ 1) % NVME_QUEUE_SIZE
;
389 q
->cq_phase
= !q
->cq_phase
;
391 cid
= le16_to_cpu(c
->cid
);
392 if (cid
== 0 || cid
> NVME_QUEUE_SIZE
) {
393 fprintf(stderr
, "Unexpected CID in completion queue: %" PRIu32
"\n",
397 trace_nvme_complete_command(s
, q
->index
, cid
);
398 preq
= &q
->reqs
[cid
- 1];
400 assert(req
.cid
== cid
);
402 nvme_put_free_req_locked(q
, preq
);
403 preq
->cb
= preq
->opaque
= NULL
;
405 qemu_mutex_unlock(&q
->lock
);
406 req
.cb(req
.opaque
, ret
);
407 qemu_mutex_lock(&q
->lock
);
411 /* Notify the device so it can post more completions. */
413 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
414 nvme_wake_free_req_locked(q
);
417 qemu_bh_cancel(q
->completion_bh
);
422 static void nvme_process_completion_bh(void *opaque
)
424 NVMeQueuePair
*q
= opaque
;
427 * We're being invoked because a nvme_process_completion() cb() function
428 * called aio_poll(). The callback may be waiting for further completions
429 * so notify the device that it has space to fill in more completions now.
432 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
433 nvme_wake_free_req_locked(q
);
435 nvme_process_completion(q
);
438 static void nvme_trace_command(const NvmeCmd
*cmd
)
442 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW
)) {
445 for (i
= 0; i
< 8; ++i
) {
446 uint8_t *cmdp
= (uint8_t *)cmd
+ i
* 8;
447 trace_nvme_submit_command_raw(cmdp
[0], cmdp
[1], cmdp
[2], cmdp
[3],
448 cmdp
[4], cmdp
[5], cmdp
[6], cmdp
[7]);
452 static void nvme_submit_command(NVMeQueuePair
*q
, NVMeRequest
*req
,
453 NvmeCmd
*cmd
, BlockCompletionFunc cb
,
458 req
->opaque
= opaque
;
459 cmd
->cid
= cpu_to_le32(req
->cid
);
461 trace_nvme_submit_command(q
->s
, q
->index
, req
->cid
);
462 nvme_trace_command(cmd
);
463 qemu_mutex_lock(&q
->lock
);
464 memcpy((uint8_t *)q
->sq
.queue
+
465 q
->sq
.tail
* NVME_SQ_ENTRY_BYTES
, cmd
, sizeof(*cmd
));
466 q
->sq
.tail
= (q
->sq
.tail
+ 1) % NVME_QUEUE_SIZE
;
469 nvme_process_completion(q
);
470 qemu_mutex_unlock(&q
->lock
);
473 static void nvme_cmd_sync_cb(void *opaque
, int ret
)
480 static int nvme_cmd_sync(BlockDriverState
*bs
, NVMeQueuePair
*q
,
483 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
485 int ret
= -EINPROGRESS
;
486 req
= nvme_get_free_req(q
);
490 nvme_submit_command(q
, req
, cmd
, nvme_cmd_sync_cb
, &ret
);
492 AIO_WAIT_WHILE(aio_context
, ret
== -EINPROGRESS
);
496 static void nvme_identify(BlockDriverState
*bs
, int namespace, Error
**errp
)
498 BDRVNVMeState
*s
= bs
->opaque
;
508 .opcode
= NVME_ADM_CMD_IDENTIFY
,
509 .cdw10
= cpu_to_le32(0x1),
512 id
= qemu_try_memalign(s
->page_size
, sizeof(*id
));
514 error_setg(errp
, "Cannot allocate buffer for identify response");
517 r
= qemu_vfio_dma_map(s
->vfio
, id
, sizeof(*id
), true, &iova
);
519 error_setg(errp
, "Cannot map buffer for DMA");
523 memset(id
, 0, sizeof(*id
));
524 cmd
.dptr
.prp1
= cpu_to_le64(iova
);
525 if (nvme_cmd_sync(bs
, s
->queues
[INDEX_ADMIN
], &cmd
)) {
526 error_setg(errp
, "Failed to identify controller");
530 if (le32_to_cpu(id
->ctrl
.nn
) < namespace) {
531 error_setg(errp
, "Invalid namespace");
534 s
->write_cache_supported
= le32_to_cpu(id
->ctrl
.vwc
) & 0x1;
535 s
->max_transfer
= (id
->ctrl
.mdts
? 1 << id
->ctrl
.mdts
: 0) * s
->page_size
;
536 /* For now the page list buffer per command is one page, to hold at most
537 * s->page_size / sizeof(uint64_t) entries. */
538 s
->max_transfer
= MIN_NON_ZERO(s
->max_transfer
,
539 s
->page_size
/ sizeof(uint64_t) * s
->page_size
);
541 oncs
= le16_to_cpu(id
->ctrl
.oncs
);
542 s
->supports_write_zeroes
= !!(oncs
& NVME_ONCS_WRITE_ZEROES
);
543 s
->supports_discard
= !!(oncs
& NVME_ONCS_DSM
);
545 memset(id
, 0, sizeof(*id
));
547 cmd
.nsid
= cpu_to_le32(namespace);
548 if (nvme_cmd_sync(bs
, s
->queues
[INDEX_ADMIN
], &cmd
)) {
549 error_setg(errp
, "Failed to identify namespace");
553 s
->nsze
= le64_to_cpu(id
->ns
.nsze
);
554 lbaf
= &id
->ns
.lbaf
[NVME_ID_NS_FLBAS_INDEX(id
->ns
.flbas
)];
556 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id
->ns
.dlfeat
) &&
557 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id
->ns
.dlfeat
) ==
558 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES
) {
559 bs
->supported_write_flags
|= BDRV_REQ_MAY_UNMAP
;
563 error_setg(errp
, "Namespaces with metadata are not yet supported");
567 if (lbaf
->ds
< BDRV_SECTOR_BITS
|| lbaf
->ds
> 12 ||
568 (1 << lbaf
->ds
) > s
->page_size
)
570 error_setg(errp
, "Namespace has unsupported block size (2^%d)",
575 s
->blkshift
= lbaf
->ds
;
577 qemu_vfio_dma_unmap(s
->vfio
, id
);
581 static bool nvme_poll_queue(NVMeQueuePair
*q
)
583 bool progress
= false;
585 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
586 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
589 * Do an early check for completions. q->lock isn't needed because
590 * nvme_process_completion() only runs in the event loop thread and
591 * cannot race with itself.
593 if ((le16_to_cpu(cqe
->status
) & 0x1) == q
->cq_phase
) {
597 qemu_mutex_lock(&q
->lock
);
598 while (nvme_process_completion(q
)) {
602 qemu_mutex_unlock(&q
->lock
);
607 static bool nvme_poll_queues(BDRVNVMeState
*s
)
609 bool progress
= false;
612 for (i
= 0; i
< s
->nr_queues
; i
++) {
613 if (nvme_poll_queue(s
->queues
[i
])) {
620 static void nvme_handle_event(EventNotifier
*n
)
622 BDRVNVMeState
*s
= container_of(n
, BDRVNVMeState
,
623 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
625 trace_nvme_handle_event(s
);
626 event_notifier_test_and_clear(n
);
630 static bool nvme_add_io_queue(BlockDriverState
*bs
, Error
**errp
)
632 BDRVNVMeState
*s
= bs
->opaque
;
633 int n
= s
->nr_queues
;
636 int queue_size
= NVME_QUEUE_SIZE
;
638 q
= nvme_create_queue_pair(s
, bdrv_get_aio_context(bs
),
639 n
, queue_size
, errp
);
644 .opcode
= NVME_ADM_CMD_CREATE_CQ
,
645 .dptr
.prp1
= cpu_to_le64(q
->cq
.iova
),
646 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | (n
& 0xFFFF)),
647 .cdw11
= cpu_to_le32(0x3),
649 if (nvme_cmd_sync(bs
, s
->queues
[INDEX_ADMIN
], &cmd
)) {
650 error_setg(errp
, "Failed to create CQ io queue [%d]", n
);
654 .opcode
= NVME_ADM_CMD_CREATE_SQ
,
655 .dptr
.prp1
= cpu_to_le64(q
->sq
.iova
),
656 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | (n
& 0xFFFF)),
657 .cdw11
= cpu_to_le32(0x1 | (n
<< 16)),
659 if (nvme_cmd_sync(bs
, s
->queues
[INDEX_ADMIN
], &cmd
)) {
660 error_setg(errp
, "Failed to create SQ io queue [%d]", n
);
663 s
->queues
= g_renew(NVMeQueuePair
*, s
->queues
, n
+ 1);
668 nvme_free_queue_pair(q
);
672 static bool nvme_poll_cb(void *opaque
)
674 EventNotifier
*e
= opaque
;
675 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
676 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
678 trace_nvme_poll_cb(s
);
679 return nvme_poll_queues(s
);
682 static int nvme_init(BlockDriverState
*bs
, const char *device
, int namespace,
685 BDRVNVMeState
*s
= bs
->opaque
;
686 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
690 uint64_t deadline
, now
;
691 Error
*local_err
= NULL
;
692 volatile NvmeBar
*regs
= NULL
;
694 qemu_co_mutex_init(&s
->dma_map_lock
);
695 qemu_co_queue_init(&s
->dma_flush_queue
);
696 s
->device
= g_strdup(device
);
698 s
->aio_context
= bdrv_get_aio_context(bs
);
699 ret
= event_notifier_init(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
], 0);
701 error_setg(errp
, "Failed to init event notifier");
705 s
->vfio
= qemu_vfio_open_pci(device
, errp
);
711 regs
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0, sizeof(NvmeBar
),
712 PROT_READ
| PROT_WRITE
, errp
);
717 /* Perform initialize sequence as described in NVMe spec "7.6.1
718 * Initialization". */
720 cap
= le64_to_cpu(regs
->cap
);
721 if (!NVME_CAP_CSS(cap
)) {
722 error_setg(errp
, "Device doesn't support NVMe command set");
727 s
->page_size
= MAX(4096, 1 << NVME_CAP_MPSMIN(cap
));
728 s
->doorbell_scale
= (4 << NVME_CAP_DSTRD(cap
)) / sizeof(uint32_t);
729 bs
->bl
.opt_mem_alignment
= s
->page_size
;
730 timeout_ms
= MIN(500 * NVME_CAP_TO(cap
), 30000);
732 /* Reset device to get a clean state. */
733 regs
->cc
= cpu_to_le32(le32_to_cpu(regs
->cc
) & 0xFE);
734 /* Wait for CSTS.RDY = 0. */
735 deadline
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + timeout_ms
* SCALE_MS
;
736 while (NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
737 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
738 error_setg(errp
, "Timeout while waiting for device to reset (%"
746 s
->doorbells
= qemu_vfio_pci_map_bar(s
->vfio
, 0, sizeof(NvmeBar
),
747 NVME_DOORBELL_SIZE
, PROT_WRITE
, errp
);
753 /* Set up admin queue. */
754 s
->queues
= g_new(NVMeQueuePair
*, 1);
755 s
->queues
[INDEX_ADMIN
] = nvme_create_queue_pair(s
, aio_context
, 0,
758 if (!s
->queues
[INDEX_ADMIN
]) {
763 QEMU_BUILD_BUG_ON(NVME_QUEUE_SIZE
& 0xF000);
764 regs
->aqa
= cpu_to_le32((NVME_QUEUE_SIZE
<< AQA_ACQS_SHIFT
) |
765 (NVME_QUEUE_SIZE
<< AQA_ASQS_SHIFT
));
766 regs
->asq
= cpu_to_le64(s
->queues
[INDEX_ADMIN
]->sq
.iova
);
767 regs
->acq
= cpu_to_le64(s
->queues
[INDEX_ADMIN
]->cq
.iova
);
769 /* After setting up all control registers we can enable device now. */
770 regs
->cc
= cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES
) << CC_IOCQES_SHIFT
) |
771 (ctz32(NVME_SQ_ENTRY_BYTES
) << CC_IOSQES_SHIFT
) |
773 /* Wait for CSTS.RDY = 1. */
774 now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
775 deadline
= now
+ timeout_ms
* SCALE_MS
;
776 while (!NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
777 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
778 error_setg(errp
, "Timeout while waiting for device to start (%"
786 ret
= qemu_vfio_pci_init_irq(s
->vfio
, s
->irq_notifier
,
787 VFIO_PCI_MSIX_IRQ_INDEX
, errp
);
791 aio_set_event_notifier(bdrv_get_aio_context(bs
),
792 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
793 false, nvme_handle_event
, nvme_poll_cb
);
795 nvme_identify(bs
, namespace, &local_err
);
797 error_propagate(errp
, local_err
);
802 /* Set up command queues. */
803 if (!nvme_add_io_queue(bs
, errp
)) {
808 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)regs
, 0, sizeof(NvmeBar
));
811 /* Cleaning up is done in nvme_file_open() upon error. */
815 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
817 * nvme://0000:44:00.0/1
819 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
820 * is the PCI address, and the last part is the namespace number starting from
821 * 1 according to the NVMe spec. */
822 static void nvme_parse_filename(const char *filename
, QDict
*options
,
825 int pref
= strlen("nvme://");
827 if (strlen(filename
) > pref
&& !strncmp(filename
, "nvme://", pref
)) {
828 const char *tmp
= filename
+ pref
;
830 const char *namespace;
832 const char *slash
= strchr(tmp
, '/');
834 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, tmp
);
837 device
= g_strndup(tmp
, slash
- tmp
);
838 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, device
);
840 namespace = slash
+ 1;
841 if (*namespace && qemu_strtoul(namespace, NULL
, 10, &ns
)) {
842 error_setg(errp
, "Invalid namespace '%s', positive number expected",
846 qdict_put_str(options
, NVME_BLOCK_OPT_NAMESPACE
,
847 *namespace ? namespace : "1");
851 static int nvme_enable_disable_write_cache(BlockDriverState
*bs
, bool enable
,
855 BDRVNVMeState
*s
= bs
->opaque
;
857 .opcode
= NVME_ADM_CMD_SET_FEATURES
,
858 .nsid
= cpu_to_le32(s
->nsid
),
859 .cdw10
= cpu_to_le32(0x06),
860 .cdw11
= cpu_to_le32(enable
? 0x01 : 0x00),
863 ret
= nvme_cmd_sync(bs
, s
->queues
[INDEX_ADMIN
], &cmd
);
865 error_setg(errp
, "Failed to configure NVMe write cache");
870 static void nvme_close(BlockDriverState
*bs
)
873 BDRVNVMeState
*s
= bs
->opaque
;
875 for (i
= 0; i
< s
->nr_queues
; ++i
) {
876 nvme_free_queue_pair(s
->queues
[i
]);
879 aio_set_event_notifier(bdrv_get_aio_context(bs
),
880 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
882 event_notifier_cleanup(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
883 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)s
->doorbells
,
884 sizeof(NvmeBar
), NVME_DOORBELL_SIZE
);
885 qemu_vfio_close(s
->vfio
);
890 static int nvme_file_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
897 BDRVNVMeState
*s
= bs
->opaque
;
899 bs
->supported_write_flags
= BDRV_REQ_FUA
;
901 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
902 qemu_opts_absorb_qdict(opts
, options
, &error_abort
);
903 device
= qemu_opt_get(opts
, NVME_BLOCK_OPT_DEVICE
);
905 error_setg(errp
, "'" NVME_BLOCK_OPT_DEVICE
"' option is required");
910 namespace = qemu_opt_get_number(opts
, NVME_BLOCK_OPT_NAMESPACE
, 1);
911 ret
= nvme_init(bs
, device
, namespace, errp
);
916 if (flags
& BDRV_O_NOCACHE
) {
917 if (!s
->write_cache_supported
) {
919 "NVMe controller doesn't support write cache configuration");
922 ret
= nvme_enable_disable_write_cache(bs
, !(flags
& BDRV_O_NOCACHE
),
935 static int64_t nvme_getlength(BlockDriverState
*bs
)
937 BDRVNVMeState
*s
= bs
->opaque
;
938 return s
->nsze
<< s
->blkshift
;
941 static uint32_t nvme_get_blocksize(BlockDriverState
*bs
)
943 BDRVNVMeState
*s
= bs
->opaque
;
944 assert(s
->blkshift
>= BDRV_SECTOR_BITS
&& s
->blkshift
<= 12);
945 return UINT32_C(1) << s
->blkshift
;
948 static int nvme_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
950 uint32_t blocksize
= nvme_get_blocksize(bs
);
951 bsz
->phys
= blocksize
;
952 bsz
->log
= blocksize
;
956 /* Called with s->dma_map_lock */
957 static coroutine_fn
int nvme_cmd_unmap_qiov(BlockDriverState
*bs
,
961 BDRVNVMeState
*s
= bs
->opaque
;
963 s
->dma_map_count
-= qiov
->size
;
964 if (!s
->dma_map_count
&& !qemu_co_queue_empty(&s
->dma_flush_queue
)) {
965 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
967 qemu_co_queue_restart_all(&s
->dma_flush_queue
);
973 /* Called with s->dma_map_lock */
974 static coroutine_fn
int nvme_cmd_map_qiov(BlockDriverState
*bs
, NvmeCmd
*cmd
,
975 NVMeRequest
*req
, QEMUIOVector
*qiov
)
977 BDRVNVMeState
*s
= bs
->opaque
;
978 uint64_t *pagelist
= req
->prp_list_page
;
983 assert(QEMU_IS_ALIGNED(qiov
->size
, s
->page_size
));
984 assert(qiov
->size
/ s
->page_size
<= s
->page_size
/ sizeof(uint64_t));
985 for (i
= 0; i
< qiov
->niov
; ++i
) {
989 r
= qemu_vfio_dma_map(s
->vfio
,
990 qiov
->iov
[i
].iov_base
,
991 qiov
->iov
[i
].iov_len
,
993 if (r
== -ENOMEM
&& retry
) {
995 trace_nvme_dma_flush_queue_wait(s
);
996 if (s
->dma_map_count
) {
997 trace_nvme_dma_map_flush(s
);
998 qemu_co_queue_wait(&s
->dma_flush_queue
, &s
->dma_map_lock
);
1000 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1011 for (j
= 0; j
< qiov
->iov
[i
].iov_len
/ s
->page_size
; j
++) {
1012 pagelist
[entries
++] = cpu_to_le64(iova
+ j
* s
->page_size
);
1014 trace_nvme_cmd_map_qiov_iov(s
, i
, qiov
->iov
[i
].iov_base
,
1015 qiov
->iov
[i
].iov_len
/ s
->page_size
);
1018 s
->dma_map_count
+= qiov
->size
;
1020 assert(entries
<= s
->page_size
/ sizeof(uint64_t));
1025 cmd
->dptr
.prp1
= pagelist
[0];
1029 cmd
->dptr
.prp1
= pagelist
[0];
1030 cmd
->dptr
.prp2
= pagelist
[1];
1033 cmd
->dptr
.prp1
= pagelist
[0];
1034 cmd
->dptr
.prp2
= cpu_to_le64(req
->prp_list_iova
+ sizeof(uint64_t));
1037 trace_nvme_cmd_map_qiov(s
, cmd
, req
, qiov
, entries
);
1038 for (i
= 0; i
< entries
; ++i
) {
1039 trace_nvme_cmd_map_qiov_pages(s
, i
, pagelist
[i
]);
1043 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1044 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1045 * because they are already mapped before calling this function; for
1046 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1047 * calling qemu_vfio_dma_reset_temporary when necessary. */
1057 static void nvme_rw_cb_bh(void *opaque
)
1059 NVMeCoData
*data
= opaque
;
1060 qemu_coroutine_enter(data
->co
);
1063 static void nvme_rw_cb(void *opaque
, int ret
)
1065 NVMeCoData
*data
= opaque
;
1068 /* The rw coroutine hasn't yielded, don't try to enter. */
1071 replay_bh_schedule_oneshot_event(data
->ctx
, nvme_rw_cb_bh
, data
);
1074 static coroutine_fn
int nvme_co_prw_aligned(BlockDriverState
*bs
,
1075 uint64_t offset
, uint64_t bytes
,
1081 BDRVNVMeState
*s
= bs
->opaque
;
1082 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1085 uint32_t cdw12
= (((bytes
>> s
->blkshift
) - 1) & 0xFFFF) |
1086 (flags
& BDRV_REQ_FUA
? 1 << 30 : 0);
1088 .opcode
= is_write
? NVME_CMD_WRITE
: NVME_CMD_READ
,
1089 .nsid
= cpu_to_le32(s
->nsid
),
1090 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1091 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1092 .cdw12
= cpu_to_le32(cdw12
),
1095 .ctx
= bdrv_get_aio_context(bs
),
1096 .ret
= -EINPROGRESS
,
1099 trace_nvme_prw_aligned(s
, is_write
, offset
, bytes
, flags
, qiov
->niov
);
1100 assert(s
->nr_queues
> 1);
1101 req
= nvme_get_free_req(ioq
);
1104 qemu_co_mutex_lock(&s
->dma_map_lock
);
1105 r
= nvme_cmd_map_qiov(bs
, &cmd
, req
, qiov
);
1106 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1108 nvme_put_free_req_and_wake(ioq
, req
);
1111 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1113 data
.co
= qemu_coroutine_self();
1114 while (data
.ret
== -EINPROGRESS
) {
1115 qemu_coroutine_yield();
1118 qemu_co_mutex_lock(&s
->dma_map_lock
);
1119 r
= nvme_cmd_unmap_qiov(bs
, qiov
);
1120 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1125 trace_nvme_rw_done(s
, is_write
, offset
, bytes
, data
.ret
);
1129 static inline bool nvme_qiov_aligned(BlockDriverState
*bs
,
1130 const QEMUIOVector
*qiov
)
1133 BDRVNVMeState
*s
= bs
->opaque
;
1135 for (i
= 0; i
< qiov
->niov
; ++i
) {
1136 if (!QEMU_PTR_IS_ALIGNED(qiov
->iov
[i
].iov_base
, s
->page_size
) ||
1137 !QEMU_IS_ALIGNED(qiov
->iov
[i
].iov_len
, s
->page_size
)) {
1138 trace_nvme_qiov_unaligned(qiov
, i
, qiov
->iov
[i
].iov_base
,
1139 qiov
->iov
[i
].iov_len
, s
->page_size
);
1146 static int nvme_co_prw(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1147 QEMUIOVector
*qiov
, bool is_write
, int flags
)
1149 BDRVNVMeState
*s
= bs
->opaque
;
1151 uint8_t *buf
= NULL
;
1152 QEMUIOVector local_qiov
;
1154 assert(QEMU_IS_ALIGNED(offset
, s
->page_size
));
1155 assert(QEMU_IS_ALIGNED(bytes
, s
->page_size
));
1156 assert(bytes
<= s
->max_transfer
);
1157 if (nvme_qiov_aligned(bs
, qiov
)) {
1158 return nvme_co_prw_aligned(bs
, offset
, bytes
, qiov
, is_write
, flags
);
1160 trace_nvme_prw_buffered(s
, offset
, bytes
, qiov
->niov
, is_write
);
1161 buf
= qemu_try_memalign(s
->page_size
, bytes
);
1166 qemu_iovec_init(&local_qiov
, 1);
1168 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
1170 qemu_iovec_add(&local_qiov
, buf
, bytes
);
1171 r
= nvme_co_prw_aligned(bs
, offset
, bytes
, &local_qiov
, is_write
, flags
);
1172 qemu_iovec_destroy(&local_qiov
);
1173 if (!r
&& !is_write
) {
1174 qemu_iovec_from_buf(qiov
, 0, buf
, bytes
);
1180 static coroutine_fn
int nvme_co_preadv(BlockDriverState
*bs
,
1181 uint64_t offset
, uint64_t bytes
,
1182 QEMUIOVector
*qiov
, int flags
)
1184 return nvme_co_prw(bs
, offset
, bytes
, qiov
, false, flags
);
1187 static coroutine_fn
int nvme_co_pwritev(BlockDriverState
*bs
,
1188 uint64_t offset
, uint64_t bytes
,
1189 QEMUIOVector
*qiov
, int flags
)
1191 return nvme_co_prw(bs
, offset
, bytes
, qiov
, true, flags
);
1194 static coroutine_fn
int nvme_co_flush(BlockDriverState
*bs
)
1196 BDRVNVMeState
*s
= bs
->opaque
;
1197 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1200 .opcode
= NVME_CMD_FLUSH
,
1201 .nsid
= cpu_to_le32(s
->nsid
),
1204 .ctx
= bdrv_get_aio_context(bs
),
1205 .ret
= -EINPROGRESS
,
1208 assert(s
->nr_queues
> 1);
1209 req
= nvme_get_free_req(ioq
);
1211 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1213 data
.co
= qemu_coroutine_self();
1214 if (data
.ret
== -EINPROGRESS
) {
1215 qemu_coroutine_yield();
1222 static coroutine_fn
int nvme_co_pwrite_zeroes(BlockDriverState
*bs
,
1225 BdrvRequestFlags flags
)
1227 BDRVNVMeState
*s
= bs
->opaque
;
1228 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1231 uint32_t cdw12
= ((bytes
>> s
->blkshift
) - 1) & 0xFFFF;
1233 if (!s
->supports_write_zeroes
) {
1238 .opcode
= NVME_CMD_WRITE_ZEROES
,
1239 .nsid
= cpu_to_le32(s
->nsid
),
1240 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1241 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1245 .ctx
= bdrv_get_aio_context(bs
),
1246 .ret
= -EINPROGRESS
,
1249 if (flags
& BDRV_REQ_MAY_UNMAP
) {
1253 if (flags
& BDRV_REQ_FUA
) {
1257 cmd
.cdw12
= cpu_to_le32(cdw12
);
1259 trace_nvme_write_zeroes(s
, offset
, bytes
, flags
);
1260 assert(s
->nr_queues
> 1);
1261 req
= nvme_get_free_req(ioq
);
1264 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1266 data
.co
= qemu_coroutine_self();
1267 while (data
.ret
== -EINPROGRESS
) {
1268 qemu_coroutine_yield();
1271 trace_nvme_rw_done(s
, true, offset
, bytes
, data
.ret
);
1276 static int coroutine_fn
nvme_co_pdiscard(BlockDriverState
*bs
,
1280 BDRVNVMeState
*s
= bs
->opaque
;
1281 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1284 QEMUIOVector local_qiov
;
1288 .opcode
= NVME_CMD_DSM
,
1289 .nsid
= cpu_to_le32(s
->nsid
),
1290 .cdw10
= cpu_to_le32(0), /*number of ranges - 0 based*/
1291 .cdw11
= cpu_to_le32(1 << 2), /*deallocate bit*/
1295 .ctx
= bdrv_get_aio_context(bs
),
1296 .ret
= -EINPROGRESS
,
1299 if (!s
->supports_discard
) {
1303 assert(s
->nr_queues
> 1);
1305 buf
= qemu_try_memalign(s
->page_size
, s
->page_size
);
1309 memset(buf
, 0, s
->page_size
);
1310 buf
->nlb
= cpu_to_le32(bytes
>> s
->blkshift
);
1311 buf
->slba
= cpu_to_le64(offset
>> s
->blkshift
);
1314 qemu_iovec_init(&local_qiov
, 1);
1315 qemu_iovec_add(&local_qiov
, buf
, 4096);
1317 req
= nvme_get_free_req(ioq
);
1320 qemu_co_mutex_lock(&s
->dma_map_lock
);
1321 ret
= nvme_cmd_map_qiov(bs
, &cmd
, req
, &local_qiov
);
1322 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1325 nvme_put_free_req_and_wake(ioq
, req
);
1329 trace_nvme_dsm(s
, offset
, bytes
);
1331 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1333 data
.co
= qemu_coroutine_self();
1334 while (data
.ret
== -EINPROGRESS
) {
1335 qemu_coroutine_yield();
1338 qemu_co_mutex_lock(&s
->dma_map_lock
);
1339 ret
= nvme_cmd_unmap_qiov(bs
, &local_qiov
);
1340 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1347 trace_nvme_dsm_done(s
, offset
, bytes
, ret
);
1349 qemu_iovec_destroy(&local_qiov
);
1356 static int nvme_reopen_prepare(BDRVReopenState
*reopen_state
,
1357 BlockReopenQueue
*queue
, Error
**errp
)
1362 static void nvme_refresh_filename(BlockDriverState
*bs
)
1364 BDRVNVMeState
*s
= bs
->opaque
;
1366 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
), "nvme://%s/%i",
1367 s
->device
, s
->nsid
);
1370 static void nvme_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1372 BDRVNVMeState
*s
= bs
->opaque
;
1374 bs
->bl
.opt_mem_alignment
= s
->page_size
;
1375 bs
->bl
.request_alignment
= s
->page_size
;
1376 bs
->bl
.max_transfer
= s
->max_transfer
;
1379 static void nvme_detach_aio_context(BlockDriverState
*bs
)
1381 BDRVNVMeState
*s
= bs
->opaque
;
1383 for (int i
= 0; i
< s
->nr_queues
; i
++) {
1384 NVMeQueuePair
*q
= s
->queues
[i
];
1386 qemu_bh_delete(q
->completion_bh
);
1387 q
->completion_bh
= NULL
;
1390 aio_set_event_notifier(bdrv_get_aio_context(bs
),
1391 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1395 static void nvme_attach_aio_context(BlockDriverState
*bs
,
1396 AioContext
*new_context
)
1398 BDRVNVMeState
*s
= bs
->opaque
;
1400 s
->aio_context
= new_context
;
1401 aio_set_event_notifier(new_context
, &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1402 false, nvme_handle_event
, nvme_poll_cb
);
1404 for (int i
= 0; i
< s
->nr_queues
; i
++) {
1405 NVMeQueuePair
*q
= s
->queues
[i
];
1408 aio_bh_new(new_context
, nvme_process_completion_bh
, q
);
1412 static void nvme_aio_plug(BlockDriverState
*bs
)
1414 BDRVNVMeState
*s
= bs
->opaque
;
1415 assert(!s
->plugged
);
1419 static void nvme_aio_unplug(BlockDriverState
*bs
)
1422 BDRVNVMeState
*s
= bs
->opaque
;
1425 for (i
= INDEX_IO(0); i
< s
->nr_queues
; i
++) {
1426 NVMeQueuePair
*q
= s
->queues
[i
];
1427 qemu_mutex_lock(&q
->lock
);
1429 nvme_process_completion(q
);
1430 qemu_mutex_unlock(&q
->lock
);
1434 static void nvme_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
1437 BDRVNVMeState
*s
= bs
->opaque
;
1439 ret
= qemu_vfio_dma_map(s
->vfio
, host
, size
, false, NULL
);
1441 /* FIXME: we may run out of IOVA addresses after repeated
1442 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1443 * doesn't reclaim addresses for fixed mappings. */
1444 error_report("nvme_register_buf failed: %s", strerror(-ret
));
1448 static void nvme_unregister_buf(BlockDriverState
*bs
, void *host
)
1450 BDRVNVMeState
*s
= bs
->opaque
;
1452 qemu_vfio_dma_unmap(s
->vfio
, host
);
1455 static const char *const nvme_strong_runtime_opts
[] = {
1456 NVME_BLOCK_OPT_DEVICE
,
1457 NVME_BLOCK_OPT_NAMESPACE
,
1462 static BlockDriver bdrv_nvme
= {
1463 .format_name
= "nvme",
1464 .protocol_name
= "nvme",
1465 .instance_size
= sizeof(BDRVNVMeState
),
1467 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
1468 .create_opts
= &bdrv_create_opts_simple
,
1470 .bdrv_parse_filename
= nvme_parse_filename
,
1471 .bdrv_file_open
= nvme_file_open
,
1472 .bdrv_close
= nvme_close
,
1473 .bdrv_getlength
= nvme_getlength
,
1474 .bdrv_probe_blocksizes
= nvme_probe_blocksizes
,
1476 .bdrv_co_preadv
= nvme_co_preadv
,
1477 .bdrv_co_pwritev
= nvme_co_pwritev
,
1479 .bdrv_co_pwrite_zeroes
= nvme_co_pwrite_zeroes
,
1480 .bdrv_co_pdiscard
= nvme_co_pdiscard
,
1482 .bdrv_co_flush_to_disk
= nvme_co_flush
,
1483 .bdrv_reopen_prepare
= nvme_reopen_prepare
,
1485 .bdrv_refresh_filename
= nvme_refresh_filename
,
1486 .bdrv_refresh_limits
= nvme_refresh_limits
,
1487 .strong_runtime_opts
= nvme_strong_runtime_opts
,
1489 .bdrv_detach_aio_context
= nvme_detach_aio_context
,
1490 .bdrv_attach_aio_context
= nvme_attach_aio_context
,
1492 .bdrv_io_plug
= nvme_aio_plug
,
1493 .bdrv_io_unplug
= nvme_aio_unplug
,
1495 .bdrv_register_buf
= nvme_register_buf
,
1496 .bdrv_unregister_buf
= nvme_unregister_buf
,
1499 static void bdrv_nvme_init(void)
1501 bdrv_register(&bdrv_nvme
);
1504 block_init(bdrv_nvme_init
);