]> git.proxmox.com Git - mirror_qemu.git/blob - block/nvme.c
7628623c05a25241151d94c48a093d033a58ac79
[mirror_qemu.git] / block / nvme.c
1 /*
2 * NVMe block driver based on vfio
3 *
4 * Copyright 2016 - 2018 Red Hat, Inc.
5 *
6 * Authors:
7 * Fam Zheng <famz@redhat.com>
8 * Paolo Bonzini <pbonzini@redhat.com>
9 *
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.
12 */
13
14 #include "qemu/osdep.h"
15 #include <linux/vfio.h>
16 #include "qapi/error.h"
17 #include "qapi/qmp/qdict.h"
18 #include "qapi/qmp/qstring.h"
19 #include "qemu/error-report.h"
20 #include "qemu/main-loop.h"
21 #include "qemu/module.h"
22 #include "qemu/cutils.h"
23 #include "qemu/option.h"
24 #include "qemu/vfio-helpers.h"
25 #include "block/block_int.h"
26 #include "sysemu/replay.h"
27 #include "trace.h"
28
29 #include "block/nvme.h"
30
31 #define NVME_SQ_ENTRY_BYTES 64
32 #define NVME_CQ_ENTRY_BYTES 16
33 #define NVME_QUEUE_SIZE 128
34 #define NVME_DOORBELL_SIZE 4096
35
36 /*
37 * We have to leave one slot empty as that is the full queue case where
38 * head == tail + 1.
39 */
40 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
41
42 typedef struct BDRVNVMeState BDRVNVMeState;
43
44 /* Same index is used for queues and IRQs */
45 #define INDEX_ADMIN 0
46 #define INDEX_IO(n) (1 + n)
47
48 /* This driver shares a single MSIX IRQ for the admin and I/O queues */
49 enum {
50 MSIX_SHARED_IRQ_IDX = 0,
51 MSIX_IRQ_COUNT = 1
52 };
53
54 typedef struct {
55 int32_t head, tail;
56 uint8_t *queue;
57 uint64_t iova;
58 /* Hardware MMIO register */
59 volatile uint32_t *doorbell;
60 } NVMeQueue;
61
62 typedef struct {
63 BlockCompletionFunc *cb;
64 void *opaque;
65 int cid;
66 void *prp_list_page;
67 uint64_t prp_list_iova;
68 int free_req_next; /* q->reqs[] index of next free req */
69 } NVMeRequest;
70
71 typedef struct {
72 QemuMutex lock;
73
74 /* Read from I/O code path, initialized under BQL */
75 BDRVNVMeState *s;
76 int index;
77
78 /* Fields protected by BQL */
79 uint8_t *prp_list_pages;
80
81 /* Fields protected by @lock */
82 CoQueue free_req_queue;
83 NVMeQueue sq, cq;
84 int cq_phase;
85 int free_req_head;
86 NVMeRequest reqs[NVME_NUM_REQS];
87 int need_kick;
88 int inflight;
89
90 /* Thread-safe, no lock necessary */
91 QEMUBH *completion_bh;
92 } NVMeQueuePair;
93
94 struct BDRVNVMeState {
95 AioContext *aio_context;
96 QEMUVFIOState *vfio;
97 /* Memory mapped registers */
98 volatile struct {
99 uint32_t sq_tail;
100 uint32_t cq_head;
101 } *doorbells;
102 /* The submission/completion queue pairs.
103 * [0]: admin queue.
104 * [1..]: io queues.
105 */
106 NVMeQueuePair **queues;
107 unsigned queue_count;
108 size_t page_size;
109 /* How many uint32_t elements does each doorbell entry take. */
110 size_t doorbell_scale;
111 bool write_cache_supported;
112 EventNotifier irq_notifier[MSIX_IRQ_COUNT];
113
114 uint64_t nsze; /* Namespace size reported by identify command */
115 int nsid; /* The namespace id to read/write data. */
116 int blkshift;
117
118 uint64_t max_transfer;
119 bool plugged;
120
121 bool supports_write_zeroes;
122 bool supports_discard;
123
124 CoMutex dma_map_lock;
125 CoQueue dma_flush_queue;
126
127 /* Total size of mapped qiov, accessed under dma_map_lock */
128 int dma_map_count;
129
130 /* PCI address (required for nvme_refresh_filename()) */
131 char *device;
132
133 struct {
134 uint64_t completion_errors;
135 uint64_t aligned_accesses;
136 uint64_t unaligned_accesses;
137 } stats;
138 };
139
140 #define NVME_BLOCK_OPT_DEVICE "device"
141 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
142
143 static void nvme_process_completion_bh(void *opaque);
144
145 static QemuOptsList runtime_opts = {
146 .name = "nvme",
147 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
148 .desc = {
149 {
150 .name = NVME_BLOCK_OPT_DEVICE,
151 .type = QEMU_OPT_STRING,
152 .help = "NVMe PCI device address",
153 },
154 {
155 .name = NVME_BLOCK_OPT_NAMESPACE,
156 .type = QEMU_OPT_NUMBER,
157 .help = "NVMe namespace",
158 },
159 { /* end of list */ }
160 },
161 };
162
163 /* Returns true on success, false on failure. */
164 static bool nvme_init_queue(BDRVNVMeState *s, NVMeQueue *q,
165 unsigned nentries, size_t entry_bytes, Error **errp)
166 {
167 size_t bytes;
168 int r;
169
170 bytes = ROUND_UP(nentries * entry_bytes, s->page_size);
171 q->head = q->tail = 0;
172 q->queue = qemu_try_memalign(s->page_size, bytes);
173 if (!q->queue) {
174 error_setg(errp, "Cannot allocate queue");
175 return false;
176 }
177 memset(q->queue, 0, bytes);
178 r = qemu_vfio_dma_map(s->vfio, q->queue, bytes, false, &q->iova);
179 if (r) {
180 error_setg(errp, "Cannot map queue");
181 return false;
182 }
183 return true;
184 }
185
186 static void nvme_free_queue_pair(NVMeQueuePair *q)
187 {
188 trace_nvme_free_queue_pair(q->index, q);
189 if (q->completion_bh) {
190 qemu_bh_delete(q->completion_bh);
191 }
192 qemu_vfree(q->prp_list_pages);
193 qemu_vfree(q->sq.queue);
194 qemu_vfree(q->cq.queue);
195 qemu_mutex_destroy(&q->lock);
196 g_free(q);
197 }
198
199 static void nvme_free_req_queue_cb(void *opaque)
200 {
201 NVMeQueuePair *q = opaque;
202
203 qemu_mutex_lock(&q->lock);
204 while (qemu_co_enter_next(&q->free_req_queue, &q->lock)) {
205 /* Retry all pending requests */
206 }
207 qemu_mutex_unlock(&q->lock);
208 }
209
210 static NVMeQueuePair *nvme_create_queue_pair(BDRVNVMeState *s,
211 AioContext *aio_context,
212 unsigned idx, size_t size,
213 Error **errp)
214 {
215 int i, r;
216 NVMeQueuePair *q;
217 uint64_t prp_list_iova;
218
219 q = g_try_new0(NVMeQueuePair, 1);
220 if (!q) {
221 return NULL;
222 }
223 trace_nvme_create_queue_pair(idx, q, size, aio_context,
224 event_notifier_get_fd(s->irq_notifier));
225 q->prp_list_pages = qemu_try_memalign(s->page_size,
226 s->page_size * NVME_NUM_REQS);
227 if (!q->prp_list_pages) {
228 goto fail;
229 }
230 memset(q->prp_list_pages, 0, s->page_size * NVME_NUM_REQS);
231 qemu_mutex_init(&q->lock);
232 q->s = s;
233 q->index = idx;
234 qemu_co_queue_init(&q->free_req_queue);
235 q->completion_bh = aio_bh_new(aio_context, nvme_process_completion_bh, q);
236 r = qemu_vfio_dma_map(s->vfio, q->prp_list_pages,
237 s->page_size * NVME_NUM_REQS,
238 false, &prp_list_iova);
239 if (r) {
240 goto fail;
241 }
242 q->free_req_head = -1;
243 for (i = 0; i < NVME_NUM_REQS; i++) {
244 NVMeRequest *req = &q->reqs[i];
245 req->cid = i + 1;
246 req->free_req_next = q->free_req_head;
247 q->free_req_head = i;
248 req->prp_list_page = q->prp_list_pages + i * s->page_size;
249 req->prp_list_iova = prp_list_iova + i * s->page_size;
250 }
251
252 if (!nvme_init_queue(s, &q->sq, size, NVME_SQ_ENTRY_BYTES, errp)) {
253 goto fail;
254 }
255 q->sq.doorbell = &s->doorbells[idx * s->doorbell_scale].sq_tail;
256
257 if (!nvme_init_queue(s, &q->cq, size, NVME_CQ_ENTRY_BYTES, errp)) {
258 goto fail;
259 }
260 q->cq.doorbell = &s->doorbells[idx * s->doorbell_scale].cq_head;
261
262 return q;
263 fail:
264 nvme_free_queue_pair(q);
265 return NULL;
266 }
267
268 /* With q->lock */
269 static void nvme_kick(NVMeQueuePair *q)
270 {
271 BDRVNVMeState *s = q->s;
272
273 if (s->plugged || !q->need_kick) {
274 return;
275 }
276 trace_nvme_kick(s, q->index);
277 assert(!(q->sq.tail & 0xFF00));
278 /* Fence the write to submission queue entry before notifying the device. */
279 smp_wmb();
280 *q->sq.doorbell = cpu_to_le32(q->sq.tail);
281 q->inflight += q->need_kick;
282 q->need_kick = 0;
283 }
284
285 /* Find a free request element if any, otherwise:
286 * a) if in coroutine context, try to wait for one to become available;
287 * b) if not in coroutine, return NULL;
288 */
289 static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
290 {
291 NVMeRequest *req;
292
293 qemu_mutex_lock(&q->lock);
294
295 while (q->free_req_head == -1) {
296 if (qemu_in_coroutine()) {
297 trace_nvme_free_req_queue_wait(q->s, q->index);
298 qemu_co_queue_wait(&q->free_req_queue, &q->lock);
299 } else {
300 qemu_mutex_unlock(&q->lock);
301 return NULL;
302 }
303 }
304
305 req = &q->reqs[q->free_req_head];
306 q->free_req_head = req->free_req_next;
307 req->free_req_next = -1;
308
309 qemu_mutex_unlock(&q->lock);
310 return req;
311 }
312
313 /* With q->lock */
314 static void nvme_put_free_req_locked(NVMeQueuePair *q, NVMeRequest *req)
315 {
316 req->free_req_next = q->free_req_head;
317 q->free_req_head = req - q->reqs;
318 }
319
320 /* With q->lock */
321 static void nvme_wake_free_req_locked(NVMeQueuePair *q)
322 {
323 if (!qemu_co_queue_empty(&q->free_req_queue)) {
324 replay_bh_schedule_oneshot_event(q->s->aio_context,
325 nvme_free_req_queue_cb, q);
326 }
327 }
328
329 /* Insert a request in the freelist and wake waiters */
330 static void nvme_put_free_req_and_wake(NVMeQueuePair *q, NVMeRequest *req)
331 {
332 qemu_mutex_lock(&q->lock);
333 nvme_put_free_req_locked(q, req);
334 nvme_wake_free_req_locked(q);
335 qemu_mutex_unlock(&q->lock);
336 }
337
338 static inline int nvme_translate_error(const NvmeCqe *c)
339 {
340 uint16_t status = (le16_to_cpu(c->status) >> 1) & 0xFF;
341 if (status) {
342 trace_nvme_error(le32_to_cpu(c->result),
343 le16_to_cpu(c->sq_head),
344 le16_to_cpu(c->sq_id),
345 le16_to_cpu(c->cid),
346 le16_to_cpu(status));
347 }
348 switch (status) {
349 case 0:
350 return 0;
351 case 1:
352 return -ENOSYS;
353 case 2:
354 return -EINVAL;
355 default:
356 return -EIO;
357 }
358 }
359
360 /* With q->lock */
361 static bool nvme_process_completion(NVMeQueuePair *q)
362 {
363 BDRVNVMeState *s = q->s;
364 bool progress = false;
365 NVMeRequest *preq;
366 NVMeRequest req;
367 NvmeCqe *c;
368
369 trace_nvme_process_completion(s, q->index, q->inflight);
370 if (s->plugged) {
371 trace_nvme_process_completion_queue_plugged(s, q->index);
372 return false;
373 }
374
375 /*
376 * Support re-entrancy when a request cb() function invokes aio_poll().
377 * Pending completions must be visible to aio_poll() so that a cb()
378 * function can wait for the completion of another request.
379 *
380 * The aio_poll() loop will execute our BH and we'll resume completion
381 * processing there.
382 */
383 qemu_bh_schedule(q->completion_bh);
384
385 assert(q->inflight >= 0);
386 while (q->inflight) {
387 int ret;
388 int16_t cid;
389
390 c = (NvmeCqe *)&q->cq.queue[q->cq.head * NVME_CQ_ENTRY_BYTES];
391 if ((le16_to_cpu(c->status) & 0x1) == q->cq_phase) {
392 break;
393 }
394 ret = nvme_translate_error(c);
395 if (ret) {
396 s->stats.completion_errors++;
397 }
398 q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
399 if (!q->cq.head) {
400 q->cq_phase = !q->cq_phase;
401 }
402 cid = le16_to_cpu(c->cid);
403 if (cid == 0 || cid > NVME_QUEUE_SIZE) {
404 warn_report("NVMe: Unexpected CID in completion queue: %"PRIu32", "
405 "queue size: %u", cid, NVME_QUEUE_SIZE);
406 continue;
407 }
408 trace_nvme_complete_command(s, q->index, cid);
409 preq = &q->reqs[cid - 1];
410 req = *preq;
411 assert(req.cid == cid);
412 assert(req.cb);
413 nvme_put_free_req_locked(q, preq);
414 preq->cb = preq->opaque = NULL;
415 q->inflight--;
416 qemu_mutex_unlock(&q->lock);
417 req.cb(req.opaque, ret);
418 qemu_mutex_lock(&q->lock);
419 progress = true;
420 }
421 if (progress) {
422 /* Notify the device so it can post more completions. */
423 smp_mb_release();
424 *q->cq.doorbell = cpu_to_le32(q->cq.head);
425 nvme_wake_free_req_locked(q);
426 }
427
428 qemu_bh_cancel(q->completion_bh);
429
430 return progress;
431 }
432
433 static void nvme_process_completion_bh(void *opaque)
434 {
435 NVMeQueuePair *q = opaque;
436
437 /*
438 * We're being invoked because a nvme_process_completion() cb() function
439 * called aio_poll(). The callback may be waiting for further completions
440 * so notify the device that it has space to fill in more completions now.
441 */
442 smp_mb_release();
443 *q->cq.doorbell = cpu_to_le32(q->cq.head);
444 nvme_wake_free_req_locked(q);
445
446 nvme_process_completion(q);
447 }
448
449 static void nvme_trace_command(const NvmeCmd *cmd)
450 {
451 int i;
452
453 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW)) {
454 return;
455 }
456 for (i = 0; i < 8; ++i) {
457 uint8_t *cmdp = (uint8_t *)cmd + i * 8;
458 trace_nvme_submit_command_raw(cmdp[0], cmdp[1], cmdp[2], cmdp[3],
459 cmdp[4], cmdp[5], cmdp[6], cmdp[7]);
460 }
461 }
462
463 static void nvme_submit_command(NVMeQueuePair *q, NVMeRequest *req,
464 NvmeCmd *cmd, BlockCompletionFunc cb,
465 void *opaque)
466 {
467 assert(!req->cb);
468 req->cb = cb;
469 req->opaque = opaque;
470 cmd->cid = cpu_to_le32(req->cid);
471
472 trace_nvme_submit_command(q->s, q->index, req->cid);
473 nvme_trace_command(cmd);
474 qemu_mutex_lock(&q->lock);
475 memcpy((uint8_t *)q->sq.queue +
476 q->sq.tail * NVME_SQ_ENTRY_BYTES, cmd, sizeof(*cmd));
477 q->sq.tail = (q->sq.tail + 1) % NVME_QUEUE_SIZE;
478 q->need_kick++;
479 nvme_kick(q);
480 nvme_process_completion(q);
481 qemu_mutex_unlock(&q->lock);
482 }
483
484 static void nvme_admin_cmd_sync_cb(void *opaque, int ret)
485 {
486 int *pret = opaque;
487 *pret = ret;
488 aio_wait_kick();
489 }
490
491 static int nvme_admin_cmd_sync(BlockDriverState *bs, NvmeCmd *cmd)
492 {
493 BDRVNVMeState *s = bs->opaque;
494 NVMeQueuePair *q = s->queues[INDEX_ADMIN];
495 AioContext *aio_context = bdrv_get_aio_context(bs);
496 NVMeRequest *req;
497 int ret = -EINPROGRESS;
498 req = nvme_get_free_req(q);
499 if (!req) {
500 return -EBUSY;
501 }
502 nvme_submit_command(q, req, cmd, nvme_admin_cmd_sync_cb, &ret);
503
504 AIO_WAIT_WHILE(aio_context, ret == -EINPROGRESS);
505 return ret;
506 }
507
508 /* Returns true on success, false on failure. */
509 static bool nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
510 {
511 BDRVNVMeState *s = bs->opaque;
512 bool ret = false;
513 union {
514 NvmeIdCtrl ctrl;
515 NvmeIdNs ns;
516 } *id;
517 NvmeLBAF *lbaf;
518 uint16_t oncs;
519 int r;
520 uint64_t iova;
521 NvmeCmd cmd = {
522 .opcode = NVME_ADM_CMD_IDENTIFY,
523 .cdw10 = cpu_to_le32(0x1),
524 };
525 size_t id_size = QEMU_ALIGN_UP(sizeof(*id), qemu_real_host_page_size);
526
527 id = qemu_try_memalign(qemu_real_host_page_size, id_size);
528 if (!id) {
529 error_setg(errp, "Cannot allocate buffer for identify response");
530 goto out;
531 }
532 r = qemu_vfio_dma_map(s->vfio, id, id_size, true, &iova);
533 if (r) {
534 error_setg(errp, "Cannot map buffer for DMA");
535 goto out;
536 }
537
538 memset(id, 0, id_size);
539 cmd.dptr.prp1 = cpu_to_le64(iova);
540 if (nvme_admin_cmd_sync(bs, &cmd)) {
541 error_setg(errp, "Failed to identify controller");
542 goto out;
543 }
544
545 if (le32_to_cpu(id->ctrl.nn) < namespace) {
546 error_setg(errp, "Invalid namespace");
547 goto out;
548 }
549 s->write_cache_supported = le32_to_cpu(id->ctrl.vwc) & 0x1;
550 s->max_transfer = (id->ctrl.mdts ? 1 << id->ctrl.mdts : 0) * s->page_size;
551 /* For now the page list buffer per command is one page, to hold at most
552 * s->page_size / sizeof(uint64_t) entries. */
553 s->max_transfer = MIN_NON_ZERO(s->max_transfer,
554 s->page_size / sizeof(uint64_t) * s->page_size);
555
556 oncs = le16_to_cpu(id->ctrl.oncs);
557 s->supports_write_zeroes = !!(oncs & NVME_ONCS_WRITE_ZEROES);
558 s->supports_discard = !!(oncs & NVME_ONCS_DSM);
559
560 memset(id, 0, id_size);
561 cmd.cdw10 = 0;
562 cmd.nsid = cpu_to_le32(namespace);
563 if (nvme_admin_cmd_sync(bs, &cmd)) {
564 error_setg(errp, "Failed to identify namespace");
565 goto out;
566 }
567
568 s->nsze = le64_to_cpu(id->ns.nsze);
569 lbaf = &id->ns.lbaf[NVME_ID_NS_FLBAS_INDEX(id->ns.flbas)];
570
571 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id->ns.dlfeat) &&
572 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id->ns.dlfeat) ==
573 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES) {
574 bs->supported_write_flags |= BDRV_REQ_MAY_UNMAP;
575 }
576
577 if (lbaf->ms) {
578 error_setg(errp, "Namespaces with metadata are not yet supported");
579 goto out;
580 }
581
582 if (lbaf->ds < BDRV_SECTOR_BITS || lbaf->ds > 12 ||
583 (1 << lbaf->ds) > s->page_size)
584 {
585 error_setg(errp, "Namespace has unsupported block size (2^%d)",
586 lbaf->ds);
587 goto out;
588 }
589
590 ret = true;
591 s->blkshift = lbaf->ds;
592 out:
593 qemu_vfio_dma_unmap(s->vfio, id);
594 qemu_vfree(id);
595
596 return ret;
597 }
598
599 static bool nvme_poll_queue(NVMeQueuePair *q)
600 {
601 bool progress = false;
602
603 const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
604 NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
605
606 trace_nvme_poll_queue(q->s, q->index);
607 /*
608 * Do an early check for completions. q->lock isn't needed because
609 * nvme_process_completion() only runs in the event loop thread and
610 * cannot race with itself.
611 */
612 if ((le16_to_cpu(cqe->status) & 0x1) == q->cq_phase) {
613 return false;
614 }
615
616 qemu_mutex_lock(&q->lock);
617 while (nvme_process_completion(q)) {
618 /* Keep polling */
619 progress = true;
620 }
621 qemu_mutex_unlock(&q->lock);
622
623 return progress;
624 }
625
626 static bool nvme_poll_queues(BDRVNVMeState *s)
627 {
628 bool progress = false;
629 int i;
630
631 for (i = 0; i < s->queue_count; i++) {
632 if (nvme_poll_queue(s->queues[i])) {
633 progress = true;
634 }
635 }
636 return progress;
637 }
638
639 static void nvme_handle_event(EventNotifier *n)
640 {
641 BDRVNVMeState *s = container_of(n, BDRVNVMeState,
642 irq_notifier[MSIX_SHARED_IRQ_IDX]);
643
644 trace_nvme_handle_event(s);
645 event_notifier_test_and_clear(n);
646 nvme_poll_queues(s);
647 }
648
649 static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
650 {
651 BDRVNVMeState *s = bs->opaque;
652 unsigned n = s->queue_count;
653 NVMeQueuePair *q;
654 NvmeCmd cmd;
655 unsigned queue_size = NVME_QUEUE_SIZE;
656
657 assert(n <= UINT16_MAX);
658 q = nvme_create_queue_pair(s, bdrv_get_aio_context(bs),
659 n, queue_size, errp);
660 if (!q) {
661 return false;
662 }
663 cmd = (NvmeCmd) {
664 .opcode = NVME_ADM_CMD_CREATE_CQ,
665 .dptr.prp1 = cpu_to_le64(q->cq.iova),
666 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
667 .cdw11 = cpu_to_le32(NVME_CQ_IEN | NVME_CQ_PC),
668 };
669 if (nvme_admin_cmd_sync(bs, &cmd)) {
670 error_setg(errp, "Failed to create CQ io queue [%u]", n);
671 goto out_error;
672 }
673 cmd = (NvmeCmd) {
674 .opcode = NVME_ADM_CMD_CREATE_SQ,
675 .dptr.prp1 = cpu_to_le64(q->sq.iova),
676 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
677 .cdw11 = cpu_to_le32(NVME_SQ_PC | (n << 16)),
678 };
679 if (nvme_admin_cmd_sync(bs, &cmd)) {
680 error_setg(errp, "Failed to create SQ io queue [%u]", n);
681 goto out_error;
682 }
683 s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
684 s->queues[n] = q;
685 s->queue_count++;
686 return true;
687 out_error:
688 nvme_free_queue_pair(q);
689 return false;
690 }
691
692 static bool nvme_poll_cb(void *opaque)
693 {
694 EventNotifier *e = opaque;
695 BDRVNVMeState *s = container_of(e, BDRVNVMeState,
696 irq_notifier[MSIX_SHARED_IRQ_IDX]);
697
698 return nvme_poll_queues(s);
699 }
700
701 static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
702 Error **errp)
703 {
704 BDRVNVMeState *s = bs->opaque;
705 NVMeQueuePair *q;
706 AioContext *aio_context = bdrv_get_aio_context(bs);
707 int ret;
708 uint64_t cap;
709 uint64_t timeout_ms;
710 uint64_t deadline, now;
711 volatile NvmeBar *regs = NULL;
712
713 qemu_co_mutex_init(&s->dma_map_lock);
714 qemu_co_queue_init(&s->dma_flush_queue);
715 s->device = g_strdup(device);
716 s->nsid = namespace;
717 s->aio_context = bdrv_get_aio_context(bs);
718 ret = event_notifier_init(&s->irq_notifier[MSIX_SHARED_IRQ_IDX], 0);
719 if (ret) {
720 error_setg(errp, "Failed to init event notifier");
721 return ret;
722 }
723
724 s->vfio = qemu_vfio_open_pci(device, errp);
725 if (!s->vfio) {
726 ret = -EINVAL;
727 goto out;
728 }
729
730 regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, sizeof(NvmeBar),
731 PROT_READ | PROT_WRITE, errp);
732 if (!regs) {
733 ret = -EINVAL;
734 goto out;
735 }
736 /* Perform initialize sequence as described in NVMe spec "7.6.1
737 * Initialization". */
738
739 cap = le64_to_cpu(regs->cap);
740 trace_nvme_controller_capability_raw(cap);
741 trace_nvme_controller_capability("Maximum Queue Entries Supported",
742 1 + NVME_CAP_MQES(cap));
743 trace_nvme_controller_capability("Contiguous Queues Required",
744 NVME_CAP_CQR(cap));
745 trace_nvme_controller_capability("Doorbell Stride",
746 2 << (2 + NVME_CAP_DSTRD(cap)));
747 trace_nvme_controller_capability("Subsystem Reset Supported",
748 NVME_CAP_NSSRS(cap));
749 trace_nvme_controller_capability("Memory Page Size Minimum",
750 1 << (12 + NVME_CAP_MPSMIN(cap)));
751 trace_nvme_controller_capability("Memory Page Size Maximum",
752 1 << (12 + NVME_CAP_MPSMAX(cap)));
753 if (!NVME_CAP_CSS(cap)) {
754 error_setg(errp, "Device doesn't support NVMe command set");
755 ret = -EINVAL;
756 goto out;
757 }
758
759 s->page_size = 1u << (12 + NVME_CAP_MPSMIN(cap));
760 s->doorbell_scale = (4 << NVME_CAP_DSTRD(cap)) / sizeof(uint32_t);
761 bs->bl.opt_mem_alignment = s->page_size;
762 bs->bl.request_alignment = s->page_size;
763 timeout_ms = MIN(500 * NVME_CAP_TO(cap), 30000);
764
765 /* Reset device to get a clean state. */
766 regs->cc = cpu_to_le32(le32_to_cpu(regs->cc) & 0xFE);
767 /* Wait for CSTS.RDY = 0. */
768 deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * SCALE_MS;
769 while (NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
770 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
771 error_setg(errp, "Timeout while waiting for device to reset (%"
772 PRId64 " ms)",
773 timeout_ms);
774 ret = -ETIMEDOUT;
775 goto out;
776 }
777 }
778
779 s->doorbells = qemu_vfio_pci_map_bar(s->vfio, 0, sizeof(NvmeBar),
780 NVME_DOORBELL_SIZE, PROT_WRITE, errp);
781 if (!s->doorbells) {
782 ret = -EINVAL;
783 goto out;
784 }
785
786 /* Set up admin queue. */
787 s->queues = g_new(NVMeQueuePair *, 1);
788 q = nvme_create_queue_pair(s, aio_context, 0, NVME_QUEUE_SIZE, errp);
789 if (!q) {
790 ret = -EINVAL;
791 goto out;
792 }
793 s->queues[INDEX_ADMIN] = q;
794 s->queue_count = 1;
795 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE - 1) & 0xF000);
796 regs->aqa = cpu_to_le32(((NVME_QUEUE_SIZE - 1) << AQA_ACQS_SHIFT) |
797 ((NVME_QUEUE_SIZE - 1) << AQA_ASQS_SHIFT));
798 regs->asq = cpu_to_le64(q->sq.iova);
799 regs->acq = cpu_to_le64(q->cq.iova);
800
801 /* After setting up all control registers we can enable device now. */
802 regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << CC_IOCQES_SHIFT) |
803 (ctz32(NVME_SQ_ENTRY_BYTES) << CC_IOSQES_SHIFT) |
804 CC_EN_MASK);
805 /* Wait for CSTS.RDY = 1. */
806 now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
807 deadline = now + timeout_ms * SCALE_MS;
808 while (!NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
809 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
810 error_setg(errp, "Timeout while waiting for device to start (%"
811 PRId64 " ms)",
812 timeout_ms);
813 ret = -ETIMEDOUT;
814 goto out;
815 }
816 }
817
818 ret = qemu_vfio_pci_init_irq(s->vfio, s->irq_notifier,
819 VFIO_PCI_MSIX_IRQ_INDEX, errp);
820 if (ret) {
821 goto out;
822 }
823 aio_set_event_notifier(bdrv_get_aio_context(bs),
824 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
825 false, nvme_handle_event, nvme_poll_cb);
826
827 if (!nvme_identify(bs, namespace, errp)) {
828 ret = -EIO;
829 goto out;
830 }
831
832 /* Set up command queues. */
833 if (!nvme_add_io_queue(bs, errp)) {
834 ret = -EIO;
835 }
836 out:
837 if (regs) {
838 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)regs, 0, sizeof(NvmeBar));
839 }
840
841 /* Cleaning up is done in nvme_file_open() upon error. */
842 return ret;
843 }
844
845 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
846 *
847 * nvme://0000:44:00.0/1
848 *
849 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
850 * is the PCI address, and the last part is the namespace number starting from
851 * 1 according to the NVMe spec. */
852 static void nvme_parse_filename(const char *filename, QDict *options,
853 Error **errp)
854 {
855 int pref = strlen("nvme://");
856
857 if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
858 const char *tmp = filename + pref;
859 char *device;
860 const char *namespace;
861 unsigned long ns;
862 const char *slash = strchr(tmp, '/');
863 if (!slash) {
864 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
865 return;
866 }
867 device = g_strndup(tmp, slash - tmp);
868 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
869 g_free(device);
870 namespace = slash + 1;
871 if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
872 error_setg(errp, "Invalid namespace '%s', positive number expected",
873 namespace);
874 return;
875 }
876 qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
877 *namespace ? namespace : "1");
878 }
879 }
880
881 static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
882 Error **errp)
883 {
884 int ret;
885 BDRVNVMeState *s = bs->opaque;
886 NvmeCmd cmd = {
887 .opcode = NVME_ADM_CMD_SET_FEATURES,
888 .nsid = cpu_to_le32(s->nsid),
889 .cdw10 = cpu_to_le32(0x06),
890 .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
891 };
892
893 ret = nvme_admin_cmd_sync(bs, &cmd);
894 if (ret) {
895 error_setg(errp, "Failed to configure NVMe write cache");
896 }
897 return ret;
898 }
899
900 static void nvme_close(BlockDriverState *bs)
901 {
902 BDRVNVMeState *s = bs->opaque;
903
904 for (unsigned i = 0; i < s->queue_count; ++i) {
905 nvme_free_queue_pair(s->queues[i]);
906 }
907 g_free(s->queues);
908 aio_set_event_notifier(bdrv_get_aio_context(bs),
909 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
910 false, NULL, NULL);
911 event_notifier_cleanup(&s->irq_notifier[MSIX_SHARED_IRQ_IDX]);
912 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)s->doorbells,
913 sizeof(NvmeBar), NVME_DOORBELL_SIZE);
914 qemu_vfio_close(s->vfio);
915
916 g_free(s->device);
917 }
918
919 static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
920 Error **errp)
921 {
922 const char *device;
923 QemuOpts *opts;
924 int namespace;
925 int ret;
926 BDRVNVMeState *s = bs->opaque;
927
928 bs->supported_write_flags = BDRV_REQ_FUA;
929
930 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
931 qemu_opts_absorb_qdict(opts, options, &error_abort);
932 device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
933 if (!device) {
934 error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
935 qemu_opts_del(opts);
936 return -EINVAL;
937 }
938
939 namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
940 ret = nvme_init(bs, device, namespace, errp);
941 qemu_opts_del(opts);
942 if (ret) {
943 goto fail;
944 }
945 if (flags & BDRV_O_NOCACHE) {
946 if (!s->write_cache_supported) {
947 error_setg(errp,
948 "NVMe controller doesn't support write cache configuration");
949 ret = -EINVAL;
950 } else {
951 ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
952 errp);
953 }
954 if (ret) {
955 goto fail;
956 }
957 }
958 return 0;
959 fail:
960 nvme_close(bs);
961 return ret;
962 }
963
964 static int64_t nvme_getlength(BlockDriverState *bs)
965 {
966 BDRVNVMeState *s = bs->opaque;
967 return s->nsze << s->blkshift;
968 }
969
970 static uint32_t nvme_get_blocksize(BlockDriverState *bs)
971 {
972 BDRVNVMeState *s = bs->opaque;
973 assert(s->blkshift >= BDRV_SECTOR_BITS && s->blkshift <= 12);
974 return UINT32_C(1) << s->blkshift;
975 }
976
977 static int nvme_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
978 {
979 uint32_t blocksize = nvme_get_blocksize(bs);
980 bsz->phys = blocksize;
981 bsz->log = blocksize;
982 return 0;
983 }
984
985 /* Called with s->dma_map_lock */
986 static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
987 QEMUIOVector *qiov)
988 {
989 int r = 0;
990 BDRVNVMeState *s = bs->opaque;
991
992 s->dma_map_count -= qiov->size;
993 if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
994 r = qemu_vfio_dma_reset_temporary(s->vfio);
995 if (!r) {
996 qemu_co_queue_restart_all(&s->dma_flush_queue);
997 }
998 }
999 return r;
1000 }
1001
1002 /* Called with s->dma_map_lock */
1003 static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
1004 NVMeRequest *req, QEMUIOVector *qiov)
1005 {
1006 BDRVNVMeState *s = bs->opaque;
1007 uint64_t *pagelist = req->prp_list_page;
1008 int i, j, r;
1009 int entries = 0;
1010
1011 assert(qiov->size);
1012 assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
1013 assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
1014 for (i = 0; i < qiov->niov; ++i) {
1015 bool retry = true;
1016 uint64_t iova;
1017 try_map:
1018 r = qemu_vfio_dma_map(s->vfio,
1019 qiov->iov[i].iov_base,
1020 qiov->iov[i].iov_len,
1021 true, &iova);
1022 if (r == -ENOMEM && retry) {
1023 retry = false;
1024 trace_nvme_dma_flush_queue_wait(s);
1025 if (s->dma_map_count) {
1026 trace_nvme_dma_map_flush(s);
1027 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
1028 } else {
1029 r = qemu_vfio_dma_reset_temporary(s->vfio);
1030 if (r) {
1031 goto fail;
1032 }
1033 }
1034 goto try_map;
1035 }
1036 if (r) {
1037 goto fail;
1038 }
1039
1040 for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
1041 pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
1042 }
1043 trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
1044 qiov->iov[i].iov_len / s->page_size);
1045 }
1046
1047 s->dma_map_count += qiov->size;
1048
1049 assert(entries <= s->page_size / sizeof(uint64_t));
1050 switch (entries) {
1051 case 0:
1052 abort();
1053 case 1:
1054 cmd->dptr.prp1 = pagelist[0];
1055 cmd->dptr.prp2 = 0;
1056 break;
1057 case 2:
1058 cmd->dptr.prp1 = pagelist[0];
1059 cmd->dptr.prp2 = pagelist[1];
1060 break;
1061 default:
1062 cmd->dptr.prp1 = pagelist[0];
1063 cmd->dptr.prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
1064 break;
1065 }
1066 trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
1067 for (i = 0; i < entries; ++i) {
1068 trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
1069 }
1070 return 0;
1071 fail:
1072 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1073 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1074 * because they are already mapped before calling this function; for
1075 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1076 * calling qemu_vfio_dma_reset_temporary when necessary. */
1077 return r;
1078 }
1079
1080 typedef struct {
1081 Coroutine *co;
1082 int ret;
1083 AioContext *ctx;
1084 } NVMeCoData;
1085
1086 static void nvme_rw_cb_bh(void *opaque)
1087 {
1088 NVMeCoData *data = opaque;
1089 qemu_coroutine_enter(data->co);
1090 }
1091
1092 static void nvme_rw_cb(void *opaque, int ret)
1093 {
1094 NVMeCoData *data = opaque;
1095 data->ret = ret;
1096 if (!data->co) {
1097 /* The rw coroutine hasn't yielded, don't try to enter. */
1098 return;
1099 }
1100 replay_bh_schedule_oneshot_event(data->ctx, nvme_rw_cb_bh, data);
1101 }
1102
1103 static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
1104 uint64_t offset, uint64_t bytes,
1105 QEMUIOVector *qiov,
1106 bool is_write,
1107 int flags)
1108 {
1109 int r;
1110 BDRVNVMeState *s = bs->opaque;
1111 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1112 NVMeRequest *req;
1113
1114 uint32_t cdw12 = (((bytes >> s->blkshift) - 1) & 0xFFFF) |
1115 (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
1116 NvmeCmd cmd = {
1117 .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
1118 .nsid = cpu_to_le32(s->nsid),
1119 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1120 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1121 .cdw12 = cpu_to_le32(cdw12),
1122 };
1123 NVMeCoData data = {
1124 .ctx = bdrv_get_aio_context(bs),
1125 .ret = -EINPROGRESS,
1126 };
1127
1128 trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
1129 assert(s->queue_count > 1);
1130 req = nvme_get_free_req(ioq);
1131 assert(req);
1132
1133 qemu_co_mutex_lock(&s->dma_map_lock);
1134 r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
1135 qemu_co_mutex_unlock(&s->dma_map_lock);
1136 if (r) {
1137 nvme_put_free_req_and_wake(ioq, req);
1138 return r;
1139 }
1140 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1141
1142 data.co = qemu_coroutine_self();
1143 while (data.ret == -EINPROGRESS) {
1144 qemu_coroutine_yield();
1145 }
1146
1147 qemu_co_mutex_lock(&s->dma_map_lock);
1148 r = nvme_cmd_unmap_qiov(bs, qiov);
1149 qemu_co_mutex_unlock(&s->dma_map_lock);
1150 if (r) {
1151 return r;
1152 }
1153
1154 trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
1155 return data.ret;
1156 }
1157
1158 static inline bool nvme_qiov_aligned(BlockDriverState *bs,
1159 const QEMUIOVector *qiov)
1160 {
1161 int i;
1162 BDRVNVMeState *s = bs->opaque;
1163
1164 for (i = 0; i < qiov->niov; ++i) {
1165 if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base, s->page_size) ||
1166 !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, s->page_size)) {
1167 trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
1168 qiov->iov[i].iov_len, s->page_size);
1169 return false;
1170 }
1171 }
1172 return true;
1173 }
1174
1175 static int nvme_co_prw(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1176 QEMUIOVector *qiov, bool is_write, int flags)
1177 {
1178 BDRVNVMeState *s = bs->opaque;
1179 int r;
1180 uint8_t *buf = NULL;
1181 QEMUIOVector local_qiov;
1182
1183 assert(QEMU_IS_ALIGNED(offset, s->page_size));
1184 assert(QEMU_IS_ALIGNED(bytes, s->page_size));
1185 assert(bytes <= s->max_transfer);
1186 if (nvme_qiov_aligned(bs, qiov)) {
1187 s->stats.aligned_accesses++;
1188 return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
1189 }
1190 s->stats.unaligned_accesses++;
1191 trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
1192 buf = qemu_try_memalign(s->page_size, bytes);
1193
1194 if (!buf) {
1195 return -ENOMEM;
1196 }
1197 qemu_iovec_init(&local_qiov, 1);
1198 if (is_write) {
1199 qemu_iovec_to_buf(qiov, 0, buf, bytes);
1200 }
1201 qemu_iovec_add(&local_qiov, buf, bytes);
1202 r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
1203 qemu_iovec_destroy(&local_qiov);
1204 if (!r && !is_write) {
1205 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1206 }
1207 qemu_vfree(buf);
1208 return r;
1209 }
1210
1211 static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1212 uint64_t offset, uint64_t bytes,
1213 QEMUIOVector *qiov, int flags)
1214 {
1215 return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1216 }
1217
1218 static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1219 uint64_t offset, uint64_t bytes,
1220 QEMUIOVector *qiov, int flags)
1221 {
1222 return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1223 }
1224
1225 static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1226 {
1227 BDRVNVMeState *s = bs->opaque;
1228 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1229 NVMeRequest *req;
1230 NvmeCmd cmd = {
1231 .opcode = NVME_CMD_FLUSH,
1232 .nsid = cpu_to_le32(s->nsid),
1233 };
1234 NVMeCoData data = {
1235 .ctx = bdrv_get_aio_context(bs),
1236 .ret = -EINPROGRESS,
1237 };
1238
1239 assert(s->queue_count > 1);
1240 req = nvme_get_free_req(ioq);
1241 assert(req);
1242 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1243
1244 data.co = qemu_coroutine_self();
1245 if (data.ret == -EINPROGRESS) {
1246 qemu_coroutine_yield();
1247 }
1248
1249 return data.ret;
1250 }
1251
1252
1253 static coroutine_fn int nvme_co_pwrite_zeroes(BlockDriverState *bs,
1254 int64_t offset,
1255 int bytes,
1256 BdrvRequestFlags flags)
1257 {
1258 BDRVNVMeState *s = bs->opaque;
1259 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1260 NVMeRequest *req;
1261
1262 uint32_t cdw12 = ((bytes >> s->blkshift) - 1) & 0xFFFF;
1263
1264 if (!s->supports_write_zeroes) {
1265 return -ENOTSUP;
1266 }
1267
1268 NvmeCmd cmd = {
1269 .opcode = NVME_CMD_WRITE_ZEROES,
1270 .nsid = cpu_to_le32(s->nsid),
1271 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1272 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1273 };
1274
1275 NVMeCoData data = {
1276 .ctx = bdrv_get_aio_context(bs),
1277 .ret = -EINPROGRESS,
1278 };
1279
1280 if (flags & BDRV_REQ_MAY_UNMAP) {
1281 cdw12 |= (1 << 25);
1282 }
1283
1284 if (flags & BDRV_REQ_FUA) {
1285 cdw12 |= (1 << 30);
1286 }
1287
1288 cmd.cdw12 = cpu_to_le32(cdw12);
1289
1290 trace_nvme_write_zeroes(s, offset, bytes, flags);
1291 assert(s->queue_count > 1);
1292 req = nvme_get_free_req(ioq);
1293 assert(req);
1294
1295 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1296
1297 data.co = qemu_coroutine_self();
1298 while (data.ret == -EINPROGRESS) {
1299 qemu_coroutine_yield();
1300 }
1301
1302 trace_nvme_rw_done(s, true, offset, bytes, data.ret);
1303 return data.ret;
1304 }
1305
1306
1307 static int coroutine_fn nvme_co_pdiscard(BlockDriverState *bs,
1308 int64_t offset,
1309 int bytes)
1310 {
1311 BDRVNVMeState *s = bs->opaque;
1312 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1313 NVMeRequest *req;
1314 NvmeDsmRange *buf;
1315 QEMUIOVector local_qiov;
1316 int ret;
1317
1318 NvmeCmd cmd = {
1319 .opcode = NVME_CMD_DSM,
1320 .nsid = cpu_to_le32(s->nsid),
1321 .cdw10 = cpu_to_le32(0), /*number of ranges - 0 based*/
1322 .cdw11 = cpu_to_le32(1 << 2), /*deallocate bit*/
1323 };
1324
1325 NVMeCoData data = {
1326 .ctx = bdrv_get_aio_context(bs),
1327 .ret = -EINPROGRESS,
1328 };
1329
1330 if (!s->supports_discard) {
1331 return -ENOTSUP;
1332 }
1333
1334 assert(s->queue_count > 1);
1335
1336 buf = qemu_try_memalign(s->page_size, s->page_size);
1337 if (!buf) {
1338 return -ENOMEM;
1339 }
1340 memset(buf, 0, s->page_size);
1341 buf->nlb = cpu_to_le32(bytes >> s->blkshift);
1342 buf->slba = cpu_to_le64(offset >> s->blkshift);
1343 buf->cattr = 0;
1344
1345 qemu_iovec_init(&local_qiov, 1);
1346 qemu_iovec_add(&local_qiov, buf, 4096);
1347
1348 req = nvme_get_free_req(ioq);
1349 assert(req);
1350
1351 qemu_co_mutex_lock(&s->dma_map_lock);
1352 ret = nvme_cmd_map_qiov(bs, &cmd, req, &local_qiov);
1353 qemu_co_mutex_unlock(&s->dma_map_lock);
1354
1355 if (ret) {
1356 nvme_put_free_req_and_wake(ioq, req);
1357 goto out;
1358 }
1359
1360 trace_nvme_dsm(s, offset, bytes);
1361
1362 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1363
1364 data.co = qemu_coroutine_self();
1365 while (data.ret == -EINPROGRESS) {
1366 qemu_coroutine_yield();
1367 }
1368
1369 qemu_co_mutex_lock(&s->dma_map_lock);
1370 ret = nvme_cmd_unmap_qiov(bs, &local_qiov);
1371 qemu_co_mutex_unlock(&s->dma_map_lock);
1372
1373 if (ret) {
1374 goto out;
1375 }
1376
1377 ret = data.ret;
1378 trace_nvme_dsm_done(s, offset, bytes, ret);
1379 out:
1380 qemu_iovec_destroy(&local_qiov);
1381 qemu_vfree(buf);
1382 return ret;
1383
1384 }
1385
1386
1387 static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1388 BlockReopenQueue *queue, Error **errp)
1389 {
1390 return 0;
1391 }
1392
1393 static void nvme_refresh_filename(BlockDriverState *bs)
1394 {
1395 BDRVNVMeState *s = bs->opaque;
1396
1397 snprintf(bs->exact_filename, sizeof(bs->exact_filename), "nvme://%s/%i",
1398 s->device, s->nsid);
1399 }
1400
1401 static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1402 {
1403 BDRVNVMeState *s = bs->opaque;
1404
1405 bs->bl.opt_mem_alignment = s->page_size;
1406 bs->bl.request_alignment = s->page_size;
1407 bs->bl.max_transfer = s->max_transfer;
1408 }
1409
1410 static void nvme_detach_aio_context(BlockDriverState *bs)
1411 {
1412 BDRVNVMeState *s = bs->opaque;
1413
1414 for (unsigned i = 0; i < s->queue_count; i++) {
1415 NVMeQueuePair *q = s->queues[i];
1416
1417 qemu_bh_delete(q->completion_bh);
1418 q->completion_bh = NULL;
1419 }
1420
1421 aio_set_event_notifier(bdrv_get_aio_context(bs),
1422 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1423 false, NULL, NULL);
1424 }
1425
1426 static void nvme_attach_aio_context(BlockDriverState *bs,
1427 AioContext *new_context)
1428 {
1429 BDRVNVMeState *s = bs->opaque;
1430
1431 s->aio_context = new_context;
1432 aio_set_event_notifier(new_context, &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1433 false, nvme_handle_event, nvme_poll_cb);
1434
1435 for (unsigned i = 0; i < s->queue_count; i++) {
1436 NVMeQueuePair *q = s->queues[i];
1437
1438 q->completion_bh =
1439 aio_bh_new(new_context, nvme_process_completion_bh, q);
1440 }
1441 }
1442
1443 static void nvme_aio_plug(BlockDriverState *bs)
1444 {
1445 BDRVNVMeState *s = bs->opaque;
1446 assert(!s->plugged);
1447 s->plugged = true;
1448 }
1449
1450 static void nvme_aio_unplug(BlockDriverState *bs)
1451 {
1452 BDRVNVMeState *s = bs->opaque;
1453 assert(s->plugged);
1454 s->plugged = false;
1455 for (unsigned i = INDEX_IO(0); i < s->queue_count; i++) {
1456 NVMeQueuePair *q = s->queues[i];
1457 qemu_mutex_lock(&q->lock);
1458 nvme_kick(q);
1459 nvme_process_completion(q);
1460 qemu_mutex_unlock(&q->lock);
1461 }
1462 }
1463
1464 static void nvme_register_buf(BlockDriverState *bs, void *host, size_t size)
1465 {
1466 int ret;
1467 BDRVNVMeState *s = bs->opaque;
1468
1469 ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL);
1470 if (ret) {
1471 /* FIXME: we may run out of IOVA addresses after repeated
1472 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1473 * doesn't reclaim addresses for fixed mappings. */
1474 error_report("nvme_register_buf failed: %s", strerror(-ret));
1475 }
1476 }
1477
1478 static void nvme_unregister_buf(BlockDriverState *bs, void *host)
1479 {
1480 BDRVNVMeState *s = bs->opaque;
1481
1482 qemu_vfio_dma_unmap(s->vfio, host);
1483 }
1484
1485 static BlockStatsSpecific *nvme_get_specific_stats(BlockDriverState *bs)
1486 {
1487 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
1488 BDRVNVMeState *s = bs->opaque;
1489
1490 stats->driver = BLOCKDEV_DRIVER_NVME;
1491 stats->u.nvme = (BlockStatsSpecificNvme) {
1492 .completion_errors = s->stats.completion_errors,
1493 .aligned_accesses = s->stats.aligned_accesses,
1494 .unaligned_accesses = s->stats.unaligned_accesses,
1495 };
1496
1497 return stats;
1498 }
1499
1500 static const char *const nvme_strong_runtime_opts[] = {
1501 NVME_BLOCK_OPT_DEVICE,
1502 NVME_BLOCK_OPT_NAMESPACE,
1503
1504 NULL
1505 };
1506
1507 static BlockDriver bdrv_nvme = {
1508 .format_name = "nvme",
1509 .protocol_name = "nvme",
1510 .instance_size = sizeof(BDRVNVMeState),
1511
1512 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
1513 .create_opts = &bdrv_create_opts_simple,
1514
1515 .bdrv_parse_filename = nvme_parse_filename,
1516 .bdrv_file_open = nvme_file_open,
1517 .bdrv_close = nvme_close,
1518 .bdrv_getlength = nvme_getlength,
1519 .bdrv_probe_blocksizes = nvme_probe_blocksizes,
1520
1521 .bdrv_co_preadv = nvme_co_preadv,
1522 .bdrv_co_pwritev = nvme_co_pwritev,
1523
1524 .bdrv_co_pwrite_zeroes = nvme_co_pwrite_zeroes,
1525 .bdrv_co_pdiscard = nvme_co_pdiscard,
1526
1527 .bdrv_co_flush_to_disk = nvme_co_flush,
1528 .bdrv_reopen_prepare = nvme_reopen_prepare,
1529
1530 .bdrv_refresh_filename = nvme_refresh_filename,
1531 .bdrv_refresh_limits = nvme_refresh_limits,
1532 .strong_runtime_opts = nvme_strong_runtime_opts,
1533 .bdrv_get_specific_stats = nvme_get_specific_stats,
1534
1535 .bdrv_detach_aio_context = nvme_detach_aio_context,
1536 .bdrv_attach_aio_context = nvme_attach_aio_context,
1537
1538 .bdrv_io_plug = nvme_aio_plug,
1539 .bdrv_io_unplug = nvme_aio_unplug,
1540
1541 .bdrv_register_buf = nvme_register_buf,
1542 .bdrv_unregister_buf = nvme_unregister_buf,
1543 };
1544
1545 static void bdrv_nvme_init(void)
1546 {
1547 bdrv_register(&bdrv_nvme);
1548 }
1549
1550 block_init(bdrv_nvme_init);