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_BAR_SIZE 8192
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
;
84 /* Memory mapped registers */
85 typedef volatile struct {
99 uint8_t reserved1
[0xec0];
100 uint8_t cmd_set_specfic
[0x100];
101 uint32_t doorbells
[];
104 QEMU_BUILD_BUG_ON(offsetof(NVMeRegs
, doorbells
) != 0x1000);
106 struct BDRVNVMeState
{
107 AioContext
*aio_context
;
110 /* The submission/completion queue pairs.
114 NVMeQueuePair
**queues
;
117 /* How many uint32_t elements does each doorbell entry take. */
118 size_t doorbell_scale
;
119 bool write_cache_supported
;
120 EventNotifier irq_notifier
;
122 uint64_t nsze
; /* Namespace size reported by identify command */
123 int nsid
; /* The namespace id to read/write data. */
126 uint64_t max_transfer
;
129 bool supports_write_zeroes
;
130 bool supports_discard
;
132 CoMutex dma_map_lock
;
133 CoQueue dma_flush_queue
;
135 /* Total size of mapped qiov, accessed under dma_map_lock */
138 /* PCI address (required for nvme_refresh_filename()) */
142 #define NVME_BLOCK_OPT_DEVICE "device"
143 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
145 static void nvme_process_completion_bh(void *opaque
);
147 static QemuOptsList runtime_opts
= {
149 .head
= QTAILQ_HEAD_INITIALIZER(runtime_opts
.head
),
152 .name
= NVME_BLOCK_OPT_DEVICE
,
153 .type
= QEMU_OPT_STRING
,
154 .help
= "NVMe PCI device address",
157 .name
= NVME_BLOCK_OPT_NAMESPACE
,
158 .type
= QEMU_OPT_NUMBER
,
159 .help
= "NVMe namespace",
161 { /* end of list */ }
165 static void nvme_init_queue(BlockDriverState
*bs
, NVMeQueue
*q
,
166 int nentries
, int entry_bytes
, Error
**errp
)
168 BDRVNVMeState
*s
= bs
->opaque
;
172 bytes
= ROUND_UP(nentries
* entry_bytes
, s
->page_size
);
173 q
->head
= q
->tail
= 0;
174 q
->queue
= qemu_try_blockalign0(bs
, bytes
);
177 error_setg(errp
, "Cannot allocate queue");
180 r
= qemu_vfio_dma_map(s
->vfio
, q
->queue
, bytes
, false, &q
->iova
);
182 error_setg(errp
, "Cannot map queue");
186 static void nvme_free_queue_pair(NVMeQueuePair
*q
)
188 if (q
->completion_bh
) {
189 qemu_bh_delete(q
->completion_bh
);
191 qemu_vfree(q
->prp_list_pages
);
192 qemu_vfree(q
->sq
.queue
);
193 qemu_vfree(q
->cq
.queue
);
194 qemu_mutex_destroy(&q
->lock
);
198 static void nvme_free_req_queue_cb(void *opaque
)
200 NVMeQueuePair
*q
= opaque
;
202 qemu_mutex_lock(&q
->lock
);
203 while (qemu_co_enter_next(&q
->free_req_queue
, &q
->lock
)) {
204 /* Retry all pending requests */
206 qemu_mutex_unlock(&q
->lock
);
209 static NVMeQueuePair
*nvme_create_queue_pair(BlockDriverState
*bs
,
214 BDRVNVMeState
*s
= bs
->opaque
;
215 Error
*local_err
= NULL
;
216 NVMeQueuePair
*q
= g_new0(NVMeQueuePair
, 1);
217 uint64_t prp_list_iova
;
219 qemu_mutex_init(&q
->lock
);
222 qemu_co_queue_init(&q
->free_req_queue
);
223 q
->prp_list_pages
= qemu_blockalign0(bs
, s
->page_size
* NVME_NUM_REQS
);
224 q
->completion_bh
= aio_bh_new(bdrv_get_aio_context(bs
),
225 nvme_process_completion_bh
, q
);
226 r
= qemu_vfio_dma_map(s
->vfio
, q
->prp_list_pages
,
227 s
->page_size
* NVME_NUM_REQS
,
228 false, &prp_list_iova
);
232 q
->free_req_head
= -1;
233 for (i
= 0; i
< NVME_NUM_REQS
; i
++) {
234 NVMeRequest
*req
= &q
->reqs
[i
];
236 req
->free_req_next
= q
->free_req_head
;
237 q
->free_req_head
= i
;
238 req
->prp_list_page
= q
->prp_list_pages
+ i
* s
->page_size
;
239 req
->prp_list_iova
= prp_list_iova
+ i
* s
->page_size
;
242 nvme_init_queue(bs
, &q
->sq
, size
, NVME_SQ_ENTRY_BYTES
, &local_err
);
244 error_propagate(errp
, local_err
);
247 q
->sq
.doorbell
= &s
->regs
->doorbells
[idx
* 2 * s
->doorbell_scale
];
249 nvme_init_queue(bs
, &q
->cq
, size
, NVME_CQ_ENTRY_BYTES
, &local_err
);
251 error_propagate(errp
, local_err
);
254 q
->cq
.doorbell
= &s
->regs
->doorbells
[(idx
* 2 + 1) * s
->doorbell_scale
];
258 nvme_free_queue_pair(q
);
263 static void nvme_kick(NVMeQueuePair
*q
)
265 BDRVNVMeState
*s
= q
->s
;
267 if (s
->plugged
|| !q
->need_kick
) {
270 trace_nvme_kick(s
, q
->index
);
271 assert(!(q
->sq
.tail
& 0xFF00));
272 /* Fence the write to submission queue entry before notifying the device. */
274 *q
->sq
.doorbell
= cpu_to_le32(q
->sq
.tail
);
275 q
->inflight
+= q
->need_kick
;
279 /* Find a free request element if any, otherwise:
280 * a) if in coroutine context, try to wait for one to become available;
281 * b) if not in coroutine, return NULL;
283 static NVMeRequest
*nvme_get_free_req(NVMeQueuePair
*q
)
287 qemu_mutex_lock(&q
->lock
);
289 while (q
->free_req_head
== -1) {
290 if (qemu_in_coroutine()) {
291 trace_nvme_free_req_queue_wait(q
);
292 qemu_co_queue_wait(&q
->free_req_queue
, &q
->lock
);
294 qemu_mutex_unlock(&q
->lock
);
299 req
= &q
->reqs
[q
->free_req_head
];
300 q
->free_req_head
= req
->free_req_next
;
301 req
->free_req_next
= -1;
303 qemu_mutex_unlock(&q
->lock
);
308 static void nvme_put_free_req_locked(NVMeQueuePair
*q
, NVMeRequest
*req
)
310 req
->free_req_next
= q
->free_req_head
;
311 q
->free_req_head
= req
- q
->reqs
;
315 static void nvme_wake_free_req_locked(NVMeQueuePair
*q
)
317 if (!qemu_co_queue_empty(&q
->free_req_queue
)) {
318 replay_bh_schedule_oneshot_event(q
->s
->aio_context
,
319 nvme_free_req_queue_cb
, q
);
323 /* Insert a request in the freelist and wake waiters */
324 static void nvme_put_free_req_and_wake(NVMeQueuePair
*q
, NVMeRequest
*req
)
326 qemu_mutex_lock(&q
->lock
);
327 nvme_put_free_req_locked(q
, req
);
328 nvme_wake_free_req_locked(q
);
329 qemu_mutex_unlock(&q
->lock
);
332 static inline int nvme_translate_error(const NvmeCqe
*c
)
334 uint16_t status
= (le16_to_cpu(c
->status
) >> 1) & 0xFF;
336 trace_nvme_error(le32_to_cpu(c
->result
),
337 le16_to_cpu(c
->sq_head
),
338 le16_to_cpu(c
->sq_id
),
340 le16_to_cpu(status
));
355 static bool nvme_process_completion(NVMeQueuePair
*q
)
357 BDRVNVMeState
*s
= q
->s
;
358 bool progress
= false;
363 trace_nvme_process_completion(s
, q
->index
, q
->inflight
);
365 trace_nvme_process_completion_queue_plugged(s
, q
->index
);
370 * Support re-entrancy when a request cb() function invokes aio_poll().
371 * Pending completions must be visible to aio_poll() so that a cb()
372 * function can wait for the completion of another request.
374 * The aio_poll() loop will execute our BH and we'll resume completion
377 qemu_bh_schedule(q
->completion_bh
);
379 assert(q
->inflight
>= 0);
380 while (q
->inflight
) {
384 c
= (NvmeCqe
*)&q
->cq
.queue
[q
->cq
.head
* NVME_CQ_ENTRY_BYTES
];
385 if ((le16_to_cpu(c
->status
) & 0x1) == q
->cq_phase
) {
388 ret
= nvme_translate_error(c
);
389 q
->cq
.head
= (q
->cq
.head
+ 1) % NVME_QUEUE_SIZE
;
391 q
->cq_phase
= !q
->cq_phase
;
393 cid
= le16_to_cpu(c
->cid
);
394 if (cid
== 0 || cid
> NVME_QUEUE_SIZE
) {
395 fprintf(stderr
, "Unexpected CID in completion queue: %" PRIu32
"\n",
399 trace_nvme_complete_command(s
, q
->index
, cid
);
400 preq
= &q
->reqs
[cid
- 1];
402 assert(req
.cid
== cid
);
404 nvme_put_free_req_locked(q
, preq
);
405 preq
->cb
= preq
->opaque
= NULL
;
407 qemu_mutex_unlock(&q
->lock
);
408 req
.cb(req
.opaque
, ret
);
409 qemu_mutex_lock(&q
->lock
);
413 /* Notify the device so it can post more completions. */
415 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
416 nvme_wake_free_req_locked(q
);
419 qemu_bh_cancel(q
->completion_bh
);
424 static void nvme_process_completion_bh(void *opaque
)
426 NVMeQueuePair
*q
= opaque
;
429 * We're being invoked because a nvme_process_completion() cb() function
430 * called aio_poll(). The callback may be waiting for further completions
431 * so notify the device that it has space to fill in more completions now.
434 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
435 nvme_wake_free_req_locked(q
);
437 nvme_process_completion(q
);
440 static void nvme_trace_command(const NvmeCmd
*cmd
)
444 for (i
= 0; i
< 8; ++i
) {
445 uint8_t *cmdp
= (uint8_t *)cmd
+ i
* 8;
446 trace_nvme_submit_command_raw(cmdp
[0], cmdp
[1], cmdp
[2], cmdp
[3],
447 cmdp
[4], cmdp
[5], cmdp
[6], cmdp
[7]);
451 static void nvme_submit_command(NVMeQueuePair
*q
, NVMeRequest
*req
,
452 NvmeCmd
*cmd
, BlockCompletionFunc cb
,
457 req
->opaque
= opaque
;
458 cmd
->cid
= cpu_to_le32(req
->cid
);
460 trace_nvme_submit_command(q
->s
, q
->index
, req
->cid
);
461 nvme_trace_command(cmd
);
462 qemu_mutex_lock(&q
->lock
);
463 memcpy((uint8_t *)q
->sq
.queue
+
464 q
->sq
.tail
* NVME_SQ_ENTRY_BYTES
, cmd
, sizeof(*cmd
));
465 q
->sq
.tail
= (q
->sq
.tail
+ 1) % NVME_QUEUE_SIZE
;
468 nvme_process_completion(q
);
469 qemu_mutex_unlock(&q
->lock
);
472 static void nvme_cmd_sync_cb(void *opaque
, int ret
)
479 static int nvme_cmd_sync(BlockDriverState
*bs
, NVMeQueuePair
*q
,
483 int ret
= -EINPROGRESS
;
484 req
= nvme_get_free_req(q
);
488 nvme_submit_command(q
, req
, cmd
, nvme_cmd_sync_cb
, &ret
);
490 BDRV_POLL_WHILE(bs
, ret
== -EINPROGRESS
);
494 static void nvme_identify(BlockDriverState
*bs
, int namespace, Error
**errp
)
496 BDRVNVMeState
*s
= bs
->opaque
;
505 .opcode
= NVME_ADM_CMD_IDENTIFY
,
506 .cdw10
= cpu_to_le32(0x1),
509 resp
= qemu_try_blockalign0(bs
, sizeof(NvmeIdCtrl
));
511 error_setg(errp
, "Cannot allocate buffer for identify response");
514 idctrl
= (NvmeIdCtrl
*)resp
;
515 idns
= (NvmeIdNs
*)resp
;
516 r
= qemu_vfio_dma_map(s
->vfio
, resp
, sizeof(NvmeIdCtrl
), true, &iova
);
518 error_setg(errp
, "Cannot map buffer for DMA");
521 cmd
.dptr
.prp1
= cpu_to_le64(iova
);
523 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
524 error_setg(errp
, "Failed to identify controller");
528 if (le32_to_cpu(idctrl
->nn
) < namespace) {
529 error_setg(errp
, "Invalid namespace");
532 s
->write_cache_supported
= le32_to_cpu(idctrl
->vwc
) & 0x1;
533 s
->max_transfer
= (idctrl
->mdts
? 1 << idctrl
->mdts
: 0) * s
->page_size
;
534 /* For now the page list buffer per command is one page, to hold at most
535 * s->page_size / sizeof(uint64_t) entries. */
536 s
->max_transfer
= MIN_NON_ZERO(s
->max_transfer
,
537 s
->page_size
/ sizeof(uint64_t) * s
->page_size
);
539 oncs
= le16_to_cpu(idctrl
->oncs
);
540 s
->supports_write_zeroes
= !!(oncs
& NVME_ONCS_WRITE_ZEROES
);
541 s
->supports_discard
= !!(oncs
& NVME_ONCS_DSM
);
543 memset(resp
, 0, 4096);
546 cmd
.nsid
= cpu_to_le32(namespace);
547 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
548 error_setg(errp
, "Failed to identify namespace");
552 s
->nsze
= le64_to_cpu(idns
->nsze
);
553 lbaf
= &idns
->lbaf
[NVME_ID_NS_FLBAS_INDEX(idns
->flbas
)];
555 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(idns
->dlfeat
) &&
556 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(idns
->dlfeat
) ==
557 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES
) {
558 bs
->supported_write_flags
|= BDRV_REQ_MAY_UNMAP
;
562 error_setg(errp
, "Namespaces with metadata are not yet supported");
566 if (lbaf
->ds
< BDRV_SECTOR_BITS
|| lbaf
->ds
> 12 ||
567 (1 << lbaf
->ds
) > s
->page_size
)
569 error_setg(errp
, "Namespace has unsupported block size (2^%d)",
574 s
->blkshift
= lbaf
->ds
;
576 qemu_vfio_dma_unmap(s
->vfio
, resp
);
580 static bool nvme_poll_queues(BDRVNVMeState
*s
)
582 bool progress
= false;
585 for (i
= 0; i
< s
->nr_queues
; i
++) {
586 NVMeQueuePair
*q
= s
->queues
[i
];
587 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
588 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
591 * Do an early check for completions. q->lock isn't needed because
592 * nvme_process_completion() only runs in the event loop thread and
593 * cannot race with itself.
595 if ((le16_to_cpu(cqe
->status
) & 0x1) == q
->cq_phase
) {
599 qemu_mutex_lock(&q
->lock
);
600 while (nvme_process_completion(q
)) {
604 qemu_mutex_unlock(&q
->lock
);
609 static void nvme_handle_event(EventNotifier
*n
)
611 BDRVNVMeState
*s
= container_of(n
, BDRVNVMeState
, irq_notifier
);
613 trace_nvme_handle_event(s
);
614 event_notifier_test_and_clear(n
);
618 static bool nvme_add_io_queue(BlockDriverState
*bs
, Error
**errp
)
620 BDRVNVMeState
*s
= bs
->opaque
;
621 int n
= s
->nr_queues
;
624 int queue_size
= NVME_QUEUE_SIZE
;
626 q
= nvme_create_queue_pair(bs
, n
, queue_size
, errp
);
631 .opcode
= NVME_ADM_CMD_CREATE_CQ
,
632 .dptr
.prp1
= cpu_to_le64(q
->cq
.iova
),
633 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | (n
& 0xFFFF)),
634 .cdw11
= cpu_to_le32(0x3),
636 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
637 error_setg(errp
, "Failed to create io queue [%d]", n
);
638 nvme_free_queue_pair(q
);
642 .opcode
= NVME_ADM_CMD_CREATE_SQ
,
643 .dptr
.prp1
= cpu_to_le64(q
->sq
.iova
),
644 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | (n
& 0xFFFF)),
645 .cdw11
= cpu_to_le32(0x1 | (n
<< 16)),
647 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
648 error_setg(errp
, "Failed to create io queue [%d]", n
);
649 nvme_free_queue_pair(q
);
652 s
->queues
= g_renew(NVMeQueuePair
*, s
->queues
, n
+ 1);
658 static bool nvme_poll_cb(void *opaque
)
660 EventNotifier
*e
= opaque
;
661 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
, irq_notifier
);
663 trace_nvme_poll_cb(s
);
664 return nvme_poll_queues(s
);
667 static int nvme_init(BlockDriverState
*bs
, const char *device
, int namespace,
670 BDRVNVMeState
*s
= bs
->opaque
;
674 uint64_t deadline
, now
;
675 Error
*local_err
= NULL
;
677 qemu_co_mutex_init(&s
->dma_map_lock
);
678 qemu_co_queue_init(&s
->dma_flush_queue
);
679 s
->device
= g_strdup(device
);
681 s
->aio_context
= bdrv_get_aio_context(bs
);
682 ret
= event_notifier_init(&s
->irq_notifier
, 0);
684 error_setg(errp
, "Failed to init event notifier");
688 s
->vfio
= qemu_vfio_open_pci(device
, errp
);
694 s
->regs
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0, NVME_BAR_SIZE
, errp
);
700 /* Perform initialize sequence as described in NVMe spec "7.6.1
701 * Initialization". */
703 cap
= le64_to_cpu(s
->regs
->cap
);
704 if (!(cap
& (1ULL << 37))) {
705 error_setg(errp
, "Device doesn't support NVMe command set");
710 s
->page_size
= MAX(4096, 1 << (12 + ((cap
>> 48) & 0xF)));
711 s
->doorbell_scale
= (4 << (((cap
>> 32) & 0xF))) / sizeof(uint32_t);
712 bs
->bl
.opt_mem_alignment
= s
->page_size
;
713 timeout_ms
= MIN(500 * ((cap
>> 24) & 0xFF), 30000);
715 /* Reset device to get a clean state. */
716 s
->regs
->cc
= cpu_to_le32(le32_to_cpu(s
->regs
->cc
) & 0xFE);
717 /* Wait for CSTS.RDY = 0. */
718 deadline
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + timeout_ms
* 1000000ULL;
719 while (le32_to_cpu(s
->regs
->csts
) & 0x1) {
720 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
721 error_setg(errp
, "Timeout while waiting for device to reset (%"
729 /* Set up admin queue. */
730 s
->queues
= g_new(NVMeQueuePair
*, 1);
731 s
->queues
[0] = nvme_create_queue_pair(bs
, 0, NVME_QUEUE_SIZE
, errp
);
737 QEMU_BUILD_BUG_ON(NVME_QUEUE_SIZE
& 0xF000);
738 s
->regs
->aqa
= cpu_to_le32((NVME_QUEUE_SIZE
<< 16) | NVME_QUEUE_SIZE
);
739 s
->regs
->asq
= cpu_to_le64(s
->queues
[0]->sq
.iova
);
740 s
->regs
->acq
= cpu_to_le64(s
->queues
[0]->cq
.iova
);
742 /* After setting up all control registers we can enable device now. */
743 s
->regs
->cc
= cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES
) << 20) |
744 (ctz32(NVME_SQ_ENTRY_BYTES
) << 16) |
746 /* Wait for CSTS.RDY = 1. */
747 now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
748 deadline
= now
+ timeout_ms
* 1000000;
749 while (!(le32_to_cpu(s
->regs
->csts
) & 0x1)) {
750 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
751 error_setg(errp
, "Timeout while waiting for device to start (%"
759 ret
= qemu_vfio_pci_init_irq(s
->vfio
, &s
->irq_notifier
,
760 VFIO_PCI_MSIX_IRQ_INDEX
, errp
);
764 aio_set_event_notifier(bdrv_get_aio_context(bs
), &s
->irq_notifier
,
765 false, nvme_handle_event
, nvme_poll_cb
);
767 nvme_identify(bs
, namespace, &local_err
);
769 error_propagate(errp
, local_err
);
774 /* Set up command queues. */
775 if (!nvme_add_io_queue(bs
, errp
)) {
779 /* Cleaning up is done in nvme_file_open() upon error. */
783 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
785 * nvme://0000:44:00.0/1
787 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
788 * is the PCI address, and the last part is the namespace number starting from
789 * 1 according to the NVMe spec. */
790 static void nvme_parse_filename(const char *filename
, QDict
*options
,
793 int pref
= strlen("nvme://");
795 if (strlen(filename
) > pref
&& !strncmp(filename
, "nvme://", pref
)) {
796 const char *tmp
= filename
+ pref
;
798 const char *namespace;
800 const char *slash
= strchr(tmp
, '/');
802 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, tmp
);
805 device
= g_strndup(tmp
, slash
- tmp
);
806 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, device
);
808 namespace = slash
+ 1;
809 if (*namespace && qemu_strtoul(namespace, NULL
, 10, &ns
)) {
810 error_setg(errp
, "Invalid namespace '%s', positive number expected",
814 qdict_put_str(options
, NVME_BLOCK_OPT_NAMESPACE
,
815 *namespace ? namespace : "1");
819 static int nvme_enable_disable_write_cache(BlockDriverState
*bs
, bool enable
,
823 BDRVNVMeState
*s
= bs
->opaque
;
825 .opcode
= NVME_ADM_CMD_SET_FEATURES
,
826 .nsid
= cpu_to_le32(s
->nsid
),
827 .cdw10
= cpu_to_le32(0x06),
828 .cdw11
= cpu_to_le32(enable
? 0x01 : 0x00),
831 ret
= nvme_cmd_sync(bs
, s
->queues
[0], &cmd
);
833 error_setg(errp
, "Failed to configure NVMe write cache");
838 static void nvme_close(BlockDriverState
*bs
)
841 BDRVNVMeState
*s
= bs
->opaque
;
843 for (i
= 0; i
< s
->nr_queues
; ++i
) {
844 nvme_free_queue_pair(s
->queues
[i
]);
847 aio_set_event_notifier(bdrv_get_aio_context(bs
), &s
->irq_notifier
,
849 event_notifier_cleanup(&s
->irq_notifier
);
850 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)s
->regs
, 0, NVME_BAR_SIZE
);
851 qemu_vfio_close(s
->vfio
);
856 static int nvme_file_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
863 BDRVNVMeState
*s
= bs
->opaque
;
865 bs
->supported_write_flags
= BDRV_REQ_FUA
;
867 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
868 qemu_opts_absorb_qdict(opts
, options
, &error_abort
);
869 device
= qemu_opt_get(opts
, NVME_BLOCK_OPT_DEVICE
);
871 error_setg(errp
, "'" NVME_BLOCK_OPT_DEVICE
"' option is required");
876 namespace = qemu_opt_get_number(opts
, NVME_BLOCK_OPT_NAMESPACE
, 1);
877 ret
= nvme_init(bs
, device
, namespace, errp
);
882 if (flags
& BDRV_O_NOCACHE
) {
883 if (!s
->write_cache_supported
) {
885 "NVMe controller doesn't support write cache configuration");
888 ret
= nvme_enable_disable_write_cache(bs
, !(flags
& BDRV_O_NOCACHE
),
901 static int64_t nvme_getlength(BlockDriverState
*bs
)
903 BDRVNVMeState
*s
= bs
->opaque
;
904 return s
->nsze
<< s
->blkshift
;
907 static uint32_t nvme_get_blocksize(BlockDriverState
*bs
)
909 BDRVNVMeState
*s
= bs
->opaque
;
910 assert(s
->blkshift
>= BDRV_SECTOR_BITS
&& s
->blkshift
<= 12);
911 return UINT32_C(1) << s
->blkshift
;
914 static int nvme_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
916 uint32_t blocksize
= nvme_get_blocksize(bs
);
917 bsz
->phys
= blocksize
;
918 bsz
->log
= blocksize
;
922 /* Called with s->dma_map_lock */
923 static coroutine_fn
int nvme_cmd_unmap_qiov(BlockDriverState
*bs
,
927 BDRVNVMeState
*s
= bs
->opaque
;
929 s
->dma_map_count
-= qiov
->size
;
930 if (!s
->dma_map_count
&& !qemu_co_queue_empty(&s
->dma_flush_queue
)) {
931 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
933 qemu_co_queue_restart_all(&s
->dma_flush_queue
);
939 /* Called with s->dma_map_lock */
940 static coroutine_fn
int nvme_cmd_map_qiov(BlockDriverState
*bs
, NvmeCmd
*cmd
,
941 NVMeRequest
*req
, QEMUIOVector
*qiov
)
943 BDRVNVMeState
*s
= bs
->opaque
;
944 uint64_t *pagelist
= req
->prp_list_page
;
949 assert(QEMU_IS_ALIGNED(qiov
->size
, s
->page_size
));
950 assert(qiov
->size
/ s
->page_size
<= s
->page_size
/ sizeof(uint64_t));
951 for (i
= 0; i
< qiov
->niov
; ++i
) {
955 r
= qemu_vfio_dma_map(s
->vfio
,
956 qiov
->iov
[i
].iov_base
,
957 qiov
->iov
[i
].iov_len
,
959 if (r
== -ENOMEM
&& retry
) {
961 trace_nvme_dma_flush_queue_wait(s
);
962 if (s
->dma_map_count
) {
963 trace_nvme_dma_map_flush(s
);
964 qemu_co_queue_wait(&s
->dma_flush_queue
, &s
->dma_map_lock
);
966 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
977 for (j
= 0; j
< qiov
->iov
[i
].iov_len
/ s
->page_size
; j
++) {
978 pagelist
[entries
++] = cpu_to_le64(iova
+ j
* s
->page_size
);
980 trace_nvme_cmd_map_qiov_iov(s
, i
, qiov
->iov
[i
].iov_base
,
981 qiov
->iov
[i
].iov_len
/ s
->page_size
);
984 s
->dma_map_count
+= qiov
->size
;
986 assert(entries
<= s
->page_size
/ sizeof(uint64_t));
991 cmd
->dptr
.prp1
= pagelist
[0];
995 cmd
->dptr
.prp1
= pagelist
[0];
996 cmd
->dptr
.prp2
= pagelist
[1];
999 cmd
->dptr
.prp1
= pagelist
[0];
1000 cmd
->dptr
.prp2
= cpu_to_le64(req
->prp_list_iova
+ sizeof(uint64_t));
1003 trace_nvme_cmd_map_qiov(s
, cmd
, req
, qiov
, entries
);
1004 for (i
= 0; i
< entries
; ++i
) {
1005 trace_nvme_cmd_map_qiov_pages(s
, i
, pagelist
[i
]);
1009 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1010 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1011 * because they are already mapped before calling this function; for
1012 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1013 * calling qemu_vfio_dma_reset_temporary when necessary. */
1023 static void nvme_rw_cb_bh(void *opaque
)
1025 NVMeCoData
*data
= opaque
;
1026 qemu_coroutine_enter(data
->co
);
1029 static void nvme_rw_cb(void *opaque
, int ret
)
1031 NVMeCoData
*data
= opaque
;
1034 /* The rw coroutine hasn't yielded, don't try to enter. */
1037 replay_bh_schedule_oneshot_event(data
->ctx
, nvme_rw_cb_bh
, data
);
1040 static coroutine_fn
int nvme_co_prw_aligned(BlockDriverState
*bs
,
1041 uint64_t offset
, uint64_t bytes
,
1047 BDRVNVMeState
*s
= bs
->opaque
;
1048 NVMeQueuePair
*ioq
= s
->queues
[1];
1051 uint32_t cdw12
= (((bytes
>> s
->blkshift
) - 1) & 0xFFFF) |
1052 (flags
& BDRV_REQ_FUA
? 1 << 30 : 0);
1054 .opcode
= is_write
? NVME_CMD_WRITE
: NVME_CMD_READ
,
1055 .nsid
= cpu_to_le32(s
->nsid
),
1056 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1057 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1058 .cdw12
= cpu_to_le32(cdw12
),
1061 .ctx
= bdrv_get_aio_context(bs
),
1062 .ret
= -EINPROGRESS
,
1065 trace_nvme_prw_aligned(s
, is_write
, offset
, bytes
, flags
, qiov
->niov
);
1066 assert(s
->nr_queues
> 1);
1067 req
= nvme_get_free_req(ioq
);
1070 qemu_co_mutex_lock(&s
->dma_map_lock
);
1071 r
= nvme_cmd_map_qiov(bs
, &cmd
, req
, qiov
);
1072 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1074 nvme_put_free_req_and_wake(ioq
, req
);
1077 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1079 data
.co
= qemu_coroutine_self();
1080 while (data
.ret
== -EINPROGRESS
) {
1081 qemu_coroutine_yield();
1084 qemu_co_mutex_lock(&s
->dma_map_lock
);
1085 r
= nvme_cmd_unmap_qiov(bs
, qiov
);
1086 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1091 trace_nvme_rw_done(s
, is_write
, offset
, bytes
, data
.ret
);
1095 static inline bool nvme_qiov_aligned(BlockDriverState
*bs
,
1096 const QEMUIOVector
*qiov
)
1099 BDRVNVMeState
*s
= bs
->opaque
;
1101 for (i
= 0; i
< qiov
->niov
; ++i
) {
1102 if (!QEMU_PTR_IS_ALIGNED(qiov
->iov
[i
].iov_base
, s
->page_size
) ||
1103 !QEMU_IS_ALIGNED(qiov
->iov
[i
].iov_len
, s
->page_size
)) {
1104 trace_nvme_qiov_unaligned(qiov
, i
, qiov
->iov
[i
].iov_base
,
1105 qiov
->iov
[i
].iov_len
, s
->page_size
);
1112 static int nvme_co_prw(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1113 QEMUIOVector
*qiov
, bool is_write
, int flags
)
1115 BDRVNVMeState
*s
= bs
->opaque
;
1117 uint8_t *buf
= NULL
;
1118 QEMUIOVector local_qiov
;
1120 assert(QEMU_IS_ALIGNED(offset
, s
->page_size
));
1121 assert(QEMU_IS_ALIGNED(bytes
, s
->page_size
));
1122 assert(bytes
<= s
->max_transfer
);
1123 if (nvme_qiov_aligned(bs
, qiov
)) {
1124 return nvme_co_prw_aligned(bs
, offset
, bytes
, qiov
, is_write
, flags
);
1126 trace_nvme_prw_buffered(s
, offset
, bytes
, qiov
->niov
, is_write
);
1127 buf
= qemu_try_blockalign(bs
, bytes
);
1132 qemu_iovec_init(&local_qiov
, 1);
1134 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
1136 qemu_iovec_add(&local_qiov
, buf
, bytes
);
1137 r
= nvme_co_prw_aligned(bs
, offset
, bytes
, &local_qiov
, is_write
, flags
);
1138 qemu_iovec_destroy(&local_qiov
);
1139 if (!r
&& !is_write
) {
1140 qemu_iovec_from_buf(qiov
, 0, buf
, bytes
);
1146 static coroutine_fn
int nvme_co_preadv(BlockDriverState
*bs
,
1147 uint64_t offset
, uint64_t bytes
,
1148 QEMUIOVector
*qiov
, int flags
)
1150 return nvme_co_prw(bs
, offset
, bytes
, qiov
, false, flags
);
1153 static coroutine_fn
int nvme_co_pwritev(BlockDriverState
*bs
,
1154 uint64_t offset
, uint64_t bytes
,
1155 QEMUIOVector
*qiov
, int flags
)
1157 return nvme_co_prw(bs
, offset
, bytes
, qiov
, true, flags
);
1160 static coroutine_fn
int nvme_co_flush(BlockDriverState
*bs
)
1162 BDRVNVMeState
*s
= bs
->opaque
;
1163 NVMeQueuePair
*ioq
= s
->queues
[1];
1166 .opcode
= NVME_CMD_FLUSH
,
1167 .nsid
= cpu_to_le32(s
->nsid
),
1170 .ctx
= bdrv_get_aio_context(bs
),
1171 .ret
= -EINPROGRESS
,
1174 assert(s
->nr_queues
> 1);
1175 req
= nvme_get_free_req(ioq
);
1177 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1179 data
.co
= qemu_coroutine_self();
1180 if (data
.ret
== -EINPROGRESS
) {
1181 qemu_coroutine_yield();
1188 static coroutine_fn
int nvme_co_pwrite_zeroes(BlockDriverState
*bs
,
1191 BdrvRequestFlags flags
)
1193 BDRVNVMeState
*s
= bs
->opaque
;
1194 NVMeQueuePair
*ioq
= s
->queues
[1];
1197 uint32_t cdw12
= ((bytes
>> s
->blkshift
) - 1) & 0xFFFF;
1199 if (!s
->supports_write_zeroes
) {
1204 .opcode
= NVME_CMD_WRITE_ZEROES
,
1205 .nsid
= cpu_to_le32(s
->nsid
),
1206 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1207 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1211 .ctx
= bdrv_get_aio_context(bs
),
1212 .ret
= -EINPROGRESS
,
1215 if (flags
& BDRV_REQ_MAY_UNMAP
) {
1219 if (flags
& BDRV_REQ_FUA
) {
1223 cmd
.cdw12
= cpu_to_le32(cdw12
);
1225 trace_nvme_write_zeroes(s
, offset
, bytes
, flags
);
1226 assert(s
->nr_queues
> 1);
1227 req
= nvme_get_free_req(ioq
);
1230 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1232 data
.co
= qemu_coroutine_self();
1233 while (data
.ret
== -EINPROGRESS
) {
1234 qemu_coroutine_yield();
1237 trace_nvme_rw_done(s
, true, offset
, bytes
, data
.ret
);
1242 static int coroutine_fn
nvme_co_pdiscard(BlockDriverState
*bs
,
1246 BDRVNVMeState
*s
= bs
->opaque
;
1247 NVMeQueuePair
*ioq
= s
->queues
[1];
1250 QEMUIOVector local_qiov
;
1254 .opcode
= NVME_CMD_DSM
,
1255 .nsid
= cpu_to_le32(s
->nsid
),
1256 .cdw10
= cpu_to_le32(0), /*number of ranges - 0 based*/
1257 .cdw11
= cpu_to_le32(1 << 2), /*deallocate bit*/
1261 .ctx
= bdrv_get_aio_context(bs
),
1262 .ret
= -EINPROGRESS
,
1265 if (!s
->supports_discard
) {
1269 assert(s
->nr_queues
> 1);
1271 buf
= qemu_try_blockalign0(bs
, s
->page_size
);
1276 buf
->nlb
= cpu_to_le32(bytes
>> s
->blkshift
);
1277 buf
->slba
= cpu_to_le64(offset
>> s
->blkshift
);
1280 qemu_iovec_init(&local_qiov
, 1);
1281 qemu_iovec_add(&local_qiov
, buf
, 4096);
1283 req
= nvme_get_free_req(ioq
);
1286 qemu_co_mutex_lock(&s
->dma_map_lock
);
1287 ret
= nvme_cmd_map_qiov(bs
, &cmd
, req
, &local_qiov
);
1288 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1291 nvme_put_free_req_and_wake(ioq
, req
);
1295 trace_nvme_dsm(s
, offset
, bytes
);
1297 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1299 data
.co
= qemu_coroutine_self();
1300 while (data
.ret
== -EINPROGRESS
) {
1301 qemu_coroutine_yield();
1304 qemu_co_mutex_lock(&s
->dma_map_lock
);
1305 ret
= nvme_cmd_unmap_qiov(bs
, &local_qiov
);
1306 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1313 trace_nvme_dsm_done(s
, offset
, bytes
, ret
);
1315 qemu_iovec_destroy(&local_qiov
);
1322 static int nvme_reopen_prepare(BDRVReopenState
*reopen_state
,
1323 BlockReopenQueue
*queue
, Error
**errp
)
1328 static void nvme_refresh_filename(BlockDriverState
*bs
)
1330 BDRVNVMeState
*s
= bs
->opaque
;
1332 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
), "nvme://%s/%i",
1333 s
->device
, s
->nsid
);
1336 static void nvme_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1338 BDRVNVMeState
*s
= bs
->opaque
;
1340 bs
->bl
.opt_mem_alignment
= s
->page_size
;
1341 bs
->bl
.request_alignment
= s
->page_size
;
1342 bs
->bl
.max_transfer
= s
->max_transfer
;
1345 static void nvme_detach_aio_context(BlockDriverState
*bs
)
1347 BDRVNVMeState
*s
= bs
->opaque
;
1349 for (int i
= 0; i
< s
->nr_queues
; i
++) {
1350 NVMeQueuePair
*q
= s
->queues
[i
];
1352 qemu_bh_delete(q
->completion_bh
);
1353 q
->completion_bh
= NULL
;
1356 aio_set_event_notifier(bdrv_get_aio_context(bs
), &s
->irq_notifier
,
1360 static void nvme_attach_aio_context(BlockDriverState
*bs
,
1361 AioContext
*new_context
)
1363 BDRVNVMeState
*s
= bs
->opaque
;
1365 s
->aio_context
= new_context
;
1366 aio_set_event_notifier(new_context
, &s
->irq_notifier
,
1367 false, nvme_handle_event
, nvme_poll_cb
);
1369 for (int i
= 0; i
< s
->nr_queues
; i
++) {
1370 NVMeQueuePair
*q
= s
->queues
[i
];
1373 aio_bh_new(new_context
, nvme_process_completion_bh
, q
);
1377 static void nvme_aio_plug(BlockDriverState
*bs
)
1379 BDRVNVMeState
*s
= bs
->opaque
;
1380 assert(!s
->plugged
);
1384 static void nvme_aio_unplug(BlockDriverState
*bs
)
1387 BDRVNVMeState
*s
= bs
->opaque
;
1390 for (i
= 1; i
< s
->nr_queues
; i
++) {
1391 NVMeQueuePair
*q
= s
->queues
[i
];
1392 qemu_mutex_lock(&q
->lock
);
1394 nvme_process_completion(q
);
1395 qemu_mutex_unlock(&q
->lock
);
1399 static void nvme_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
1402 BDRVNVMeState
*s
= bs
->opaque
;
1404 ret
= qemu_vfio_dma_map(s
->vfio
, host
, size
, false, NULL
);
1406 /* FIXME: we may run out of IOVA addresses after repeated
1407 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1408 * doesn't reclaim addresses for fixed mappings. */
1409 error_report("nvme_register_buf failed: %s", strerror(-ret
));
1413 static void nvme_unregister_buf(BlockDriverState
*bs
, void *host
)
1415 BDRVNVMeState
*s
= bs
->opaque
;
1417 qemu_vfio_dma_unmap(s
->vfio
, host
);
1420 static const char *const nvme_strong_runtime_opts
[] = {
1421 NVME_BLOCK_OPT_DEVICE
,
1422 NVME_BLOCK_OPT_NAMESPACE
,
1427 static BlockDriver bdrv_nvme
= {
1428 .format_name
= "nvme",
1429 .protocol_name
= "nvme",
1430 .instance_size
= sizeof(BDRVNVMeState
),
1432 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
1433 .create_opts
= &bdrv_create_opts_simple
,
1435 .bdrv_parse_filename
= nvme_parse_filename
,
1436 .bdrv_file_open
= nvme_file_open
,
1437 .bdrv_close
= nvme_close
,
1438 .bdrv_getlength
= nvme_getlength
,
1439 .bdrv_probe_blocksizes
= nvme_probe_blocksizes
,
1441 .bdrv_co_preadv
= nvme_co_preadv
,
1442 .bdrv_co_pwritev
= nvme_co_pwritev
,
1444 .bdrv_co_pwrite_zeroes
= nvme_co_pwrite_zeroes
,
1445 .bdrv_co_pdiscard
= nvme_co_pdiscard
,
1447 .bdrv_co_flush_to_disk
= nvme_co_flush
,
1448 .bdrv_reopen_prepare
= nvme_reopen_prepare
,
1450 .bdrv_refresh_filename
= nvme_refresh_filename
,
1451 .bdrv_refresh_limits
= nvme_refresh_limits
,
1452 .strong_runtime_opts
= nvme_strong_runtime_opts
,
1454 .bdrv_detach_aio_context
= nvme_detach_aio_context
,
1455 .bdrv_attach_aio_context
= nvme_attach_aio_context
,
1457 .bdrv_io_plug
= nvme_aio_plug
,
1458 .bdrv_io_unplug
= nvme_aio_unplug
,
1460 .bdrv_register_buf
= nvme_register_buf
,
1461 .bdrv_unregister_buf
= nvme_unregister_buf
,
1464 static void bdrv_nvme_init(void)
1466 bdrv_register(&bdrv_nvme
);
1469 block_init(bdrv_nvme_init
);