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/memalign.h"
25 #include "qemu/vfio-helpers.h"
26 #include "block/block_int.h"
27 #include "sysemu/replay.h"
30 #include "block/nvme.h"
32 #define NVME_SQ_ENTRY_BYTES 64
33 #define NVME_CQ_ENTRY_BYTES 16
34 #define NVME_QUEUE_SIZE 128
35 #define NVME_DOORBELL_SIZE 4096
38 * We have to leave one slot empty as that is the full queue case where
41 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
43 typedef struct BDRVNVMeState BDRVNVMeState
;
45 /* Same index is used for queues and IRQs */
47 #define INDEX_IO(n) (1 + n)
49 /* This driver shares a single MSIX IRQ for the admin and I/O queues */
51 MSIX_SHARED_IRQ_IDX
= 0,
59 /* Hardware MMIO register */
60 volatile uint32_t *doorbell
;
64 BlockCompletionFunc
*cb
;
68 uint64_t prp_list_iova
;
69 int free_req_next
; /* q->reqs[] index of next free req */
75 /* Read from I/O code path, initialized under BQL */
79 /* Fields protected by BQL */
80 uint8_t *prp_list_pages
;
82 /* Fields protected by @lock */
83 CoQueue free_req_queue
;
87 NVMeRequest reqs
[NVME_NUM_REQS
];
91 /* Thread-safe, no lock necessary */
92 QEMUBH
*completion_bh
;
95 struct BDRVNVMeState
{
96 AioContext
*aio_context
;
99 /* Memory mapped registers */
104 /* The submission/completion queue pairs.
108 NVMeQueuePair
**queues
;
109 unsigned queue_count
;
111 /* How many uint32_t elements does each doorbell entry take. */
112 size_t doorbell_scale
;
113 bool write_cache_supported
;
114 EventNotifier irq_notifier
[MSIX_IRQ_COUNT
];
116 uint64_t nsze
; /* Namespace size reported by identify command */
117 int nsid
; /* The namespace id to read/write data. */
120 uint64_t max_transfer
;
123 bool supports_write_zeroes
;
124 bool supports_discard
;
126 CoMutex dma_map_lock
;
127 CoQueue dma_flush_queue
;
129 /* Total size of mapped qiov, accessed under dma_map_lock */
132 /* PCI address (required for nvme_refresh_filename()) */
136 uint64_t completion_errors
;
137 uint64_t aligned_accesses
;
138 uint64_t unaligned_accesses
;
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 /* Returns true on success, false on failure. */
166 static bool nvme_init_queue(BDRVNVMeState
*s
, NVMeQueue
*q
,
167 unsigned nentries
, size_t entry_bytes
, Error
**errp
)
172 bytes
= ROUND_UP(nentries
* entry_bytes
, qemu_real_host_page_size());
173 q
->head
= q
->tail
= 0;
174 q
->queue
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
176 error_setg(errp
, "Cannot allocate queue");
179 memset(q
->queue
, 0, bytes
);
180 r
= qemu_vfio_dma_map(s
->vfio
, q
->queue
, bytes
, false, &q
->iova
, errp
);
182 error_prepend(errp
, "Cannot map queue: ");
187 static void nvme_free_queue(NVMeQueue
*q
)
189 qemu_vfree(q
->queue
);
192 static void nvme_free_queue_pair(NVMeQueuePair
*q
)
194 trace_nvme_free_queue_pair(q
->index
, q
, &q
->cq
, &q
->sq
);
195 if (q
->completion_bh
) {
196 qemu_bh_delete(q
->completion_bh
);
198 nvme_free_queue(&q
->sq
);
199 nvme_free_queue(&q
->cq
);
200 qemu_vfree(q
->prp_list_pages
);
201 qemu_mutex_destroy(&q
->lock
);
205 static void nvme_free_req_queue_cb(void *opaque
)
207 NVMeQueuePair
*q
= opaque
;
209 qemu_mutex_lock(&q
->lock
);
210 while (q
->free_req_head
!= -1 &&
211 qemu_co_enter_next(&q
->free_req_queue
, &q
->lock
)) {
212 /* Retry waiting requests */
214 qemu_mutex_unlock(&q
->lock
);
217 static NVMeQueuePair
*nvme_create_queue_pair(BDRVNVMeState
*s
,
218 AioContext
*aio_context
,
219 unsigned idx
, size_t size
,
224 uint64_t prp_list_iova
;
227 q
= g_try_new0(NVMeQueuePair
, 1);
229 error_setg(errp
, "Cannot allocate queue pair");
232 trace_nvme_create_queue_pair(idx
, q
, size
, aio_context
,
233 event_notifier_get_fd(s
->irq_notifier
));
234 bytes
= QEMU_ALIGN_UP(s
->page_size
* NVME_NUM_REQS
,
235 qemu_real_host_page_size());
236 q
->prp_list_pages
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
237 if (!q
->prp_list_pages
) {
238 error_setg(errp
, "Cannot allocate PRP page list");
241 memset(q
->prp_list_pages
, 0, bytes
);
242 qemu_mutex_init(&q
->lock
);
245 qemu_co_queue_init(&q
->free_req_queue
);
246 q
->completion_bh
= aio_bh_new(aio_context
, nvme_process_completion_bh
, q
);
247 r
= qemu_vfio_dma_map(s
->vfio
, q
->prp_list_pages
, bytes
,
248 false, &prp_list_iova
, errp
);
250 error_prepend(errp
, "Cannot map buffer for DMA: ");
253 q
->free_req_head
= -1;
254 for (i
= 0; i
< NVME_NUM_REQS
; i
++) {
255 NVMeRequest
*req
= &q
->reqs
[i
];
257 req
->free_req_next
= q
->free_req_head
;
258 q
->free_req_head
= i
;
259 req
->prp_list_page
= q
->prp_list_pages
+ i
* s
->page_size
;
260 req
->prp_list_iova
= prp_list_iova
+ i
* s
->page_size
;
263 if (!nvme_init_queue(s
, &q
->sq
, size
, NVME_SQ_ENTRY_BYTES
, errp
)) {
266 q
->sq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].sq_tail
;
268 if (!nvme_init_queue(s
, &q
->cq
, size
, NVME_CQ_ENTRY_BYTES
, errp
)) {
271 q
->cq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].cq_head
;
275 nvme_free_queue_pair(q
);
280 static void nvme_kick(NVMeQueuePair
*q
)
282 BDRVNVMeState
*s
= q
->s
;
284 if (s
->plugged
|| !q
->need_kick
) {
287 trace_nvme_kick(s
, q
->index
);
288 assert(!(q
->sq
.tail
& 0xFF00));
289 /* Fence the write to submission queue entry before notifying the device. */
291 *q
->sq
.doorbell
= cpu_to_le32(q
->sq
.tail
);
292 q
->inflight
+= q
->need_kick
;
296 /* Find a free request element if any, otherwise:
297 * a) if in coroutine context, try to wait for one to become available;
298 * b) if not in coroutine, return NULL;
300 static NVMeRequest
*nvme_get_free_req(NVMeQueuePair
*q
)
304 qemu_mutex_lock(&q
->lock
);
306 while (q
->free_req_head
== -1) {
307 if (qemu_in_coroutine()) {
308 trace_nvme_free_req_queue_wait(q
->s
, q
->index
);
309 qemu_co_queue_wait(&q
->free_req_queue
, &q
->lock
);
311 qemu_mutex_unlock(&q
->lock
);
316 req
= &q
->reqs
[q
->free_req_head
];
317 q
->free_req_head
= req
->free_req_next
;
318 req
->free_req_next
= -1;
320 qemu_mutex_unlock(&q
->lock
);
325 static void nvme_put_free_req_locked(NVMeQueuePair
*q
, NVMeRequest
*req
)
327 req
->free_req_next
= q
->free_req_head
;
328 q
->free_req_head
= req
- q
->reqs
;
332 static void nvme_wake_free_req_locked(NVMeQueuePair
*q
)
334 if (!qemu_co_queue_empty(&q
->free_req_queue
)) {
335 replay_bh_schedule_oneshot_event(q
->s
->aio_context
,
336 nvme_free_req_queue_cb
, q
);
340 /* Insert a request in the freelist and wake waiters */
341 static void nvme_put_free_req_and_wake(NVMeQueuePair
*q
, NVMeRequest
*req
)
343 qemu_mutex_lock(&q
->lock
);
344 nvme_put_free_req_locked(q
, req
);
345 nvme_wake_free_req_locked(q
);
346 qemu_mutex_unlock(&q
->lock
);
349 static inline int nvme_translate_error(const NvmeCqe
*c
)
351 uint16_t status
= (le16_to_cpu(c
->status
) >> 1) & 0xFF;
353 trace_nvme_error(le32_to_cpu(c
->result
),
354 le16_to_cpu(c
->sq_head
),
355 le16_to_cpu(c
->sq_id
),
357 le16_to_cpu(status
));
372 static bool nvme_process_completion(NVMeQueuePair
*q
)
374 BDRVNVMeState
*s
= q
->s
;
375 bool progress
= false;
380 trace_nvme_process_completion(s
, q
->index
, q
->inflight
);
382 trace_nvme_process_completion_queue_plugged(s
, q
->index
);
387 * Support re-entrancy when a request cb() function invokes aio_poll().
388 * Pending completions must be visible to aio_poll() so that a cb()
389 * function can wait for the completion of another request.
391 * The aio_poll() loop will execute our BH and we'll resume completion
394 qemu_bh_schedule(q
->completion_bh
);
396 assert(q
->inflight
>= 0);
397 while (q
->inflight
) {
401 c
= (NvmeCqe
*)&q
->cq
.queue
[q
->cq
.head
* NVME_CQ_ENTRY_BYTES
];
402 if ((le16_to_cpu(c
->status
) & 0x1) == q
->cq_phase
) {
405 ret
= nvme_translate_error(c
);
407 s
->stats
.completion_errors
++;
409 q
->cq
.head
= (q
->cq
.head
+ 1) % NVME_QUEUE_SIZE
;
411 q
->cq_phase
= !q
->cq_phase
;
413 cid
= le16_to_cpu(c
->cid
);
414 if (cid
== 0 || cid
> NVME_QUEUE_SIZE
) {
415 warn_report("NVMe: Unexpected CID in completion queue: %"PRIu32
", "
416 "queue size: %u", cid
, NVME_QUEUE_SIZE
);
419 trace_nvme_complete_command(s
, q
->index
, cid
);
420 preq
= &q
->reqs
[cid
- 1];
422 assert(req
.cid
== cid
);
424 nvme_put_free_req_locked(q
, preq
);
425 preq
->cb
= preq
->opaque
= NULL
;
427 qemu_mutex_unlock(&q
->lock
);
428 req
.cb(req
.opaque
, ret
);
429 qemu_mutex_lock(&q
->lock
);
433 /* Notify the device so it can post more completions. */
435 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
436 nvme_wake_free_req_locked(q
);
439 qemu_bh_cancel(q
->completion_bh
);
444 static void nvme_process_completion_bh(void *opaque
)
446 NVMeQueuePair
*q
= opaque
;
449 * We're being invoked because a nvme_process_completion() cb() function
450 * called aio_poll(). The callback may be waiting for further completions
451 * so notify the device that it has space to fill in more completions now.
454 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
455 nvme_wake_free_req_locked(q
);
457 nvme_process_completion(q
);
460 static void nvme_trace_command(const NvmeCmd
*cmd
)
464 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW
)) {
467 for (i
= 0; i
< 8; ++i
) {
468 uint8_t *cmdp
= (uint8_t *)cmd
+ i
* 8;
469 trace_nvme_submit_command_raw(cmdp
[0], cmdp
[1], cmdp
[2], cmdp
[3],
470 cmdp
[4], cmdp
[5], cmdp
[6], cmdp
[7]);
474 static void nvme_submit_command(NVMeQueuePair
*q
, NVMeRequest
*req
,
475 NvmeCmd
*cmd
, BlockCompletionFunc cb
,
480 req
->opaque
= opaque
;
481 cmd
->cid
= cpu_to_le16(req
->cid
);
483 trace_nvme_submit_command(q
->s
, q
->index
, req
->cid
);
484 nvme_trace_command(cmd
);
485 qemu_mutex_lock(&q
->lock
);
486 memcpy((uint8_t *)q
->sq
.queue
+
487 q
->sq
.tail
* NVME_SQ_ENTRY_BYTES
, cmd
, sizeof(*cmd
));
488 q
->sq
.tail
= (q
->sq
.tail
+ 1) % NVME_QUEUE_SIZE
;
491 nvme_process_completion(q
);
492 qemu_mutex_unlock(&q
->lock
);
495 static void nvme_admin_cmd_sync_cb(void *opaque
, int ret
)
502 static int nvme_admin_cmd_sync(BlockDriverState
*bs
, NvmeCmd
*cmd
)
504 BDRVNVMeState
*s
= bs
->opaque
;
505 NVMeQueuePair
*q
= s
->queues
[INDEX_ADMIN
];
506 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
508 int ret
= -EINPROGRESS
;
509 req
= nvme_get_free_req(q
);
513 nvme_submit_command(q
, req
, cmd
, nvme_admin_cmd_sync_cb
, &ret
);
515 AIO_WAIT_WHILE(aio_context
, ret
== -EINPROGRESS
);
519 /* Returns true on success, false on failure. */
520 static bool nvme_identify(BlockDriverState
*bs
, int namespace, Error
**errp
)
522 BDRVNVMeState
*s
= bs
->opaque
;
524 QEMU_AUTO_VFREE
union {
533 .opcode
= NVME_ADM_CMD_IDENTIFY
,
534 .cdw10
= cpu_to_le32(0x1),
536 size_t id_size
= QEMU_ALIGN_UP(sizeof(*id
), qemu_real_host_page_size());
538 id
= qemu_try_memalign(qemu_real_host_page_size(), id_size
);
540 error_setg(errp
, "Cannot allocate buffer for identify response");
543 r
= qemu_vfio_dma_map(s
->vfio
, id
, id_size
, true, &iova
, errp
);
545 error_prepend(errp
, "Cannot map buffer for DMA: ");
549 memset(id
, 0, id_size
);
550 cmd
.dptr
.prp1
= cpu_to_le64(iova
);
551 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
552 error_setg(errp
, "Failed to identify controller");
556 if (le32_to_cpu(id
->ctrl
.nn
) < namespace) {
557 error_setg(errp
, "Invalid namespace");
560 s
->write_cache_supported
= le32_to_cpu(id
->ctrl
.vwc
) & 0x1;
561 s
->max_transfer
= (id
->ctrl
.mdts
? 1 << id
->ctrl
.mdts
: 0) * s
->page_size
;
562 /* For now the page list buffer per command is one page, to hold at most
563 * s->page_size / sizeof(uint64_t) entries. */
564 s
->max_transfer
= MIN_NON_ZERO(s
->max_transfer
,
565 s
->page_size
/ sizeof(uint64_t) * s
->page_size
);
567 oncs
= le16_to_cpu(id
->ctrl
.oncs
);
568 s
->supports_write_zeroes
= !!(oncs
& NVME_ONCS_WRITE_ZEROES
);
569 s
->supports_discard
= !!(oncs
& NVME_ONCS_DSM
);
571 memset(id
, 0, id_size
);
573 cmd
.nsid
= cpu_to_le32(namespace);
574 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
575 error_setg(errp
, "Failed to identify namespace");
579 s
->nsze
= le64_to_cpu(id
->ns
.nsze
);
580 lbaf
= &id
->ns
.lbaf
[NVME_ID_NS_FLBAS_INDEX(id
->ns
.flbas
)];
582 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id
->ns
.dlfeat
) &&
583 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id
->ns
.dlfeat
) ==
584 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES
) {
585 bs
->supported_write_flags
|= BDRV_REQ_MAY_UNMAP
;
589 error_setg(errp
, "Namespaces with metadata are not yet supported");
593 if (lbaf
->ds
< BDRV_SECTOR_BITS
|| lbaf
->ds
> 12 ||
594 (1 << lbaf
->ds
) > s
->page_size
)
596 error_setg(errp
, "Namespace has unsupported block size (2^%d)",
602 s
->blkshift
= lbaf
->ds
;
604 qemu_vfio_dma_unmap(s
->vfio
, id
);
609 static void nvme_poll_queue(NVMeQueuePair
*q
)
611 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
612 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
614 trace_nvme_poll_queue(q
->s
, q
->index
);
616 * Do an early check for completions. q->lock isn't needed because
617 * nvme_process_completion() only runs in the event loop thread and
618 * cannot race with itself.
620 if ((le16_to_cpu(cqe
->status
) & 0x1) == q
->cq_phase
) {
624 qemu_mutex_lock(&q
->lock
);
625 while (nvme_process_completion(q
)) {
628 qemu_mutex_unlock(&q
->lock
);
631 static void nvme_poll_queues(BDRVNVMeState
*s
)
635 for (i
= 0; i
< s
->queue_count
; i
++) {
636 nvme_poll_queue(s
->queues
[i
]);
640 static void nvme_handle_event(EventNotifier
*n
)
642 BDRVNVMeState
*s
= container_of(n
, BDRVNVMeState
,
643 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
645 trace_nvme_handle_event(s
);
646 event_notifier_test_and_clear(n
);
650 static bool nvme_add_io_queue(BlockDriverState
*bs
, Error
**errp
)
652 BDRVNVMeState
*s
= bs
->opaque
;
653 unsigned n
= s
->queue_count
;
656 unsigned queue_size
= NVME_QUEUE_SIZE
;
658 assert(n
<= UINT16_MAX
);
659 q
= nvme_create_queue_pair(s
, bdrv_get_aio_context(bs
),
660 n
, queue_size
, errp
);
665 .opcode
= NVME_ADM_CMD_CREATE_CQ
,
666 .dptr
.prp1
= cpu_to_le64(q
->cq
.iova
),
667 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
668 .cdw11
= cpu_to_le32(NVME_CQ_IEN
| NVME_CQ_PC
),
670 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
671 error_setg(errp
, "Failed to create CQ io queue [%u]", n
);
675 .opcode
= NVME_ADM_CMD_CREATE_SQ
,
676 .dptr
.prp1
= cpu_to_le64(q
->sq
.iova
),
677 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
678 .cdw11
= cpu_to_le32(NVME_SQ_PC
| (n
<< 16)),
680 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
681 error_setg(errp
, "Failed to create SQ io queue [%u]", n
);
684 s
->queues
= g_renew(NVMeQueuePair
*, s
->queues
, n
+ 1);
689 nvme_free_queue_pair(q
);
693 static bool nvme_poll_cb(void *opaque
)
695 EventNotifier
*e
= opaque
;
696 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
697 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
700 for (i
= 0; i
< s
->queue_count
; i
++) {
701 NVMeQueuePair
*q
= s
->queues
[i
];
702 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
703 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
706 * q->lock isn't needed because nvme_process_completion() only runs in
707 * the event loop thread and cannot race with itself.
709 if ((le16_to_cpu(cqe
->status
) & 0x1) != q
->cq_phase
) {
716 static void nvme_poll_ready(EventNotifier
*e
)
718 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
719 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
724 static int nvme_init(BlockDriverState
*bs
, const char *device
, int namespace,
727 BDRVNVMeState
*s
= bs
->opaque
;
729 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
734 uint64_t deadline
, now
;
735 volatile NvmeBar
*regs
= NULL
;
737 qemu_co_mutex_init(&s
->dma_map_lock
);
738 qemu_co_queue_init(&s
->dma_flush_queue
);
739 s
->device
= g_strdup(device
);
741 s
->aio_context
= bdrv_get_aio_context(bs
);
742 ret
= event_notifier_init(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
], 0);
744 error_setg(errp
, "Failed to init event notifier");
748 s
->vfio
= qemu_vfio_open_pci(device
, errp
);
754 regs
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0, sizeof(NvmeBar
),
755 PROT_READ
| PROT_WRITE
, errp
);
760 /* Perform initialize sequence as described in NVMe spec "7.6.1
761 * Initialization". */
763 cap
= le64_to_cpu(regs
->cap
);
764 trace_nvme_controller_capability_raw(cap
);
765 trace_nvme_controller_capability("Maximum Queue Entries Supported",
766 1 + NVME_CAP_MQES(cap
));
767 trace_nvme_controller_capability("Contiguous Queues Required",
769 trace_nvme_controller_capability("Doorbell Stride",
770 1 << (2 + NVME_CAP_DSTRD(cap
)));
771 trace_nvme_controller_capability("Subsystem Reset Supported",
772 NVME_CAP_NSSRS(cap
));
773 trace_nvme_controller_capability("Memory Page Size Minimum",
774 1 << (12 + NVME_CAP_MPSMIN(cap
)));
775 trace_nvme_controller_capability("Memory Page Size Maximum",
776 1 << (12 + NVME_CAP_MPSMAX(cap
)));
777 if (!NVME_CAP_CSS(cap
)) {
778 error_setg(errp
, "Device doesn't support NVMe command set");
783 s
->page_size
= 1u << (12 + NVME_CAP_MPSMIN(cap
));
784 s
->doorbell_scale
= (4 << NVME_CAP_DSTRD(cap
)) / sizeof(uint32_t);
785 bs
->bl
.opt_mem_alignment
= s
->page_size
;
786 bs
->bl
.request_alignment
= s
->page_size
;
787 timeout_ms
= MIN(500 * NVME_CAP_TO(cap
), 30000);
789 ver
= le32_to_cpu(regs
->vs
);
790 trace_nvme_controller_spec_version(extract32(ver
, 16, 16),
791 extract32(ver
, 8, 8),
792 extract32(ver
, 0, 8));
794 /* Reset device to get a clean state. */
795 regs
->cc
= cpu_to_le32(le32_to_cpu(regs
->cc
) & 0xFE);
796 /* Wait for CSTS.RDY = 0. */
797 deadline
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + timeout_ms
* SCALE_MS
;
798 while (NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
799 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
800 error_setg(errp
, "Timeout while waiting for device to reset (%"
808 s
->bar0_wo_map
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0,
809 sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
,
811 s
->doorbells
= (void *)((uintptr_t)s
->bar0_wo_map
+ sizeof(NvmeBar
));
817 /* Set up admin queue. */
818 s
->queues
= g_new(NVMeQueuePair
*, 1);
819 q
= nvme_create_queue_pair(s
, aio_context
, 0, NVME_QUEUE_SIZE
, errp
);
824 s
->queues
[INDEX_ADMIN
] = q
;
826 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE
- 1) & 0xF000);
827 regs
->aqa
= cpu_to_le32(((NVME_QUEUE_SIZE
- 1) << AQA_ACQS_SHIFT
) |
828 ((NVME_QUEUE_SIZE
- 1) << AQA_ASQS_SHIFT
));
829 regs
->asq
= cpu_to_le64(q
->sq
.iova
);
830 regs
->acq
= cpu_to_le64(q
->cq
.iova
);
832 /* After setting up all control registers we can enable device now. */
833 regs
->cc
= cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES
) << CC_IOCQES_SHIFT
) |
834 (ctz32(NVME_SQ_ENTRY_BYTES
) << CC_IOSQES_SHIFT
) |
836 /* Wait for CSTS.RDY = 1. */
837 now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
838 deadline
= now
+ timeout_ms
* SCALE_MS
;
839 while (!NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
840 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
841 error_setg(errp
, "Timeout while waiting for device to start (%"
849 ret
= qemu_vfio_pci_init_irq(s
->vfio
, s
->irq_notifier
,
850 VFIO_PCI_MSIX_IRQ_INDEX
, errp
);
854 aio_set_event_notifier(bdrv_get_aio_context(bs
),
855 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
856 false, nvme_handle_event
, nvme_poll_cb
,
859 if (!nvme_identify(bs
, namespace, errp
)) {
864 /* Set up command queues. */
865 if (!nvme_add_io_queue(bs
, errp
)) {
870 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)regs
, 0, sizeof(NvmeBar
));
873 /* Cleaning up is done in nvme_file_open() upon error. */
877 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
879 * nvme://0000:44:00.0/1
881 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
882 * is the PCI address, and the last part is the namespace number starting from
883 * 1 according to the NVMe spec. */
884 static void nvme_parse_filename(const char *filename
, QDict
*options
,
887 int pref
= strlen("nvme://");
889 if (strlen(filename
) > pref
&& !strncmp(filename
, "nvme://", pref
)) {
890 const char *tmp
= filename
+ pref
;
892 const char *namespace;
894 const char *slash
= strchr(tmp
, '/');
896 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, tmp
);
899 device
= g_strndup(tmp
, slash
- tmp
);
900 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, device
);
902 namespace = slash
+ 1;
903 if (*namespace && qemu_strtoul(namespace, NULL
, 10, &ns
)) {
904 error_setg(errp
, "Invalid namespace '%s', positive number expected",
908 qdict_put_str(options
, NVME_BLOCK_OPT_NAMESPACE
,
909 *namespace ? namespace : "1");
913 static int nvme_enable_disable_write_cache(BlockDriverState
*bs
, bool enable
,
917 BDRVNVMeState
*s
= bs
->opaque
;
919 .opcode
= NVME_ADM_CMD_SET_FEATURES
,
920 .nsid
= cpu_to_le32(s
->nsid
),
921 .cdw10
= cpu_to_le32(0x06),
922 .cdw11
= cpu_to_le32(enable
? 0x01 : 0x00),
925 ret
= nvme_admin_cmd_sync(bs
, &cmd
);
927 error_setg(errp
, "Failed to configure NVMe write cache");
932 static void nvme_close(BlockDriverState
*bs
)
934 BDRVNVMeState
*s
= bs
->opaque
;
936 for (unsigned i
= 0; i
< s
->queue_count
; ++i
) {
937 nvme_free_queue_pair(s
->queues
[i
]);
940 aio_set_event_notifier(bdrv_get_aio_context(bs
),
941 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
942 false, NULL
, NULL
, NULL
);
943 event_notifier_cleanup(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
944 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, s
->bar0_wo_map
,
945 0, sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
);
946 qemu_vfio_close(s
->vfio
);
951 static int nvme_file_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
958 BDRVNVMeState
*s
= bs
->opaque
;
960 bs
->supported_write_flags
= BDRV_REQ_FUA
;
962 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
963 qemu_opts_absorb_qdict(opts
, options
, &error_abort
);
964 device
= qemu_opt_get(opts
, NVME_BLOCK_OPT_DEVICE
);
966 error_setg(errp
, "'" NVME_BLOCK_OPT_DEVICE
"' option is required");
971 namespace = qemu_opt_get_number(opts
, NVME_BLOCK_OPT_NAMESPACE
, 1);
972 ret
= nvme_init(bs
, device
, namespace, errp
);
977 if (flags
& BDRV_O_NOCACHE
) {
978 if (!s
->write_cache_supported
) {
980 "NVMe controller doesn't support write cache configuration");
983 ret
= nvme_enable_disable_write_cache(bs
, !(flags
& BDRV_O_NOCACHE
),
996 static int64_t nvme_getlength(BlockDriverState
*bs
)
998 BDRVNVMeState
*s
= bs
->opaque
;
999 return s
->nsze
<< s
->blkshift
;
1002 static uint32_t nvme_get_blocksize(BlockDriverState
*bs
)
1004 BDRVNVMeState
*s
= bs
->opaque
;
1005 assert(s
->blkshift
>= BDRV_SECTOR_BITS
&& s
->blkshift
<= 12);
1006 return UINT32_C(1) << s
->blkshift
;
1009 static int nvme_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1011 uint32_t blocksize
= nvme_get_blocksize(bs
);
1012 bsz
->phys
= blocksize
;
1013 bsz
->log
= blocksize
;
1017 /* Called with s->dma_map_lock */
1018 static coroutine_fn
int nvme_cmd_unmap_qiov(BlockDriverState
*bs
,
1022 BDRVNVMeState
*s
= bs
->opaque
;
1024 s
->dma_map_count
-= qiov
->size
;
1025 if (!s
->dma_map_count
&& !qemu_co_queue_empty(&s
->dma_flush_queue
)) {
1026 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1028 qemu_co_queue_restart_all(&s
->dma_flush_queue
);
1034 /* Called with s->dma_map_lock */
1035 static coroutine_fn
int nvme_cmd_map_qiov(BlockDriverState
*bs
, NvmeCmd
*cmd
,
1036 NVMeRequest
*req
, QEMUIOVector
*qiov
)
1038 BDRVNVMeState
*s
= bs
->opaque
;
1039 uint64_t *pagelist
= req
->prp_list_page
;
1042 Error
*local_err
= NULL
, **errp
= NULL
;
1045 assert(QEMU_IS_ALIGNED(qiov
->size
, s
->page_size
));
1046 assert(qiov
->size
/ s
->page_size
<= s
->page_size
/ sizeof(uint64_t));
1047 for (i
= 0; i
< qiov
->niov
; ++i
) {
1050 size_t len
= QEMU_ALIGN_UP(qiov
->iov
[i
].iov_len
,
1051 qemu_real_host_page_size());
1053 r
= qemu_vfio_dma_map(s
->vfio
,
1054 qiov
->iov
[i
].iov_base
,
1055 len
, true, &iova
, errp
);
1058 * In addition to the -ENOMEM error, the VFIO_IOMMU_MAP_DMA
1059 * ioctl returns -ENOSPC to signal the user exhausted the DMA
1060 * mappings available for a container since Linux kernel commit
1061 * 492855939bdb ("vfio/type1: Limit DMA mappings per container",
1062 * April 2019, see CVE-2019-3882).
1064 * This block driver already handles this error path by checking
1065 * for the -ENOMEM error, so we directly replace -ENOSPC by
1066 * -ENOMEM. Beside, -ENOSPC has a specific meaning for blockdev
1067 * coroutines: it triggers BLOCKDEV_ON_ERROR_ENOSPC and
1068 * BLOCK_ERROR_ACTION_STOP which stops the VM, asking the operator
1069 * to add more storage to the blockdev. Not something we can do
1070 * easily with an IOMMU :)
1074 if (r
== -ENOMEM
&& retry
) {
1076 * We exhausted the DMA mappings available for our container:
1077 * recycle the volatile IOVA mappings.
1080 trace_nvme_dma_flush_queue_wait(s
);
1081 if (s
->dma_map_count
) {
1082 trace_nvme_dma_map_flush(s
);
1083 qemu_co_queue_wait(&s
->dma_flush_queue
, &s
->dma_map_lock
);
1085 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1098 for (j
= 0; j
< qiov
->iov
[i
].iov_len
/ s
->page_size
; j
++) {
1099 pagelist
[entries
++] = cpu_to_le64(iova
+ j
* s
->page_size
);
1101 trace_nvme_cmd_map_qiov_iov(s
, i
, qiov
->iov
[i
].iov_base
,
1102 qiov
->iov
[i
].iov_len
/ s
->page_size
);
1105 s
->dma_map_count
+= qiov
->size
;
1107 assert(entries
<= s
->page_size
/ sizeof(uint64_t));
1112 cmd
->dptr
.prp1
= pagelist
[0];
1116 cmd
->dptr
.prp1
= pagelist
[0];
1117 cmd
->dptr
.prp2
= pagelist
[1];
1120 cmd
->dptr
.prp1
= pagelist
[0];
1121 cmd
->dptr
.prp2
= cpu_to_le64(req
->prp_list_iova
+ sizeof(uint64_t));
1124 trace_nvme_cmd_map_qiov(s
, cmd
, req
, qiov
, entries
);
1125 for (i
= 0; i
< entries
; ++i
) {
1126 trace_nvme_cmd_map_qiov_pages(s
, i
, pagelist
[i
]);
1130 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1131 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1132 * because they are already mapped before calling this function; for
1133 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1134 * calling qemu_vfio_dma_reset_temporary when necessary. */
1136 error_reportf_err(local_err
, "Cannot map buffer for DMA: ");
1147 static void nvme_rw_cb_bh(void *opaque
)
1149 NVMeCoData
*data
= opaque
;
1150 qemu_coroutine_enter(data
->co
);
1153 static void nvme_rw_cb(void *opaque
, int ret
)
1155 NVMeCoData
*data
= opaque
;
1158 /* The rw coroutine hasn't yielded, don't try to enter. */
1161 replay_bh_schedule_oneshot_event(data
->ctx
, nvme_rw_cb_bh
, data
);
1164 static coroutine_fn
int nvme_co_prw_aligned(BlockDriverState
*bs
,
1165 uint64_t offset
, uint64_t bytes
,
1171 BDRVNVMeState
*s
= bs
->opaque
;
1172 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1175 uint32_t cdw12
= (((bytes
>> s
->blkshift
) - 1) & 0xFFFF) |
1176 (flags
& BDRV_REQ_FUA
? 1 << 30 : 0);
1178 .opcode
= is_write
? NVME_CMD_WRITE
: NVME_CMD_READ
,
1179 .nsid
= cpu_to_le32(s
->nsid
),
1180 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1181 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1182 .cdw12
= cpu_to_le32(cdw12
),
1185 .ctx
= bdrv_get_aio_context(bs
),
1186 .ret
= -EINPROGRESS
,
1189 trace_nvme_prw_aligned(s
, is_write
, offset
, bytes
, flags
, qiov
->niov
);
1190 assert(s
->queue_count
> 1);
1191 req
= nvme_get_free_req(ioq
);
1194 qemu_co_mutex_lock(&s
->dma_map_lock
);
1195 r
= nvme_cmd_map_qiov(bs
, &cmd
, req
, qiov
);
1196 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1198 nvme_put_free_req_and_wake(ioq
, req
);
1201 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1203 data
.co
= qemu_coroutine_self();
1204 while (data
.ret
== -EINPROGRESS
) {
1205 qemu_coroutine_yield();
1208 qemu_co_mutex_lock(&s
->dma_map_lock
);
1209 r
= nvme_cmd_unmap_qiov(bs
, qiov
);
1210 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1215 trace_nvme_rw_done(s
, is_write
, offset
, bytes
, data
.ret
);
1219 static inline bool nvme_qiov_aligned(BlockDriverState
*bs
,
1220 const QEMUIOVector
*qiov
)
1223 BDRVNVMeState
*s
= bs
->opaque
;
1225 for (i
= 0; i
< qiov
->niov
; ++i
) {
1226 if (!QEMU_PTR_IS_ALIGNED(qiov
->iov
[i
].iov_base
,
1227 qemu_real_host_page_size()) ||
1228 !QEMU_IS_ALIGNED(qiov
->iov
[i
].iov_len
, qemu_real_host_page_size())) {
1229 trace_nvme_qiov_unaligned(qiov
, i
, qiov
->iov
[i
].iov_base
,
1230 qiov
->iov
[i
].iov_len
, s
->page_size
);
1237 static int nvme_co_prw(BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
1238 QEMUIOVector
*qiov
, bool is_write
, int flags
)
1240 BDRVNVMeState
*s
= bs
->opaque
;
1242 QEMU_AUTO_VFREE
uint8_t *buf
= NULL
;
1243 QEMUIOVector local_qiov
;
1244 size_t len
= QEMU_ALIGN_UP(bytes
, qemu_real_host_page_size());
1245 assert(QEMU_IS_ALIGNED(offset
, s
->page_size
));
1246 assert(QEMU_IS_ALIGNED(bytes
, s
->page_size
));
1247 assert(bytes
<= s
->max_transfer
);
1248 if (nvme_qiov_aligned(bs
, qiov
)) {
1249 s
->stats
.aligned_accesses
++;
1250 return nvme_co_prw_aligned(bs
, offset
, bytes
, qiov
, is_write
, flags
);
1252 s
->stats
.unaligned_accesses
++;
1253 trace_nvme_prw_buffered(s
, offset
, bytes
, qiov
->niov
, is_write
);
1254 buf
= qemu_try_memalign(qemu_real_host_page_size(), len
);
1259 qemu_iovec_init(&local_qiov
, 1);
1261 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
1263 qemu_iovec_add(&local_qiov
, buf
, bytes
);
1264 r
= nvme_co_prw_aligned(bs
, offset
, bytes
, &local_qiov
, is_write
, flags
);
1265 qemu_iovec_destroy(&local_qiov
);
1266 if (!r
&& !is_write
) {
1267 qemu_iovec_from_buf(qiov
, 0, buf
, bytes
);
1272 static coroutine_fn
int nvme_co_preadv(BlockDriverState
*bs
,
1273 int64_t offset
, int64_t bytes
,
1275 BdrvRequestFlags flags
)
1277 return nvme_co_prw(bs
, offset
, bytes
, qiov
, false, flags
);
1280 static coroutine_fn
int nvme_co_pwritev(BlockDriverState
*bs
,
1281 int64_t offset
, int64_t bytes
,
1283 BdrvRequestFlags flags
)
1285 return nvme_co_prw(bs
, offset
, bytes
, qiov
, true, flags
);
1288 static coroutine_fn
int nvme_co_flush(BlockDriverState
*bs
)
1290 BDRVNVMeState
*s
= bs
->opaque
;
1291 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1294 .opcode
= NVME_CMD_FLUSH
,
1295 .nsid
= cpu_to_le32(s
->nsid
),
1298 .ctx
= bdrv_get_aio_context(bs
),
1299 .ret
= -EINPROGRESS
,
1302 assert(s
->queue_count
> 1);
1303 req
= nvme_get_free_req(ioq
);
1305 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1307 data
.co
= qemu_coroutine_self();
1308 if (data
.ret
== -EINPROGRESS
) {
1309 qemu_coroutine_yield();
1316 static coroutine_fn
int nvme_co_pwrite_zeroes(BlockDriverState
*bs
,
1319 BdrvRequestFlags flags
)
1321 BDRVNVMeState
*s
= bs
->opaque
;
1322 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1326 if (!s
->supports_write_zeroes
) {
1334 cdw12
= ((bytes
>> s
->blkshift
) - 1) & 0xFFFF;
1336 * We should not lose information. pwrite_zeroes_alignment and
1337 * max_pwrite_zeroes guarantees it.
1339 assert(((cdw12
+ 1) << s
->blkshift
) == bytes
);
1342 .opcode
= NVME_CMD_WRITE_ZEROES
,
1343 .nsid
= cpu_to_le32(s
->nsid
),
1344 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1345 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1349 .ctx
= bdrv_get_aio_context(bs
),
1350 .ret
= -EINPROGRESS
,
1353 if (flags
& BDRV_REQ_MAY_UNMAP
) {
1357 if (flags
& BDRV_REQ_FUA
) {
1361 cmd
.cdw12
= cpu_to_le32(cdw12
);
1363 trace_nvme_write_zeroes(s
, offset
, bytes
, flags
);
1364 assert(s
->queue_count
> 1);
1365 req
= nvme_get_free_req(ioq
);
1368 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1370 data
.co
= qemu_coroutine_self();
1371 while (data
.ret
== -EINPROGRESS
) {
1372 qemu_coroutine_yield();
1375 trace_nvme_rw_done(s
, true, offset
, bytes
, data
.ret
);
1380 static int coroutine_fn
nvme_co_pdiscard(BlockDriverState
*bs
,
1384 BDRVNVMeState
*s
= bs
->opaque
;
1385 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1387 QEMU_AUTO_VFREE NvmeDsmRange
*buf
= NULL
;
1388 QEMUIOVector local_qiov
;
1392 .opcode
= NVME_CMD_DSM
,
1393 .nsid
= cpu_to_le32(s
->nsid
),
1394 .cdw10
= cpu_to_le32(0), /*number of ranges - 0 based*/
1395 .cdw11
= cpu_to_le32(1 << 2), /*deallocate bit*/
1399 .ctx
= bdrv_get_aio_context(bs
),
1400 .ret
= -EINPROGRESS
,
1403 if (!s
->supports_discard
) {
1407 assert(s
->queue_count
> 1);
1410 * Filling the @buf requires @offset and @bytes to satisfy restrictions
1411 * defined in nvme_refresh_limits().
1413 assert(QEMU_IS_ALIGNED(bytes
, 1UL << s
->blkshift
));
1414 assert(QEMU_IS_ALIGNED(offset
, 1UL << s
->blkshift
));
1415 assert((bytes
>> s
->blkshift
) <= UINT32_MAX
);
1417 buf
= qemu_try_memalign(s
->page_size
, s
->page_size
);
1421 memset(buf
, 0, s
->page_size
);
1422 buf
->nlb
= cpu_to_le32(bytes
>> s
->blkshift
);
1423 buf
->slba
= cpu_to_le64(offset
>> s
->blkshift
);
1426 qemu_iovec_init(&local_qiov
, 1);
1427 qemu_iovec_add(&local_qiov
, buf
, 4096);
1429 req
= nvme_get_free_req(ioq
);
1432 qemu_co_mutex_lock(&s
->dma_map_lock
);
1433 ret
= nvme_cmd_map_qiov(bs
, &cmd
, req
, &local_qiov
);
1434 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1437 nvme_put_free_req_and_wake(ioq
, req
);
1441 trace_nvme_dsm(s
, offset
, bytes
);
1443 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1445 data
.co
= qemu_coroutine_self();
1446 while (data
.ret
== -EINPROGRESS
) {
1447 qemu_coroutine_yield();
1450 qemu_co_mutex_lock(&s
->dma_map_lock
);
1451 ret
= nvme_cmd_unmap_qiov(bs
, &local_qiov
);
1452 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1459 trace_nvme_dsm_done(s
, offset
, bytes
, ret
);
1461 qemu_iovec_destroy(&local_qiov
);
1466 static int coroutine_fn
nvme_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1467 bool exact
, PreallocMode prealloc
,
1468 BdrvRequestFlags flags
, Error
**errp
)
1472 if (prealloc
!= PREALLOC_MODE_OFF
) {
1473 error_setg(errp
, "Unsupported preallocation mode '%s'",
1474 PreallocMode_str(prealloc
));
1478 cur_length
= nvme_getlength(bs
);
1479 if (offset
!= cur_length
&& exact
) {
1480 error_setg(errp
, "Cannot resize NVMe devices");
1482 } else if (offset
> cur_length
) {
1483 error_setg(errp
, "Cannot grow NVMe devices");
1490 static int nvme_reopen_prepare(BDRVReopenState
*reopen_state
,
1491 BlockReopenQueue
*queue
, Error
**errp
)
1496 static void nvme_refresh_filename(BlockDriverState
*bs
)
1498 BDRVNVMeState
*s
= bs
->opaque
;
1500 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
), "nvme://%s/%i",
1501 s
->device
, s
->nsid
);
1504 static void nvme_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1506 BDRVNVMeState
*s
= bs
->opaque
;
1508 bs
->bl
.opt_mem_alignment
= s
->page_size
;
1509 bs
->bl
.request_alignment
= s
->page_size
;
1510 bs
->bl
.max_transfer
= s
->max_transfer
;
1513 * Look at nvme_co_pwrite_zeroes: after shift and decrement we should get
1516 bs
->bl
.max_pwrite_zeroes
= 1ULL << (s
->blkshift
+ 16);
1517 bs
->bl
.pwrite_zeroes_alignment
= MAX(bs
->bl
.request_alignment
,
1518 1UL << s
->blkshift
);
1520 bs
->bl
.max_pdiscard
= (uint64_t)UINT32_MAX
<< s
->blkshift
;
1521 bs
->bl
.pdiscard_alignment
= MAX(bs
->bl
.request_alignment
,
1522 1UL << s
->blkshift
);
1525 static void nvme_detach_aio_context(BlockDriverState
*bs
)
1527 BDRVNVMeState
*s
= bs
->opaque
;
1529 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1530 NVMeQueuePair
*q
= s
->queues
[i
];
1532 qemu_bh_delete(q
->completion_bh
);
1533 q
->completion_bh
= NULL
;
1536 aio_set_event_notifier(bdrv_get_aio_context(bs
),
1537 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1538 false, NULL
, NULL
, NULL
);
1541 static void nvme_attach_aio_context(BlockDriverState
*bs
,
1542 AioContext
*new_context
)
1544 BDRVNVMeState
*s
= bs
->opaque
;
1546 s
->aio_context
= new_context
;
1547 aio_set_event_notifier(new_context
, &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1548 false, nvme_handle_event
, nvme_poll_cb
,
1551 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1552 NVMeQueuePair
*q
= s
->queues
[i
];
1555 aio_bh_new(new_context
, nvme_process_completion_bh
, q
);
1559 static void nvme_aio_plug(BlockDriverState
*bs
)
1561 BDRVNVMeState
*s
= bs
->opaque
;
1562 assert(!s
->plugged
);
1566 static void nvme_aio_unplug(BlockDriverState
*bs
)
1568 BDRVNVMeState
*s
= bs
->opaque
;
1571 for (unsigned i
= INDEX_IO(0); i
< s
->queue_count
; i
++) {
1572 NVMeQueuePair
*q
= s
->queues
[i
];
1573 qemu_mutex_lock(&q
->lock
);
1575 nvme_process_completion(q
);
1576 qemu_mutex_unlock(&q
->lock
);
1580 static void nvme_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
1583 Error
*local_err
= NULL
;
1584 BDRVNVMeState
*s
= bs
->opaque
;
1586 ret
= qemu_vfio_dma_map(s
->vfio
, host
, size
, false, NULL
, &local_err
);
1588 /* FIXME: we may run out of IOVA addresses after repeated
1589 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1590 * doesn't reclaim addresses for fixed mappings. */
1591 error_reportf_err(local_err
, "nvme_register_buf failed: ");
1595 static void nvme_unregister_buf(BlockDriverState
*bs
, void *host
)
1597 BDRVNVMeState
*s
= bs
->opaque
;
1599 qemu_vfio_dma_unmap(s
->vfio
, host
);
1602 static BlockStatsSpecific
*nvme_get_specific_stats(BlockDriverState
*bs
)
1604 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
1605 BDRVNVMeState
*s
= bs
->opaque
;
1607 stats
->driver
= BLOCKDEV_DRIVER_NVME
;
1608 stats
->u
.nvme
= (BlockStatsSpecificNvme
) {
1609 .completion_errors
= s
->stats
.completion_errors
,
1610 .aligned_accesses
= s
->stats
.aligned_accesses
,
1611 .unaligned_accesses
= s
->stats
.unaligned_accesses
,
1617 static const char *const nvme_strong_runtime_opts
[] = {
1618 NVME_BLOCK_OPT_DEVICE
,
1619 NVME_BLOCK_OPT_NAMESPACE
,
1624 static BlockDriver bdrv_nvme
= {
1625 .format_name
= "nvme",
1626 .protocol_name
= "nvme",
1627 .instance_size
= sizeof(BDRVNVMeState
),
1629 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
1630 .create_opts
= &bdrv_create_opts_simple
,
1632 .bdrv_parse_filename
= nvme_parse_filename
,
1633 .bdrv_file_open
= nvme_file_open
,
1634 .bdrv_close
= nvme_close
,
1635 .bdrv_getlength
= nvme_getlength
,
1636 .bdrv_probe_blocksizes
= nvme_probe_blocksizes
,
1637 .bdrv_co_truncate
= nvme_co_truncate
,
1639 .bdrv_co_preadv
= nvme_co_preadv
,
1640 .bdrv_co_pwritev
= nvme_co_pwritev
,
1642 .bdrv_co_pwrite_zeroes
= nvme_co_pwrite_zeroes
,
1643 .bdrv_co_pdiscard
= nvme_co_pdiscard
,
1645 .bdrv_co_flush_to_disk
= nvme_co_flush
,
1646 .bdrv_reopen_prepare
= nvme_reopen_prepare
,
1648 .bdrv_refresh_filename
= nvme_refresh_filename
,
1649 .bdrv_refresh_limits
= nvme_refresh_limits
,
1650 .strong_runtime_opts
= nvme_strong_runtime_opts
,
1651 .bdrv_get_specific_stats
= nvme_get_specific_stats
,
1653 .bdrv_detach_aio_context
= nvme_detach_aio_context
,
1654 .bdrv_attach_aio_context
= nvme_attach_aio_context
,
1656 .bdrv_io_plug
= nvme_aio_plug
,
1657 .bdrv_io_unplug
= nvme_aio_unplug
,
1659 .bdrv_register_buf
= nvme_register_buf
,
1660 .bdrv_unregister_buf
= nvme_unregister_buf
,
1663 static void bdrv_nvme_init(void)
1665 bdrv_register(&bdrv_nvme
);
1668 block_init(bdrv_nvme_init
);