hw/arm/armsse: Make number of SRAM banks parameterised
[qemu/ar7.git] / block / nvme.c
blob982097b5b1c91631083c65d4edcd2d12008b44c8
1 /*
2 * NVMe block driver based on vfio
4 * Copyright 2016 - 2018 Red Hat, Inc.
6 * Authors:
7 * Fam Zheng <famz@redhat.com>
8 * Paolo Bonzini <pbonzini@redhat.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include <linux/vfio.h>
16 #include "qapi/error.h"
17 #include "qapi/qmp/qdict.h"
18 #include "qapi/qmp/qstring.h"
19 #include "qemu/error-report.h"
20 #include "qemu/cutils.h"
21 #include "qemu/option.h"
22 #include "qemu/vfio-helpers.h"
23 #include "block/block_int.h"
24 #include "trace.h"
26 #include "block/nvme.h"
28 #define NVME_SQ_ENTRY_BYTES 64
29 #define NVME_CQ_ENTRY_BYTES 16
30 #define NVME_QUEUE_SIZE 128
31 #define NVME_BAR_SIZE 8192
33 typedef struct {
34 int32_t head, tail;
35 uint8_t *queue;
36 uint64_t iova;
37 /* Hardware MMIO register */
38 volatile uint32_t *doorbell;
39 } NVMeQueue;
41 typedef struct {
42 BlockCompletionFunc *cb;
43 void *opaque;
44 int cid;
45 void *prp_list_page;
46 uint64_t prp_list_iova;
47 bool busy;
48 } NVMeRequest;
50 typedef struct {
51 CoQueue free_req_queue;
52 QemuMutex lock;
54 /* Fields protected by BQL */
55 int index;
56 uint8_t *prp_list_pages;
58 /* Fields protected by @lock */
59 NVMeQueue sq, cq;
60 int cq_phase;
61 NVMeRequest reqs[NVME_QUEUE_SIZE];
62 bool busy;
63 int need_kick;
64 int inflight;
65 } NVMeQueuePair;
67 /* Memory mapped registers */
68 typedef volatile struct {
69 uint64_t cap;
70 uint32_t vs;
71 uint32_t intms;
72 uint32_t intmc;
73 uint32_t cc;
74 uint32_t reserved0;
75 uint32_t csts;
76 uint32_t nssr;
77 uint32_t aqa;
78 uint64_t asq;
79 uint64_t acq;
80 uint32_t cmbloc;
81 uint32_t cmbsz;
82 uint8_t reserved1[0xec0];
83 uint8_t cmd_set_specfic[0x100];
84 uint32_t doorbells[];
85 } QEMU_PACKED NVMeRegs;
87 QEMU_BUILD_BUG_ON(offsetof(NVMeRegs, doorbells) != 0x1000);
89 typedef struct {
90 AioContext *aio_context;
91 QEMUVFIOState *vfio;
92 NVMeRegs *regs;
93 /* The submission/completion queue pairs.
94 * [0]: admin queue.
95 * [1..]: io queues.
97 NVMeQueuePair **queues;
98 int nr_queues;
99 size_t page_size;
100 /* How many uint32_t elements does each doorbell entry take. */
101 size_t doorbell_scale;
102 bool write_cache_supported;
103 EventNotifier irq_notifier;
104 uint64_t nsze; /* Namespace size reported by identify command */
105 int nsid; /* The namespace id to read/write data. */
106 uint64_t max_transfer;
107 bool plugged;
109 CoMutex dma_map_lock;
110 CoQueue dma_flush_queue;
112 /* Total size of mapped qiov, accessed under dma_map_lock */
113 int dma_map_count;
114 } BDRVNVMeState;
116 #define NVME_BLOCK_OPT_DEVICE "device"
117 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
119 static QemuOptsList runtime_opts = {
120 .name = "nvme",
121 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
122 .desc = {
124 .name = NVME_BLOCK_OPT_DEVICE,
125 .type = QEMU_OPT_STRING,
126 .help = "NVMe PCI device address",
129 .name = NVME_BLOCK_OPT_NAMESPACE,
130 .type = QEMU_OPT_NUMBER,
131 .help = "NVMe namespace",
133 { /* end of list */ }
137 static void nvme_init_queue(BlockDriverState *bs, NVMeQueue *q,
138 int nentries, int entry_bytes, Error **errp)
140 BDRVNVMeState *s = bs->opaque;
141 size_t bytes;
142 int r;
144 bytes = ROUND_UP(nentries * entry_bytes, s->page_size);
145 q->head = q->tail = 0;
146 q->queue = qemu_try_blockalign0(bs, bytes);
148 if (!q->queue) {
149 error_setg(errp, "Cannot allocate queue");
150 return;
152 r = qemu_vfio_dma_map(s->vfio, q->queue, bytes, false, &q->iova);
153 if (r) {
154 error_setg(errp, "Cannot map queue");
158 static void nvme_free_queue_pair(BlockDriverState *bs, NVMeQueuePair *q)
160 qemu_vfree(q->prp_list_pages);
161 qemu_vfree(q->sq.queue);
162 qemu_vfree(q->cq.queue);
163 qemu_mutex_destroy(&q->lock);
164 g_free(q);
167 static void nvme_free_req_queue_cb(void *opaque)
169 NVMeQueuePair *q = opaque;
171 qemu_mutex_lock(&q->lock);
172 while (qemu_co_enter_next(&q->free_req_queue, &q->lock)) {
173 /* Retry all pending requests */
175 qemu_mutex_unlock(&q->lock);
178 static NVMeQueuePair *nvme_create_queue_pair(BlockDriverState *bs,
179 int idx, int size,
180 Error **errp)
182 int i, r;
183 BDRVNVMeState *s = bs->opaque;
184 Error *local_err = NULL;
185 NVMeQueuePair *q = g_new0(NVMeQueuePair, 1);
186 uint64_t prp_list_iova;
188 qemu_mutex_init(&q->lock);
189 q->index = idx;
190 qemu_co_queue_init(&q->free_req_queue);
191 q->prp_list_pages = qemu_blockalign0(bs, s->page_size * NVME_QUEUE_SIZE);
192 r = qemu_vfio_dma_map(s->vfio, q->prp_list_pages,
193 s->page_size * NVME_QUEUE_SIZE,
194 false, &prp_list_iova);
195 if (r) {
196 goto fail;
198 for (i = 0; i < NVME_QUEUE_SIZE; i++) {
199 NVMeRequest *req = &q->reqs[i];
200 req->cid = i + 1;
201 req->prp_list_page = q->prp_list_pages + i * s->page_size;
202 req->prp_list_iova = prp_list_iova + i * s->page_size;
204 nvme_init_queue(bs, &q->sq, size, NVME_SQ_ENTRY_BYTES, &local_err);
205 if (local_err) {
206 error_propagate(errp, local_err);
207 goto fail;
209 q->sq.doorbell = &s->regs->doorbells[idx * 2 * s->doorbell_scale];
211 nvme_init_queue(bs, &q->cq, size, NVME_CQ_ENTRY_BYTES, &local_err);
212 if (local_err) {
213 error_propagate(errp, local_err);
214 goto fail;
216 q->cq.doorbell = &s->regs->doorbells[idx * 2 * s->doorbell_scale + 1];
218 return q;
219 fail:
220 nvme_free_queue_pair(bs, q);
221 return NULL;
224 /* With q->lock */
225 static void nvme_kick(BDRVNVMeState *s, NVMeQueuePair *q)
227 if (s->plugged || !q->need_kick) {
228 return;
230 trace_nvme_kick(s, q->index);
231 assert(!(q->sq.tail & 0xFF00));
232 /* Fence the write to submission queue entry before notifying the device. */
233 smp_wmb();
234 *q->sq.doorbell = cpu_to_le32(q->sq.tail);
235 q->inflight += q->need_kick;
236 q->need_kick = 0;
239 /* Find a free request element if any, otherwise:
240 * a) if in coroutine context, try to wait for one to become available;
241 * b) if not in coroutine, return NULL;
243 static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
245 int i;
246 NVMeRequest *req = NULL;
248 qemu_mutex_lock(&q->lock);
249 while (q->inflight + q->need_kick > NVME_QUEUE_SIZE - 2) {
250 /* We have to leave one slot empty as that is the full queue case (head
251 * == tail + 1). */
252 if (qemu_in_coroutine()) {
253 trace_nvme_free_req_queue_wait(q);
254 qemu_co_queue_wait(&q->free_req_queue, &q->lock);
255 } else {
256 qemu_mutex_unlock(&q->lock);
257 return NULL;
260 for (i = 0; i < NVME_QUEUE_SIZE; i++) {
261 if (!q->reqs[i].busy) {
262 q->reqs[i].busy = true;
263 req = &q->reqs[i];
264 break;
267 /* We have checked inflight and need_kick while holding q->lock, so one
268 * free req must be available. */
269 assert(req);
270 qemu_mutex_unlock(&q->lock);
271 return req;
274 static inline int nvme_translate_error(const NvmeCqe *c)
276 uint16_t status = (le16_to_cpu(c->status) >> 1) & 0xFF;
277 if (status) {
278 trace_nvme_error(le32_to_cpu(c->result),
279 le16_to_cpu(c->sq_head),
280 le16_to_cpu(c->sq_id),
281 le16_to_cpu(c->cid),
282 le16_to_cpu(status));
284 switch (status) {
285 case 0:
286 return 0;
287 case 1:
288 return -ENOSYS;
289 case 2:
290 return -EINVAL;
291 default:
292 return -EIO;
296 /* With q->lock */
297 static bool nvme_process_completion(BDRVNVMeState *s, NVMeQueuePair *q)
299 bool progress = false;
300 NVMeRequest *preq;
301 NVMeRequest req;
302 NvmeCqe *c;
304 trace_nvme_process_completion(s, q->index, q->inflight);
305 if (q->busy || s->plugged) {
306 trace_nvme_process_completion_queue_busy(s, q->index);
307 return false;
309 q->busy = true;
310 assert(q->inflight >= 0);
311 while (q->inflight) {
312 int16_t cid;
313 c = (NvmeCqe *)&q->cq.queue[q->cq.head * NVME_CQ_ENTRY_BYTES];
314 if (!c->cid || (le16_to_cpu(c->status) & 0x1) == q->cq_phase) {
315 break;
317 q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
318 if (!q->cq.head) {
319 q->cq_phase = !q->cq_phase;
321 cid = le16_to_cpu(c->cid);
322 if (cid == 0 || cid > NVME_QUEUE_SIZE) {
323 fprintf(stderr, "Unexpected CID in completion queue: %" PRIu32 "\n",
324 cid);
325 continue;
327 assert(cid <= NVME_QUEUE_SIZE);
328 trace_nvme_complete_command(s, q->index, cid);
329 preq = &q->reqs[cid - 1];
330 req = *preq;
331 assert(req.cid == cid);
332 assert(req.cb);
333 preq->busy = false;
334 preq->cb = preq->opaque = NULL;
335 qemu_mutex_unlock(&q->lock);
336 req.cb(req.opaque, nvme_translate_error(c));
337 qemu_mutex_lock(&q->lock);
338 c->cid = cpu_to_le16(0);
339 q->inflight--;
340 /* Flip Phase Tag bit. */
341 c->status = cpu_to_le16(le16_to_cpu(c->status) ^ 0x1);
342 progress = true;
344 if (progress) {
345 /* Notify the device so it can post more completions. */
346 smp_mb_release();
347 *q->cq.doorbell = cpu_to_le32(q->cq.head);
348 if (!qemu_co_queue_empty(&q->free_req_queue)) {
349 aio_bh_schedule_oneshot(s->aio_context, nvme_free_req_queue_cb, q);
352 q->busy = false;
353 return progress;
356 static void nvme_trace_command(const NvmeCmd *cmd)
358 int i;
360 for (i = 0; i < 8; ++i) {
361 uint8_t *cmdp = (uint8_t *)cmd + i * 8;
362 trace_nvme_submit_command_raw(cmdp[0], cmdp[1], cmdp[2], cmdp[3],
363 cmdp[4], cmdp[5], cmdp[6], cmdp[7]);
367 static void nvme_submit_command(BDRVNVMeState *s, NVMeQueuePair *q,
368 NVMeRequest *req,
369 NvmeCmd *cmd, BlockCompletionFunc cb,
370 void *opaque)
372 assert(!req->cb);
373 req->cb = cb;
374 req->opaque = opaque;
375 cmd->cid = cpu_to_le32(req->cid);
377 trace_nvme_submit_command(s, q->index, req->cid);
378 nvme_trace_command(cmd);
379 qemu_mutex_lock(&q->lock);
380 memcpy((uint8_t *)q->sq.queue +
381 q->sq.tail * NVME_SQ_ENTRY_BYTES, cmd, sizeof(*cmd));
382 q->sq.tail = (q->sq.tail + 1) % NVME_QUEUE_SIZE;
383 q->need_kick++;
384 nvme_kick(s, q);
385 nvme_process_completion(s, q);
386 qemu_mutex_unlock(&q->lock);
389 static void nvme_cmd_sync_cb(void *opaque, int ret)
391 int *pret = opaque;
392 *pret = ret;
395 static int nvme_cmd_sync(BlockDriverState *bs, NVMeQueuePair *q,
396 NvmeCmd *cmd)
398 NVMeRequest *req;
399 BDRVNVMeState *s = bs->opaque;
400 int ret = -EINPROGRESS;
401 req = nvme_get_free_req(q);
402 if (!req) {
403 return -EBUSY;
405 nvme_submit_command(s, q, req, cmd, nvme_cmd_sync_cb, &ret);
407 BDRV_POLL_WHILE(bs, ret == -EINPROGRESS);
408 return ret;
411 static void nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
413 BDRVNVMeState *s = bs->opaque;
414 NvmeIdCtrl *idctrl;
415 NvmeIdNs *idns;
416 uint8_t *resp;
417 int r;
418 uint64_t iova;
419 NvmeCmd cmd = {
420 .opcode = NVME_ADM_CMD_IDENTIFY,
421 .cdw10 = cpu_to_le32(0x1),
424 resp = qemu_try_blockalign0(bs, sizeof(NvmeIdCtrl));
425 if (!resp) {
426 error_setg(errp, "Cannot allocate buffer for identify response");
427 goto out;
429 idctrl = (NvmeIdCtrl *)resp;
430 idns = (NvmeIdNs *)resp;
431 r = qemu_vfio_dma_map(s->vfio, resp, sizeof(NvmeIdCtrl), true, &iova);
432 if (r) {
433 error_setg(errp, "Cannot map buffer for DMA");
434 goto out;
436 cmd.prp1 = cpu_to_le64(iova);
438 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
439 error_setg(errp, "Failed to identify controller");
440 goto out;
443 if (le32_to_cpu(idctrl->nn) < namespace) {
444 error_setg(errp, "Invalid namespace");
445 goto out;
447 s->write_cache_supported = le32_to_cpu(idctrl->vwc) & 0x1;
448 s->max_transfer = (idctrl->mdts ? 1 << idctrl->mdts : 0) * s->page_size;
449 /* For now the page list buffer per command is one page, to hold at most
450 * s->page_size / sizeof(uint64_t) entries. */
451 s->max_transfer = MIN_NON_ZERO(s->max_transfer,
452 s->page_size / sizeof(uint64_t) * s->page_size);
454 memset(resp, 0, 4096);
456 cmd.cdw10 = 0;
457 cmd.nsid = cpu_to_le32(namespace);
458 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
459 error_setg(errp, "Failed to identify namespace");
460 goto out;
463 s->nsze = le64_to_cpu(idns->nsze);
465 out:
466 qemu_vfio_dma_unmap(s->vfio, resp);
467 qemu_vfree(resp);
470 static bool nvme_poll_queues(BDRVNVMeState *s)
472 bool progress = false;
473 int i;
475 for (i = 0; i < s->nr_queues; i++) {
476 NVMeQueuePair *q = s->queues[i];
477 qemu_mutex_lock(&q->lock);
478 while (nvme_process_completion(s, q)) {
479 /* Keep polling */
480 progress = true;
482 qemu_mutex_unlock(&q->lock);
484 return progress;
487 static void nvme_handle_event(EventNotifier *n)
489 BDRVNVMeState *s = container_of(n, BDRVNVMeState, irq_notifier);
491 trace_nvme_handle_event(s);
492 event_notifier_test_and_clear(n);
493 nvme_poll_queues(s);
496 static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
498 BDRVNVMeState *s = bs->opaque;
499 int n = s->nr_queues;
500 NVMeQueuePair *q;
501 NvmeCmd cmd;
502 int queue_size = NVME_QUEUE_SIZE;
504 q = nvme_create_queue_pair(bs, n, queue_size, errp);
505 if (!q) {
506 return false;
508 cmd = (NvmeCmd) {
509 .opcode = NVME_ADM_CMD_CREATE_CQ,
510 .prp1 = cpu_to_le64(q->cq.iova),
511 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | (n & 0xFFFF)),
512 .cdw11 = cpu_to_le32(0x3),
514 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
515 error_setg(errp, "Failed to create io queue [%d]", n);
516 nvme_free_queue_pair(bs, q);
517 return false;
519 cmd = (NvmeCmd) {
520 .opcode = NVME_ADM_CMD_CREATE_SQ,
521 .prp1 = cpu_to_le64(q->sq.iova),
522 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | (n & 0xFFFF)),
523 .cdw11 = cpu_to_le32(0x1 | (n << 16)),
525 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
526 error_setg(errp, "Failed to create io queue [%d]", n);
527 nvme_free_queue_pair(bs, q);
528 return false;
530 s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
531 s->queues[n] = q;
532 s->nr_queues++;
533 return true;
536 static bool nvme_poll_cb(void *opaque)
538 EventNotifier *e = opaque;
539 BDRVNVMeState *s = container_of(e, BDRVNVMeState, irq_notifier);
540 bool progress = false;
542 trace_nvme_poll_cb(s);
543 progress = nvme_poll_queues(s);
544 return progress;
547 static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
548 Error **errp)
550 BDRVNVMeState *s = bs->opaque;
551 int ret;
552 uint64_t cap;
553 uint64_t timeout_ms;
554 uint64_t deadline, now;
555 Error *local_err = NULL;
557 qemu_co_mutex_init(&s->dma_map_lock);
558 qemu_co_queue_init(&s->dma_flush_queue);
559 s->nsid = namespace;
560 s->aio_context = bdrv_get_aio_context(bs);
561 ret = event_notifier_init(&s->irq_notifier, 0);
562 if (ret) {
563 error_setg(errp, "Failed to init event notifier");
564 return ret;
567 s->vfio = qemu_vfio_open_pci(device, errp);
568 if (!s->vfio) {
569 ret = -EINVAL;
570 goto out;
573 s->regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, NVME_BAR_SIZE, errp);
574 if (!s->regs) {
575 ret = -EINVAL;
576 goto out;
579 /* Perform initialize sequence as described in NVMe spec "7.6.1
580 * Initialization". */
582 cap = le64_to_cpu(s->regs->cap);
583 if (!(cap & (1ULL << 37))) {
584 error_setg(errp, "Device doesn't support NVMe command set");
585 ret = -EINVAL;
586 goto out;
589 s->page_size = MAX(4096, 1 << (12 + ((cap >> 48) & 0xF)));
590 s->doorbell_scale = (4 << (((cap >> 32) & 0xF))) / sizeof(uint32_t);
591 bs->bl.opt_mem_alignment = s->page_size;
592 timeout_ms = MIN(500 * ((cap >> 24) & 0xFF), 30000);
594 /* Reset device to get a clean state. */
595 s->regs->cc = cpu_to_le32(le32_to_cpu(s->regs->cc) & 0xFE);
596 /* Wait for CSTS.RDY = 0. */
597 deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * 1000000ULL;
598 while (le32_to_cpu(s->regs->csts) & 0x1) {
599 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
600 error_setg(errp, "Timeout while waiting for device to reset (%"
601 PRId64 " ms)",
602 timeout_ms);
603 ret = -ETIMEDOUT;
604 goto out;
608 /* Set up admin queue. */
609 s->queues = g_new(NVMeQueuePair *, 1);
610 s->nr_queues = 1;
611 s->queues[0] = nvme_create_queue_pair(bs, 0, NVME_QUEUE_SIZE, errp);
612 if (!s->queues[0]) {
613 ret = -EINVAL;
614 goto out;
616 QEMU_BUILD_BUG_ON(NVME_QUEUE_SIZE & 0xF000);
617 s->regs->aqa = cpu_to_le32((NVME_QUEUE_SIZE << 16) | NVME_QUEUE_SIZE);
618 s->regs->asq = cpu_to_le64(s->queues[0]->sq.iova);
619 s->regs->acq = cpu_to_le64(s->queues[0]->cq.iova);
621 /* After setting up all control registers we can enable device now. */
622 s->regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << 20) |
623 (ctz32(NVME_SQ_ENTRY_BYTES) << 16) |
624 0x1);
625 /* Wait for CSTS.RDY = 1. */
626 now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
627 deadline = now + timeout_ms * 1000000;
628 while (!(le32_to_cpu(s->regs->csts) & 0x1)) {
629 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
630 error_setg(errp, "Timeout while waiting for device to start (%"
631 PRId64 " ms)",
632 timeout_ms);
633 ret = -ETIMEDOUT;
634 goto out;
638 ret = qemu_vfio_pci_init_irq(s->vfio, &s->irq_notifier,
639 VFIO_PCI_MSIX_IRQ_INDEX, errp);
640 if (ret) {
641 goto out;
643 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
644 false, nvme_handle_event, nvme_poll_cb);
646 nvme_identify(bs, namespace, &local_err);
647 if (local_err) {
648 error_propagate(errp, local_err);
649 ret = -EIO;
650 goto out;
653 /* Set up command queues. */
654 if (!nvme_add_io_queue(bs, errp)) {
655 ret = -EIO;
657 out:
658 /* Cleaning up is done in nvme_file_open() upon error. */
659 return ret;
662 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
664 * nvme://0000:44:00.0/1
666 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
667 * is the PCI address, and the last part is the namespace number starting from
668 * 1 according to the NVMe spec. */
669 static void nvme_parse_filename(const char *filename, QDict *options,
670 Error **errp)
672 int pref = strlen("nvme://");
674 if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
675 const char *tmp = filename + pref;
676 char *device;
677 const char *namespace;
678 unsigned long ns;
679 const char *slash = strchr(tmp, '/');
680 if (!slash) {
681 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
682 return;
684 device = g_strndup(tmp, slash - tmp);
685 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
686 g_free(device);
687 namespace = slash + 1;
688 if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
689 error_setg(errp, "Invalid namespace '%s', positive number expected",
690 namespace);
691 return;
693 qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
694 *namespace ? namespace : "1");
698 static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
699 Error **errp)
701 int ret;
702 BDRVNVMeState *s = bs->opaque;
703 NvmeCmd cmd = {
704 .opcode = NVME_ADM_CMD_SET_FEATURES,
705 .nsid = cpu_to_le32(s->nsid),
706 .cdw10 = cpu_to_le32(0x06),
707 .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
710 ret = nvme_cmd_sync(bs, s->queues[0], &cmd);
711 if (ret) {
712 error_setg(errp, "Failed to configure NVMe write cache");
714 return ret;
717 static void nvme_close(BlockDriverState *bs)
719 int i;
720 BDRVNVMeState *s = bs->opaque;
722 for (i = 0; i < s->nr_queues; ++i) {
723 nvme_free_queue_pair(bs, s->queues[i]);
725 g_free(s->queues);
726 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
727 false, NULL, NULL);
728 event_notifier_cleanup(&s->irq_notifier);
729 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)s->regs, 0, NVME_BAR_SIZE);
730 qemu_vfio_close(s->vfio);
733 static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
734 Error **errp)
736 const char *device;
737 QemuOpts *opts;
738 int namespace;
739 int ret;
740 BDRVNVMeState *s = bs->opaque;
742 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
743 qemu_opts_absorb_qdict(opts, options, &error_abort);
744 device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
745 if (!device) {
746 error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
747 qemu_opts_del(opts);
748 return -EINVAL;
751 namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
752 ret = nvme_init(bs, device, namespace, errp);
753 qemu_opts_del(opts);
754 if (ret) {
755 goto fail;
757 if (flags & BDRV_O_NOCACHE) {
758 if (!s->write_cache_supported) {
759 error_setg(errp,
760 "NVMe controller doesn't support write cache configuration");
761 ret = -EINVAL;
762 } else {
763 ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
764 errp);
766 if (ret) {
767 goto fail;
770 bs->supported_write_flags = BDRV_REQ_FUA;
771 return 0;
772 fail:
773 nvme_close(bs);
774 return ret;
777 static int64_t nvme_getlength(BlockDriverState *bs)
779 BDRVNVMeState *s = bs->opaque;
781 return s->nsze << BDRV_SECTOR_BITS;
784 /* Called with s->dma_map_lock */
785 static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
786 QEMUIOVector *qiov)
788 int r = 0;
789 BDRVNVMeState *s = bs->opaque;
791 s->dma_map_count -= qiov->size;
792 if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
793 r = qemu_vfio_dma_reset_temporary(s->vfio);
794 if (!r) {
795 qemu_co_queue_restart_all(&s->dma_flush_queue);
798 return r;
801 /* Called with s->dma_map_lock */
802 static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
803 NVMeRequest *req, QEMUIOVector *qiov)
805 BDRVNVMeState *s = bs->opaque;
806 uint64_t *pagelist = req->prp_list_page;
807 int i, j, r;
808 int entries = 0;
810 assert(qiov->size);
811 assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
812 assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
813 for (i = 0; i < qiov->niov; ++i) {
814 bool retry = true;
815 uint64_t iova;
816 try_map:
817 r = qemu_vfio_dma_map(s->vfio,
818 qiov->iov[i].iov_base,
819 qiov->iov[i].iov_len,
820 true, &iova);
821 if (r == -ENOMEM && retry) {
822 retry = false;
823 trace_nvme_dma_flush_queue_wait(s);
824 if (s->dma_map_count) {
825 trace_nvme_dma_map_flush(s);
826 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
827 } else {
828 r = qemu_vfio_dma_reset_temporary(s->vfio);
829 if (r) {
830 goto fail;
833 goto try_map;
835 if (r) {
836 goto fail;
839 for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
840 pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
842 trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
843 qiov->iov[i].iov_len / s->page_size);
846 s->dma_map_count += qiov->size;
848 assert(entries <= s->page_size / sizeof(uint64_t));
849 switch (entries) {
850 case 0:
851 abort();
852 case 1:
853 cmd->prp1 = pagelist[0];
854 cmd->prp2 = 0;
855 break;
856 case 2:
857 cmd->prp1 = pagelist[0];
858 cmd->prp2 = pagelist[1];
859 break;
860 default:
861 cmd->prp1 = pagelist[0];
862 cmd->prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
863 break;
865 trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
866 for (i = 0; i < entries; ++i) {
867 trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
869 return 0;
870 fail:
871 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
872 * increment s->dma_map_count. This is okay for fixed mapping memory areas
873 * because they are already mapped before calling this function; for
874 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
875 * calling qemu_vfio_dma_reset_temporary when necessary. */
876 return r;
879 typedef struct {
880 Coroutine *co;
881 int ret;
882 AioContext *ctx;
883 } NVMeCoData;
885 static void nvme_rw_cb_bh(void *opaque)
887 NVMeCoData *data = opaque;
888 qemu_coroutine_enter(data->co);
891 static void nvme_rw_cb(void *opaque, int ret)
893 NVMeCoData *data = opaque;
894 data->ret = ret;
895 if (!data->co) {
896 /* The rw coroutine hasn't yielded, don't try to enter. */
897 return;
899 aio_bh_schedule_oneshot(data->ctx, nvme_rw_cb_bh, data);
902 static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
903 uint64_t offset, uint64_t bytes,
904 QEMUIOVector *qiov,
905 bool is_write,
906 int flags)
908 int r;
909 BDRVNVMeState *s = bs->opaque;
910 NVMeQueuePair *ioq = s->queues[1];
911 NVMeRequest *req;
912 uint32_t cdw12 = (((bytes >> BDRV_SECTOR_BITS) - 1) & 0xFFFF) |
913 (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
914 NvmeCmd cmd = {
915 .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
916 .nsid = cpu_to_le32(s->nsid),
917 .cdw10 = cpu_to_le32((offset >> BDRV_SECTOR_BITS) & 0xFFFFFFFF),
918 .cdw11 = cpu_to_le32(((offset >> BDRV_SECTOR_BITS) >> 32) & 0xFFFFFFFF),
919 .cdw12 = cpu_to_le32(cdw12),
921 NVMeCoData data = {
922 .ctx = bdrv_get_aio_context(bs),
923 .ret = -EINPROGRESS,
926 trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
927 assert(s->nr_queues > 1);
928 req = nvme_get_free_req(ioq);
929 assert(req);
931 qemu_co_mutex_lock(&s->dma_map_lock);
932 r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
933 qemu_co_mutex_unlock(&s->dma_map_lock);
934 if (r) {
935 req->busy = false;
936 return r;
938 nvme_submit_command(s, ioq, req, &cmd, nvme_rw_cb, &data);
940 data.co = qemu_coroutine_self();
941 while (data.ret == -EINPROGRESS) {
942 qemu_coroutine_yield();
945 qemu_co_mutex_lock(&s->dma_map_lock);
946 r = nvme_cmd_unmap_qiov(bs, qiov);
947 qemu_co_mutex_unlock(&s->dma_map_lock);
948 if (r) {
949 return r;
952 trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
953 return data.ret;
956 static inline bool nvme_qiov_aligned(BlockDriverState *bs,
957 const QEMUIOVector *qiov)
959 int i;
960 BDRVNVMeState *s = bs->opaque;
962 for (i = 0; i < qiov->niov; ++i) {
963 if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base, s->page_size) ||
964 !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, s->page_size)) {
965 trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
966 qiov->iov[i].iov_len, s->page_size);
967 return false;
970 return true;
973 static int nvme_co_prw(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
974 QEMUIOVector *qiov, bool is_write, int flags)
976 BDRVNVMeState *s = bs->opaque;
977 int r;
978 uint8_t *buf = NULL;
979 QEMUIOVector local_qiov;
981 assert(QEMU_IS_ALIGNED(offset, s->page_size));
982 assert(QEMU_IS_ALIGNED(bytes, s->page_size));
983 assert(bytes <= s->max_transfer);
984 if (nvme_qiov_aligned(bs, qiov)) {
985 return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
987 trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
988 buf = qemu_try_blockalign(bs, bytes);
990 if (!buf) {
991 return -ENOMEM;
993 qemu_iovec_init(&local_qiov, 1);
994 if (is_write) {
995 qemu_iovec_to_buf(qiov, 0, buf, bytes);
997 qemu_iovec_add(&local_qiov, buf, bytes);
998 r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
999 qemu_iovec_destroy(&local_qiov);
1000 if (!r && !is_write) {
1001 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1003 qemu_vfree(buf);
1004 return r;
1007 static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1008 uint64_t offset, uint64_t bytes,
1009 QEMUIOVector *qiov, int flags)
1011 return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1014 static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1015 uint64_t offset, uint64_t bytes,
1016 QEMUIOVector *qiov, int flags)
1018 return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1021 static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1023 BDRVNVMeState *s = bs->opaque;
1024 NVMeQueuePair *ioq = s->queues[1];
1025 NVMeRequest *req;
1026 NvmeCmd cmd = {
1027 .opcode = NVME_CMD_FLUSH,
1028 .nsid = cpu_to_le32(s->nsid),
1030 NVMeCoData data = {
1031 .ctx = bdrv_get_aio_context(bs),
1032 .ret = -EINPROGRESS,
1035 assert(s->nr_queues > 1);
1036 req = nvme_get_free_req(ioq);
1037 assert(req);
1038 nvme_submit_command(s, ioq, req, &cmd, nvme_rw_cb, &data);
1040 data.co = qemu_coroutine_self();
1041 if (data.ret == -EINPROGRESS) {
1042 qemu_coroutine_yield();
1045 return data.ret;
1049 static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1050 BlockReopenQueue *queue, Error **errp)
1052 return 0;
1055 static void nvme_refresh_filename(BlockDriverState *bs, QDict *opts)
1057 qdict_del(opts, "filename");
1059 if (!qdict_size(opts)) {
1060 snprintf(bs->exact_filename, sizeof(bs->exact_filename), "%s://",
1061 bs->drv->format_name);
1064 qdict_put_str(opts, "driver", bs->drv->format_name);
1065 bs->full_open_options = qobject_ref(opts);
1068 static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1070 BDRVNVMeState *s = bs->opaque;
1072 bs->bl.opt_mem_alignment = s->page_size;
1073 bs->bl.request_alignment = s->page_size;
1074 bs->bl.max_transfer = s->max_transfer;
1077 static void nvme_detach_aio_context(BlockDriverState *bs)
1079 BDRVNVMeState *s = bs->opaque;
1081 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
1082 false, NULL, NULL);
1085 static void nvme_attach_aio_context(BlockDriverState *bs,
1086 AioContext *new_context)
1088 BDRVNVMeState *s = bs->opaque;
1090 s->aio_context = new_context;
1091 aio_set_event_notifier(new_context, &s->irq_notifier,
1092 false, nvme_handle_event, nvme_poll_cb);
1095 static void nvme_aio_plug(BlockDriverState *bs)
1097 BDRVNVMeState *s = bs->opaque;
1098 assert(!s->plugged);
1099 s->plugged = true;
1102 static void nvme_aio_unplug(BlockDriverState *bs)
1104 int i;
1105 BDRVNVMeState *s = bs->opaque;
1106 assert(s->plugged);
1107 s->plugged = false;
1108 for (i = 1; i < s->nr_queues; i++) {
1109 NVMeQueuePair *q = s->queues[i];
1110 qemu_mutex_lock(&q->lock);
1111 nvme_kick(s, q);
1112 nvme_process_completion(s, q);
1113 qemu_mutex_unlock(&q->lock);
1117 static void nvme_register_buf(BlockDriverState *bs, void *host, size_t size)
1119 int ret;
1120 BDRVNVMeState *s = bs->opaque;
1122 ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL);
1123 if (ret) {
1124 /* FIXME: we may run out of IOVA addresses after repeated
1125 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1126 * doesn't reclaim addresses for fixed mappings. */
1127 error_report("nvme_register_buf failed: %s", strerror(-ret));
1131 static void nvme_unregister_buf(BlockDriverState *bs, void *host)
1133 BDRVNVMeState *s = bs->opaque;
1135 qemu_vfio_dma_unmap(s->vfio, host);
1138 static BlockDriver bdrv_nvme = {
1139 .format_name = "nvme",
1140 .protocol_name = "nvme",
1141 .instance_size = sizeof(BDRVNVMeState),
1143 .bdrv_parse_filename = nvme_parse_filename,
1144 .bdrv_file_open = nvme_file_open,
1145 .bdrv_close = nvme_close,
1146 .bdrv_getlength = nvme_getlength,
1148 .bdrv_co_preadv = nvme_co_preadv,
1149 .bdrv_co_pwritev = nvme_co_pwritev,
1150 .bdrv_co_flush_to_disk = nvme_co_flush,
1151 .bdrv_reopen_prepare = nvme_reopen_prepare,
1153 .bdrv_refresh_filename = nvme_refresh_filename,
1154 .bdrv_refresh_limits = nvme_refresh_limits,
1156 .bdrv_detach_aio_context = nvme_detach_aio_context,
1157 .bdrv_attach_aio_context = nvme_attach_aio_context,
1159 .bdrv_io_plug = nvme_aio_plug,
1160 .bdrv_io_unplug = nvme_aio_unplug,
1162 .bdrv_register_buf = nvme_register_buf,
1163 .bdrv_unregister_buf = nvme_unregister_buf,
1166 static void bdrv_nvme_init(void)
1168 bdrv_register(&bdrv_nvme);
1171 block_init(bdrv_nvme_init);