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