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"
28 #include "block/nvme.h"
30 #define NVME_SQ_ENTRY_BYTES 64
31 #define NVME_CQ_ENTRY_BYTES 16
32 #define NVME_QUEUE_SIZE 128
33 #define NVME_BAR_SIZE 8192
39 /* Hardware MMIO register */
40 volatile uint32_t *doorbell
;
44 BlockCompletionFunc
*cb
;
48 uint64_t prp_list_iova
;
53 CoQueue free_req_queue
;
56 /* Fields protected by BQL */
58 uint8_t *prp_list_pages
;
60 /* Fields protected by @lock */
63 NVMeRequest reqs
[NVME_QUEUE_SIZE
];
69 /* Memory mapped registers */
70 typedef volatile struct {
84 uint8_t reserved1
[0xec0];
85 uint8_t cmd_set_specfic
[0x100];
89 QEMU_BUILD_BUG_ON(offsetof(NVMeRegs
, doorbells
) != 0x1000);
92 AioContext
*aio_context
;
95 /* The submission/completion queue pairs.
99 NVMeQueuePair
**queues
;
102 /* How many uint32_t elements does each doorbell entry take. */
103 size_t doorbell_scale
;
104 bool write_cache_supported
;
105 EventNotifier irq_notifier
;
107 uint64_t nsze
; /* Namespace size reported by identify command */
108 int nsid
; /* The namespace id to read/write data. */
111 uint64_t max_transfer
;
114 CoMutex dma_map_lock
;
115 CoQueue dma_flush_queue
;
117 /* Total size of mapped qiov, accessed under dma_map_lock */
120 /* PCI address (required for nvme_refresh_filename()) */
124 #define NVME_BLOCK_OPT_DEVICE "device"
125 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
127 static QemuOptsList runtime_opts
= {
129 .head
= QTAILQ_HEAD_INITIALIZER(runtime_opts
.head
),
132 .name
= NVME_BLOCK_OPT_DEVICE
,
133 .type
= QEMU_OPT_STRING
,
134 .help
= "NVMe PCI device address",
137 .name
= NVME_BLOCK_OPT_NAMESPACE
,
138 .type
= QEMU_OPT_NUMBER
,
139 .help
= "NVMe namespace",
141 { /* end of list */ }
145 static void nvme_init_queue(BlockDriverState
*bs
, NVMeQueue
*q
,
146 int nentries
, int entry_bytes
, Error
**errp
)
148 BDRVNVMeState
*s
= bs
->opaque
;
152 bytes
= ROUND_UP(nentries
* entry_bytes
, s
->page_size
);
153 q
->head
= q
->tail
= 0;
154 q
->queue
= qemu_try_blockalign0(bs
, bytes
);
157 error_setg(errp
, "Cannot allocate queue");
160 r
= qemu_vfio_dma_map(s
->vfio
, q
->queue
, bytes
, false, &q
->iova
);
162 error_setg(errp
, "Cannot map queue");
166 static void nvme_free_queue_pair(BlockDriverState
*bs
, NVMeQueuePair
*q
)
168 qemu_vfree(q
->prp_list_pages
);
169 qemu_vfree(q
->sq
.queue
);
170 qemu_vfree(q
->cq
.queue
);
171 qemu_mutex_destroy(&q
->lock
);
175 static void nvme_free_req_queue_cb(void *opaque
)
177 NVMeQueuePair
*q
= opaque
;
179 qemu_mutex_lock(&q
->lock
);
180 while (qemu_co_enter_next(&q
->free_req_queue
, &q
->lock
)) {
181 /* Retry all pending requests */
183 qemu_mutex_unlock(&q
->lock
);
186 static NVMeQueuePair
*nvme_create_queue_pair(BlockDriverState
*bs
,
191 BDRVNVMeState
*s
= bs
->opaque
;
192 Error
*local_err
= NULL
;
193 NVMeQueuePair
*q
= g_new0(NVMeQueuePair
, 1);
194 uint64_t prp_list_iova
;
196 qemu_mutex_init(&q
->lock
);
198 qemu_co_queue_init(&q
->free_req_queue
);
199 q
->prp_list_pages
= qemu_blockalign0(bs
, s
->page_size
* NVME_QUEUE_SIZE
);
200 r
= qemu_vfio_dma_map(s
->vfio
, q
->prp_list_pages
,
201 s
->page_size
* NVME_QUEUE_SIZE
,
202 false, &prp_list_iova
);
206 for (i
= 0; i
< NVME_QUEUE_SIZE
; i
++) {
207 NVMeRequest
*req
= &q
->reqs
[i
];
209 req
->prp_list_page
= q
->prp_list_pages
+ i
* s
->page_size
;
210 req
->prp_list_iova
= prp_list_iova
+ i
* s
->page_size
;
212 nvme_init_queue(bs
, &q
->sq
, size
, NVME_SQ_ENTRY_BYTES
, &local_err
);
214 error_propagate(errp
, local_err
);
217 q
->sq
.doorbell
= &s
->regs
->doorbells
[idx
* 2 * s
->doorbell_scale
];
219 nvme_init_queue(bs
, &q
->cq
, size
, NVME_CQ_ENTRY_BYTES
, &local_err
);
221 error_propagate(errp
, local_err
);
224 q
->cq
.doorbell
= &s
->regs
->doorbells
[(idx
* 2 + 1) * s
->doorbell_scale
];
228 nvme_free_queue_pair(bs
, q
);
233 static void nvme_kick(BDRVNVMeState
*s
, NVMeQueuePair
*q
)
235 if (s
->plugged
|| !q
->need_kick
) {
238 trace_nvme_kick(s
, q
->index
);
239 assert(!(q
->sq
.tail
& 0xFF00));
240 /* Fence the write to submission queue entry before notifying the device. */
242 *q
->sq
.doorbell
= cpu_to_le32(q
->sq
.tail
);
243 q
->inflight
+= q
->need_kick
;
247 /* Find a free request element if any, otherwise:
248 * a) if in coroutine context, try to wait for one to become available;
249 * b) if not in coroutine, return NULL;
251 static NVMeRequest
*nvme_get_free_req(NVMeQueuePair
*q
)
254 NVMeRequest
*req
= NULL
;
256 qemu_mutex_lock(&q
->lock
);
257 while (q
->inflight
+ q
->need_kick
> NVME_QUEUE_SIZE
- 2) {
258 /* We have to leave one slot empty as that is the full queue case (head
260 if (qemu_in_coroutine()) {
261 trace_nvme_free_req_queue_wait(q
);
262 qemu_co_queue_wait(&q
->free_req_queue
, &q
->lock
);
264 qemu_mutex_unlock(&q
->lock
);
268 for (i
= 0; i
< NVME_QUEUE_SIZE
; i
++) {
269 if (!q
->reqs
[i
].busy
) {
270 q
->reqs
[i
].busy
= true;
275 /* We have checked inflight and need_kick while holding q->lock, so one
276 * free req must be available. */
278 qemu_mutex_unlock(&q
->lock
);
282 static inline int nvme_translate_error(const NvmeCqe
*c
)
284 uint16_t status
= (le16_to_cpu(c
->status
) >> 1) & 0xFF;
286 trace_nvme_error(le32_to_cpu(c
->result
),
287 le16_to_cpu(c
->sq_head
),
288 le16_to_cpu(c
->sq_id
),
290 le16_to_cpu(status
));
305 static bool nvme_process_completion(BDRVNVMeState
*s
, NVMeQueuePair
*q
)
307 bool progress
= false;
312 trace_nvme_process_completion(s
, q
->index
, q
->inflight
);
313 if (q
->busy
|| s
->plugged
) {
314 trace_nvme_process_completion_queue_busy(s
, q
->index
);
318 assert(q
->inflight
>= 0);
319 while (q
->inflight
) {
321 c
= (NvmeCqe
*)&q
->cq
.queue
[q
->cq
.head
* NVME_CQ_ENTRY_BYTES
];
322 if ((le16_to_cpu(c
->status
) & 0x1) == q
->cq_phase
) {
325 q
->cq
.head
= (q
->cq
.head
+ 1) % NVME_QUEUE_SIZE
;
327 q
->cq_phase
= !q
->cq_phase
;
329 cid
= le16_to_cpu(c
->cid
);
330 if (cid
== 0 || cid
> NVME_QUEUE_SIZE
) {
331 fprintf(stderr
, "Unexpected CID in completion queue: %" PRIu32
"\n",
335 assert(cid
<= NVME_QUEUE_SIZE
);
336 trace_nvme_complete_command(s
, q
->index
, cid
);
337 preq
= &q
->reqs
[cid
- 1];
339 assert(req
.cid
== cid
);
342 preq
->cb
= preq
->opaque
= NULL
;
343 qemu_mutex_unlock(&q
->lock
);
344 req
.cb(req
.opaque
, nvme_translate_error(c
));
345 qemu_mutex_lock(&q
->lock
);
350 /* Notify the device so it can post more completions. */
352 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
353 if (!qemu_co_queue_empty(&q
->free_req_queue
)) {
354 aio_bh_schedule_oneshot(s
->aio_context
, nvme_free_req_queue_cb
, q
);
361 static void nvme_trace_command(const NvmeCmd
*cmd
)
365 for (i
= 0; i
< 8; ++i
) {
366 uint8_t *cmdp
= (uint8_t *)cmd
+ i
* 8;
367 trace_nvme_submit_command_raw(cmdp
[0], cmdp
[1], cmdp
[2], cmdp
[3],
368 cmdp
[4], cmdp
[5], cmdp
[6], cmdp
[7]);
372 static void nvme_submit_command(BDRVNVMeState
*s
, NVMeQueuePair
*q
,
374 NvmeCmd
*cmd
, BlockCompletionFunc cb
,
379 req
->opaque
= opaque
;
380 cmd
->cid
= cpu_to_le32(req
->cid
);
382 trace_nvme_submit_command(s
, q
->index
, req
->cid
);
383 nvme_trace_command(cmd
);
384 qemu_mutex_lock(&q
->lock
);
385 memcpy((uint8_t *)q
->sq
.queue
+
386 q
->sq
.tail
* NVME_SQ_ENTRY_BYTES
, cmd
, sizeof(*cmd
));
387 q
->sq
.tail
= (q
->sq
.tail
+ 1) % NVME_QUEUE_SIZE
;
390 nvme_process_completion(s
, q
);
391 qemu_mutex_unlock(&q
->lock
);
394 static void nvme_cmd_sync_cb(void *opaque
, int ret
)
401 static int nvme_cmd_sync(BlockDriverState
*bs
, NVMeQueuePair
*q
,
405 BDRVNVMeState
*s
= bs
->opaque
;
406 int ret
= -EINPROGRESS
;
407 req
= nvme_get_free_req(q
);
411 nvme_submit_command(s
, q
, req
, cmd
, nvme_cmd_sync_cb
, &ret
);
413 BDRV_POLL_WHILE(bs
, ret
== -EINPROGRESS
);
417 static void nvme_identify(BlockDriverState
*bs
, int namespace, Error
**errp
)
419 BDRVNVMeState
*s
= bs
->opaque
;
427 .opcode
= NVME_ADM_CMD_IDENTIFY
,
428 .cdw10
= cpu_to_le32(0x1),
431 resp
= qemu_try_blockalign0(bs
, sizeof(NvmeIdCtrl
));
433 error_setg(errp
, "Cannot allocate buffer for identify response");
436 idctrl
= (NvmeIdCtrl
*)resp
;
437 idns
= (NvmeIdNs
*)resp
;
438 r
= qemu_vfio_dma_map(s
->vfio
, resp
, sizeof(NvmeIdCtrl
), true, &iova
);
440 error_setg(errp
, "Cannot map buffer for DMA");
443 cmd
.prp1
= cpu_to_le64(iova
);
445 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
446 error_setg(errp
, "Failed to identify controller");
450 if (le32_to_cpu(idctrl
->nn
) < namespace) {
451 error_setg(errp
, "Invalid namespace");
454 s
->write_cache_supported
= le32_to_cpu(idctrl
->vwc
) & 0x1;
455 s
->max_transfer
= (idctrl
->mdts
? 1 << idctrl
->mdts
: 0) * s
->page_size
;
456 /* For now the page list buffer per command is one page, to hold at most
457 * s->page_size / sizeof(uint64_t) entries. */
458 s
->max_transfer
= MIN_NON_ZERO(s
->max_transfer
,
459 s
->page_size
/ sizeof(uint64_t) * s
->page_size
);
461 memset(resp
, 0, 4096);
464 cmd
.nsid
= cpu_to_le32(namespace);
465 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
466 error_setg(errp
, "Failed to identify namespace");
470 s
->nsze
= le64_to_cpu(idns
->nsze
);
471 lbaf
= &idns
->lbaf
[NVME_ID_NS_FLBAS_INDEX(idns
->flbas
)];
474 error_setg(errp
, "Namespaces with metadata are not yet supported");
478 if (lbaf
->ds
< BDRV_SECTOR_BITS
|| lbaf
->ds
> 12 ||
479 (1 << lbaf
->ds
) > s
->page_size
)
481 error_setg(errp
, "Namespace has unsupported block size (2^%d)",
486 s
->blkshift
= lbaf
->ds
;
488 qemu_vfio_dma_unmap(s
->vfio
, resp
);
492 static bool nvme_poll_queues(BDRVNVMeState
*s
)
494 bool progress
= false;
497 for (i
= 0; i
< s
->nr_queues
; i
++) {
498 NVMeQueuePair
*q
= s
->queues
[i
];
499 qemu_mutex_lock(&q
->lock
);
500 while (nvme_process_completion(s
, q
)) {
504 qemu_mutex_unlock(&q
->lock
);
509 static void nvme_handle_event(EventNotifier
*n
)
511 BDRVNVMeState
*s
= container_of(n
, BDRVNVMeState
, irq_notifier
);
513 trace_nvme_handle_event(s
);
514 event_notifier_test_and_clear(n
);
518 static bool nvme_add_io_queue(BlockDriverState
*bs
, Error
**errp
)
520 BDRVNVMeState
*s
= bs
->opaque
;
521 int n
= s
->nr_queues
;
524 int queue_size
= NVME_QUEUE_SIZE
;
526 q
= nvme_create_queue_pair(bs
, n
, queue_size
, errp
);
531 .opcode
= NVME_ADM_CMD_CREATE_CQ
,
532 .prp1
= cpu_to_le64(q
->cq
.iova
),
533 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | (n
& 0xFFFF)),
534 .cdw11
= cpu_to_le32(0x3),
536 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
537 error_setg(errp
, "Failed to create io queue [%d]", n
);
538 nvme_free_queue_pair(bs
, q
);
542 .opcode
= NVME_ADM_CMD_CREATE_SQ
,
543 .prp1
= cpu_to_le64(q
->sq
.iova
),
544 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | (n
& 0xFFFF)),
545 .cdw11
= cpu_to_le32(0x1 | (n
<< 16)),
547 if (nvme_cmd_sync(bs
, s
->queues
[0], &cmd
)) {
548 error_setg(errp
, "Failed to create io queue [%d]", n
);
549 nvme_free_queue_pair(bs
, q
);
552 s
->queues
= g_renew(NVMeQueuePair
*, s
->queues
, n
+ 1);
558 static bool nvme_poll_cb(void *opaque
)
560 EventNotifier
*e
= opaque
;
561 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
, irq_notifier
);
562 bool progress
= false;
564 trace_nvme_poll_cb(s
);
565 progress
= nvme_poll_queues(s
);
569 static int nvme_init(BlockDriverState
*bs
, const char *device
, int namespace,
572 BDRVNVMeState
*s
= bs
->opaque
;
576 uint64_t deadline
, now
;
577 Error
*local_err
= NULL
;
579 qemu_co_mutex_init(&s
->dma_map_lock
);
580 qemu_co_queue_init(&s
->dma_flush_queue
);
581 s
->device
= g_strdup(device
);
583 s
->aio_context
= bdrv_get_aio_context(bs
);
584 ret
= event_notifier_init(&s
->irq_notifier
, 0);
586 error_setg(errp
, "Failed to init event notifier");
590 s
->vfio
= qemu_vfio_open_pci(device
, errp
);
596 s
->regs
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0, NVME_BAR_SIZE
, errp
);
602 /* Perform initialize sequence as described in NVMe spec "7.6.1
603 * Initialization". */
605 cap
= le64_to_cpu(s
->regs
->cap
);
606 if (!(cap
& (1ULL << 37))) {
607 error_setg(errp
, "Device doesn't support NVMe command set");
612 s
->page_size
= MAX(4096, 1 << (12 + ((cap
>> 48) & 0xF)));
613 s
->doorbell_scale
= (4 << (((cap
>> 32) & 0xF))) / sizeof(uint32_t);
614 bs
->bl
.opt_mem_alignment
= s
->page_size
;
615 timeout_ms
= MIN(500 * ((cap
>> 24) & 0xFF), 30000);
617 /* Reset device to get a clean state. */
618 s
->regs
->cc
= cpu_to_le32(le32_to_cpu(s
->regs
->cc
) & 0xFE);
619 /* Wait for CSTS.RDY = 0. */
620 deadline
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + timeout_ms
* 1000000ULL;
621 while (le32_to_cpu(s
->regs
->csts
) & 0x1) {
622 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
623 error_setg(errp
, "Timeout while waiting for device to reset (%"
631 /* Set up admin queue. */
632 s
->queues
= g_new(NVMeQueuePair
*, 1);
633 s
->queues
[0] = nvme_create_queue_pair(bs
, 0, NVME_QUEUE_SIZE
, errp
);
639 QEMU_BUILD_BUG_ON(NVME_QUEUE_SIZE
& 0xF000);
640 s
->regs
->aqa
= cpu_to_le32((NVME_QUEUE_SIZE
<< 16) | NVME_QUEUE_SIZE
);
641 s
->regs
->asq
= cpu_to_le64(s
->queues
[0]->sq
.iova
);
642 s
->regs
->acq
= cpu_to_le64(s
->queues
[0]->cq
.iova
);
644 /* After setting up all control registers we can enable device now. */
645 s
->regs
->cc
= cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES
) << 20) |
646 (ctz32(NVME_SQ_ENTRY_BYTES
) << 16) |
648 /* Wait for CSTS.RDY = 1. */
649 now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
650 deadline
= now
+ timeout_ms
* 1000000;
651 while (!(le32_to_cpu(s
->regs
->csts
) & 0x1)) {
652 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
653 error_setg(errp
, "Timeout while waiting for device to start (%"
661 ret
= qemu_vfio_pci_init_irq(s
->vfio
, &s
->irq_notifier
,
662 VFIO_PCI_MSIX_IRQ_INDEX
, errp
);
666 aio_set_event_notifier(bdrv_get_aio_context(bs
), &s
->irq_notifier
,
667 false, nvme_handle_event
, nvme_poll_cb
);
669 nvme_identify(bs
, namespace, &local_err
);
671 error_propagate(errp
, local_err
);
676 /* Set up command queues. */
677 if (!nvme_add_io_queue(bs
, errp
)) {
681 /* Cleaning up is done in nvme_file_open() upon error. */
685 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
687 * nvme://0000:44:00.0/1
689 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
690 * is the PCI address, and the last part is the namespace number starting from
691 * 1 according to the NVMe spec. */
692 static void nvme_parse_filename(const char *filename
, QDict
*options
,
695 int pref
= strlen("nvme://");
697 if (strlen(filename
) > pref
&& !strncmp(filename
, "nvme://", pref
)) {
698 const char *tmp
= filename
+ pref
;
700 const char *namespace;
702 const char *slash
= strchr(tmp
, '/');
704 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, tmp
);
707 device
= g_strndup(tmp
, slash
- tmp
);
708 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, device
);
710 namespace = slash
+ 1;
711 if (*namespace && qemu_strtoul(namespace, NULL
, 10, &ns
)) {
712 error_setg(errp
, "Invalid namespace '%s', positive number expected",
716 qdict_put_str(options
, NVME_BLOCK_OPT_NAMESPACE
,
717 *namespace ? namespace : "1");
721 static int nvme_enable_disable_write_cache(BlockDriverState
*bs
, bool enable
,
725 BDRVNVMeState
*s
= bs
->opaque
;
727 .opcode
= NVME_ADM_CMD_SET_FEATURES
,
728 .nsid
= cpu_to_le32(s
->nsid
),
729 .cdw10
= cpu_to_le32(0x06),
730 .cdw11
= cpu_to_le32(enable
? 0x01 : 0x00),
733 ret
= nvme_cmd_sync(bs
, s
->queues
[0], &cmd
);
735 error_setg(errp
, "Failed to configure NVMe write cache");
740 static void nvme_close(BlockDriverState
*bs
)
743 BDRVNVMeState
*s
= bs
->opaque
;
745 for (i
= 0; i
< s
->nr_queues
; ++i
) {
746 nvme_free_queue_pair(bs
, s
->queues
[i
]);
749 aio_set_event_notifier(bdrv_get_aio_context(bs
), &s
->irq_notifier
,
751 event_notifier_cleanup(&s
->irq_notifier
);
752 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)s
->regs
, 0, NVME_BAR_SIZE
);
753 qemu_vfio_close(s
->vfio
);
758 static int nvme_file_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
765 BDRVNVMeState
*s
= bs
->opaque
;
767 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
768 qemu_opts_absorb_qdict(opts
, options
, &error_abort
);
769 device
= qemu_opt_get(opts
, NVME_BLOCK_OPT_DEVICE
);
771 error_setg(errp
, "'" NVME_BLOCK_OPT_DEVICE
"' option is required");
776 namespace = qemu_opt_get_number(opts
, NVME_BLOCK_OPT_NAMESPACE
, 1);
777 ret
= nvme_init(bs
, device
, namespace, errp
);
782 if (flags
& BDRV_O_NOCACHE
) {
783 if (!s
->write_cache_supported
) {
785 "NVMe controller doesn't support write cache configuration");
788 ret
= nvme_enable_disable_write_cache(bs
, !(flags
& BDRV_O_NOCACHE
),
795 bs
->supported_write_flags
= BDRV_REQ_FUA
;
802 static int64_t nvme_getlength(BlockDriverState
*bs
)
804 BDRVNVMeState
*s
= bs
->opaque
;
805 return s
->nsze
<< s
->blkshift
;
808 static uint32_t nvme_get_blocksize(BlockDriverState
*bs
)
810 BDRVNVMeState
*s
= bs
->opaque
;
811 assert(s
->blkshift
>= BDRV_SECTOR_BITS
&& s
->blkshift
<= 12);
812 return UINT32_C(1) << s
->blkshift
;
815 static int nvme_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
817 uint32_t blocksize
= nvme_get_blocksize(bs
);
818 bsz
->phys
= blocksize
;
819 bsz
->log
= blocksize
;
823 /* Called with s->dma_map_lock */
824 static coroutine_fn
int nvme_cmd_unmap_qiov(BlockDriverState
*bs
,
828 BDRVNVMeState
*s
= bs
->opaque
;
830 s
->dma_map_count
-= qiov
->size
;
831 if (!s
->dma_map_count
&& !qemu_co_queue_empty(&s
->dma_flush_queue
)) {
832 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
834 qemu_co_queue_restart_all(&s
->dma_flush_queue
);
840 /* Called with s->dma_map_lock */
841 static coroutine_fn
int nvme_cmd_map_qiov(BlockDriverState
*bs
, NvmeCmd
*cmd
,
842 NVMeRequest
*req
, QEMUIOVector
*qiov
)
844 BDRVNVMeState
*s
= bs
->opaque
;
845 uint64_t *pagelist
= req
->prp_list_page
;
850 assert(QEMU_IS_ALIGNED(qiov
->size
, s
->page_size
));
851 assert(qiov
->size
/ s
->page_size
<= s
->page_size
/ sizeof(uint64_t));
852 for (i
= 0; i
< qiov
->niov
; ++i
) {
856 r
= qemu_vfio_dma_map(s
->vfio
,
857 qiov
->iov
[i
].iov_base
,
858 qiov
->iov
[i
].iov_len
,
860 if (r
== -ENOMEM
&& retry
) {
862 trace_nvme_dma_flush_queue_wait(s
);
863 if (s
->dma_map_count
) {
864 trace_nvme_dma_map_flush(s
);
865 qemu_co_queue_wait(&s
->dma_flush_queue
, &s
->dma_map_lock
);
867 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
878 for (j
= 0; j
< qiov
->iov
[i
].iov_len
/ s
->page_size
; j
++) {
879 pagelist
[entries
++] = cpu_to_le64(iova
+ j
* s
->page_size
);
881 trace_nvme_cmd_map_qiov_iov(s
, i
, qiov
->iov
[i
].iov_base
,
882 qiov
->iov
[i
].iov_len
/ s
->page_size
);
885 s
->dma_map_count
+= qiov
->size
;
887 assert(entries
<= s
->page_size
/ sizeof(uint64_t));
892 cmd
->prp1
= pagelist
[0];
896 cmd
->prp1
= pagelist
[0];
897 cmd
->prp2
= pagelist
[1];
900 cmd
->prp1
= pagelist
[0];
901 cmd
->prp2
= cpu_to_le64(req
->prp_list_iova
+ sizeof(uint64_t));
904 trace_nvme_cmd_map_qiov(s
, cmd
, req
, qiov
, entries
);
905 for (i
= 0; i
< entries
; ++i
) {
906 trace_nvme_cmd_map_qiov_pages(s
, i
, pagelist
[i
]);
910 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
911 * increment s->dma_map_count. This is okay for fixed mapping memory areas
912 * because they are already mapped before calling this function; for
913 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
914 * calling qemu_vfio_dma_reset_temporary when necessary. */
924 static void nvme_rw_cb_bh(void *opaque
)
926 NVMeCoData
*data
= opaque
;
927 qemu_coroutine_enter(data
->co
);
930 static void nvme_rw_cb(void *opaque
, int ret
)
932 NVMeCoData
*data
= opaque
;
935 /* The rw coroutine hasn't yielded, don't try to enter. */
938 aio_bh_schedule_oneshot(data
->ctx
, nvme_rw_cb_bh
, data
);
941 static coroutine_fn
int nvme_co_prw_aligned(BlockDriverState
*bs
,
942 uint64_t offset
, uint64_t bytes
,
948 BDRVNVMeState
*s
= bs
->opaque
;
949 NVMeQueuePair
*ioq
= s
->queues
[1];
952 uint32_t cdw12
= (((bytes
>> s
->blkshift
) - 1) & 0xFFFF) |
953 (flags
& BDRV_REQ_FUA
? 1 << 30 : 0);
955 .opcode
= is_write
? NVME_CMD_WRITE
: NVME_CMD_READ
,
956 .nsid
= cpu_to_le32(s
->nsid
),
957 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
958 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
959 .cdw12
= cpu_to_le32(cdw12
),
962 .ctx
= bdrv_get_aio_context(bs
),
966 trace_nvme_prw_aligned(s
, is_write
, offset
, bytes
, flags
, qiov
->niov
);
967 assert(s
->nr_queues
> 1);
968 req
= nvme_get_free_req(ioq
);
971 qemu_co_mutex_lock(&s
->dma_map_lock
);
972 r
= nvme_cmd_map_qiov(bs
, &cmd
, req
, qiov
);
973 qemu_co_mutex_unlock(&s
->dma_map_lock
);
978 nvme_submit_command(s
, ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
980 data
.co
= qemu_coroutine_self();
981 while (data
.ret
== -EINPROGRESS
) {
982 qemu_coroutine_yield();
985 qemu_co_mutex_lock(&s
->dma_map_lock
);
986 r
= nvme_cmd_unmap_qiov(bs
, qiov
);
987 qemu_co_mutex_unlock(&s
->dma_map_lock
);
992 trace_nvme_rw_done(s
, is_write
, offset
, bytes
, data
.ret
);
996 static inline bool nvme_qiov_aligned(BlockDriverState
*bs
,
997 const QEMUIOVector
*qiov
)
1000 BDRVNVMeState
*s
= bs
->opaque
;
1002 for (i
= 0; i
< qiov
->niov
; ++i
) {
1003 if (!QEMU_PTR_IS_ALIGNED(qiov
->iov
[i
].iov_base
, s
->page_size
) ||
1004 !QEMU_IS_ALIGNED(qiov
->iov
[i
].iov_len
, s
->page_size
)) {
1005 trace_nvme_qiov_unaligned(qiov
, i
, qiov
->iov
[i
].iov_base
,
1006 qiov
->iov
[i
].iov_len
, s
->page_size
);
1013 static int nvme_co_prw(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1014 QEMUIOVector
*qiov
, bool is_write
, int flags
)
1016 BDRVNVMeState
*s
= bs
->opaque
;
1018 uint8_t *buf
= NULL
;
1019 QEMUIOVector local_qiov
;
1021 assert(QEMU_IS_ALIGNED(offset
, s
->page_size
));
1022 assert(QEMU_IS_ALIGNED(bytes
, s
->page_size
));
1023 assert(bytes
<= s
->max_transfer
);
1024 if (nvme_qiov_aligned(bs
, qiov
)) {
1025 return nvme_co_prw_aligned(bs
, offset
, bytes
, qiov
, is_write
, flags
);
1027 trace_nvme_prw_buffered(s
, offset
, bytes
, qiov
->niov
, is_write
);
1028 buf
= qemu_try_blockalign(bs
, bytes
);
1033 qemu_iovec_init(&local_qiov
, 1);
1035 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
1037 qemu_iovec_add(&local_qiov
, buf
, bytes
);
1038 r
= nvme_co_prw_aligned(bs
, offset
, bytes
, &local_qiov
, is_write
, flags
);
1039 qemu_iovec_destroy(&local_qiov
);
1040 if (!r
&& !is_write
) {
1041 qemu_iovec_from_buf(qiov
, 0, buf
, bytes
);
1047 static coroutine_fn
int nvme_co_preadv(BlockDriverState
*bs
,
1048 uint64_t offset
, uint64_t bytes
,
1049 QEMUIOVector
*qiov
, int flags
)
1051 return nvme_co_prw(bs
, offset
, bytes
, qiov
, false, flags
);
1054 static coroutine_fn
int nvme_co_pwritev(BlockDriverState
*bs
,
1055 uint64_t offset
, uint64_t bytes
,
1056 QEMUIOVector
*qiov
, int flags
)
1058 return nvme_co_prw(bs
, offset
, bytes
, qiov
, true, flags
);
1061 static coroutine_fn
int nvme_co_flush(BlockDriverState
*bs
)
1063 BDRVNVMeState
*s
= bs
->opaque
;
1064 NVMeQueuePair
*ioq
= s
->queues
[1];
1067 .opcode
= NVME_CMD_FLUSH
,
1068 .nsid
= cpu_to_le32(s
->nsid
),
1071 .ctx
= bdrv_get_aio_context(bs
),
1072 .ret
= -EINPROGRESS
,
1075 assert(s
->nr_queues
> 1);
1076 req
= nvme_get_free_req(ioq
);
1078 nvme_submit_command(s
, ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1080 data
.co
= qemu_coroutine_self();
1081 if (data
.ret
== -EINPROGRESS
) {
1082 qemu_coroutine_yield();
1089 static int nvme_reopen_prepare(BDRVReopenState
*reopen_state
,
1090 BlockReopenQueue
*queue
, Error
**errp
)
1095 static void nvme_refresh_filename(BlockDriverState
*bs
)
1097 BDRVNVMeState
*s
= bs
->opaque
;
1099 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
), "nvme://%s/%i",
1100 s
->device
, s
->nsid
);
1103 static void nvme_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1105 BDRVNVMeState
*s
= bs
->opaque
;
1107 bs
->bl
.opt_mem_alignment
= s
->page_size
;
1108 bs
->bl
.request_alignment
= s
->page_size
;
1109 bs
->bl
.max_transfer
= s
->max_transfer
;
1112 static void nvme_detach_aio_context(BlockDriverState
*bs
)
1114 BDRVNVMeState
*s
= bs
->opaque
;
1116 aio_set_event_notifier(bdrv_get_aio_context(bs
), &s
->irq_notifier
,
1120 static void nvme_attach_aio_context(BlockDriverState
*bs
,
1121 AioContext
*new_context
)
1123 BDRVNVMeState
*s
= bs
->opaque
;
1125 s
->aio_context
= new_context
;
1126 aio_set_event_notifier(new_context
, &s
->irq_notifier
,
1127 false, nvme_handle_event
, nvme_poll_cb
);
1130 static void nvme_aio_plug(BlockDriverState
*bs
)
1132 BDRVNVMeState
*s
= bs
->opaque
;
1133 assert(!s
->plugged
);
1137 static void nvme_aio_unplug(BlockDriverState
*bs
)
1140 BDRVNVMeState
*s
= bs
->opaque
;
1143 for (i
= 1; i
< s
->nr_queues
; i
++) {
1144 NVMeQueuePair
*q
= s
->queues
[i
];
1145 qemu_mutex_lock(&q
->lock
);
1147 nvme_process_completion(s
, q
);
1148 qemu_mutex_unlock(&q
->lock
);
1152 static void nvme_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
1155 BDRVNVMeState
*s
= bs
->opaque
;
1157 ret
= qemu_vfio_dma_map(s
->vfio
, host
, size
, false, NULL
);
1159 /* FIXME: we may run out of IOVA addresses after repeated
1160 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1161 * doesn't reclaim addresses for fixed mappings. */
1162 error_report("nvme_register_buf failed: %s", strerror(-ret
));
1166 static void nvme_unregister_buf(BlockDriverState
*bs
, void *host
)
1168 BDRVNVMeState
*s
= bs
->opaque
;
1170 qemu_vfio_dma_unmap(s
->vfio
, host
);
1173 static const char *const nvme_strong_runtime_opts
[] = {
1174 NVME_BLOCK_OPT_DEVICE
,
1175 NVME_BLOCK_OPT_NAMESPACE
,
1180 static BlockDriver bdrv_nvme
= {
1181 .format_name
= "nvme",
1182 .protocol_name
= "nvme",
1183 .instance_size
= sizeof(BDRVNVMeState
),
1185 .bdrv_parse_filename
= nvme_parse_filename
,
1186 .bdrv_file_open
= nvme_file_open
,
1187 .bdrv_close
= nvme_close
,
1188 .bdrv_getlength
= nvme_getlength
,
1189 .bdrv_probe_blocksizes
= nvme_probe_blocksizes
,
1191 .bdrv_co_preadv
= nvme_co_preadv
,
1192 .bdrv_co_pwritev
= nvme_co_pwritev
,
1193 .bdrv_co_flush_to_disk
= nvme_co_flush
,
1194 .bdrv_reopen_prepare
= nvme_reopen_prepare
,
1196 .bdrv_refresh_filename
= nvme_refresh_filename
,
1197 .bdrv_refresh_limits
= nvme_refresh_limits
,
1198 .strong_runtime_opts
= nvme_strong_runtime_opts
,
1200 .bdrv_detach_aio_context
= nvme_detach_aio_context
,
1201 .bdrv_attach_aio_context
= nvme_attach_aio_context
,
1203 .bdrv_io_plug
= nvme_aio_plug
,
1204 .bdrv_io_unplug
= nvme_aio_unplug
,
1206 .bdrv_register_buf
= nvme_register_buf
,
1207 .bdrv_unregister_buf
= nvme_unregister_buf
,
1210 static void bdrv_nvme_init(void)
1212 bdrv_register(&bdrv_nvme
);
1215 block_init(bdrv_nvme_init
);