xref: /spdk/lib/nvmf/vfio_user.c (revision 9efad7468f30e1c5f7442823f5a8b17acd1e6a9b)
1 /*-
2  *   BSD LICENSE
3  *   Copyright (c) Intel Corporation. All rights reserved.
4  *   Copyright (c) 2019, Nutanix Inc. All rights reserved.
5  *
6  *   Redistribution and use in source and binary forms, with or without
7  *   modification, are permitted provided that the following conditions
8  *   are met:
9  *
10  *     * Redistributions of source code must retain the above copyright
11  *       notice, this list of conditions and the following disclaimer.
12  *     * Redistributions in binary form must reproduce the above copyright
13  *       notice, this list of conditions and the following disclaimer in
14  *       the documentation and/or other materials provided with the
15  *       distribution.
16  *     * Neither the name of Intel Corporation nor the names of its
17  *       contributors may be used to endorse or promote products derived
18  *       from this software without specific prior written permission.
19  *
20  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * NVMe over vfio-user transport
35  */
36 
37 #include <vfio-user/libvfio-user.h>
38 #include <vfio-user/pci_defs.h>
39 
40 #include "spdk/barrier.h"
41 #include "spdk/stdinc.h"
42 #include "spdk/assert.h"
43 #include "spdk/thread.h"
44 #include "spdk/nvmf_transport.h"
45 #include "spdk/sock.h"
46 #include "spdk/string.h"
47 #include "spdk/util.h"
48 #include "spdk/log.h"
49 
50 #include "transport.h"
51 
52 #include "nvmf_internal.h"
53 
54 #define NVMF_VFIO_USER_DEFAULT_MAX_QUEUE_DEPTH 256
55 #define NVMF_VFIO_USER_DEFAULT_AQ_DEPTH 32
56 #define NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR 64
57 #define NVMF_VFIO_USER_DEFAULT_MAX_IO_SIZE ((NVMF_REQ_MAX_BUFFERS - 1) << SHIFT_4KB)
58 #define NVMF_VFIO_USER_DEFAULT_IO_UNIT_SIZE NVMF_VFIO_USER_DEFAULT_MAX_IO_SIZE
59 
60 #define NVMF_VFIO_USER_DOORBELLS_OFFSET	0x1000
61 #define NVMF_VFIO_USER_DOORBELLS_SIZE 0x1000
62 
63 #define NVME_REG_CFG_SIZE       0x1000
64 #define NVME_REG_BAR0_SIZE      0x4000
65 #define NVME_IRQ_INTX_NUM       1
66 #define NVME_IRQ_MSIX_NUM	NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR
67 
68 struct nvmf_vfio_user_req;
69 struct nvmf_vfio_user_qpair;
70 
71 typedef int (*nvmf_vfio_user_req_cb_fn)(struct nvmf_vfio_user_req *req, void *cb_arg);
72 
73 /* 1 more for PRP2 list itself */
74 #define NVMF_VFIO_USER_MAX_IOVECS	(NVMF_REQ_MAX_BUFFERS + 1)
75 
76 enum nvmf_vfio_user_req_state {
77 	VFIO_USER_REQUEST_STATE_FREE = 0,
78 	VFIO_USER_REQUEST_STATE_EXECUTING,
79 };
80 
81 struct nvmf_vfio_user_req  {
82 	struct spdk_nvmf_request		req;
83 	struct spdk_nvme_cpl			rsp;
84 	struct spdk_nvme_cmd			cmd;
85 
86 	enum nvmf_vfio_user_req_state		state;
87 	nvmf_vfio_user_req_cb_fn		cb_fn;
88 	void					*cb_arg;
89 
90 	/* old CC before prop_set_cc fabric command */
91 	union spdk_nvme_cc_register		cc;
92 
93 	/* placeholder for gpa_to_vva memory map table, the IO buffer doesn't use it */
94 	dma_sg_t				*sg;
95 	struct iovec				iov[NVMF_VFIO_USER_MAX_IOVECS];
96 	uint8_t					iovcnt;
97 
98 	TAILQ_ENTRY(nvmf_vfio_user_req)		link;
99 };
100 
101 /*
102  * A NVMe queue.
103  */
104 struct nvme_q {
105 	bool is_cq;
106 
107 	void *addr;
108 
109 	dma_sg_t *sg;
110 	struct iovec iov;
111 
112 	uint32_t size;
113 	uint64_t prp1;
114 
115 	union {
116 		struct {
117 			uint32_t head;
118 			/* multiple SQs can be mapped to the same CQ */
119 			uint16_t cqid;
120 		};
121 		struct {
122 			uint32_t tail;
123 			uint16_t iv;
124 			bool ien;
125 			bool phase;
126 		};
127 	};
128 };
129 
130 enum nvmf_vfio_user_qpair_state {
131 	VFIO_USER_QPAIR_UNINITIALIZED = 0,
132 	VFIO_USER_QPAIR_ACTIVE,
133 	VFIO_USER_QPAIR_SQ_DELETED,
134 	VFIO_USER_QPAIR_INACTIVE,
135 	VFIO_USER_QPAIR_ERROR,
136 };
137 
138 struct nvmf_vfio_user_qpair {
139 	struct spdk_nvmf_qpair			qpair;
140 	struct spdk_nvmf_transport_poll_group	*group;
141 	struct nvmf_vfio_user_ctrlr		*ctrlr;
142 	struct nvmf_vfio_user_req		*reqs_internal;
143 	uint32_t				qsize;
144 	struct nvme_q				cq;
145 	struct nvme_q				sq;
146 	enum nvmf_vfio_user_qpair_state		state;
147 
148 	/* Copy of Create IO SQ command */
149 	struct spdk_nvme_cmd			create_io_sq_cmd;
150 
151 	TAILQ_HEAD(, nvmf_vfio_user_req)	reqs;
152 	/* Poll group entry */
153 	TAILQ_ENTRY(nvmf_vfio_user_qpair)	link;
154 	/* Connected queue pair entry */
155 	TAILQ_ENTRY(nvmf_vfio_user_qpair)	tailq;
156 };
157 
158 struct nvmf_vfio_user_poll_group {
159 	struct spdk_nvmf_transport_poll_group	group;
160 	TAILQ_HEAD(, nvmf_vfio_user_qpair)	qps;
161 };
162 
163 struct nvmf_vfio_user_ctrlr {
164 	struct nvmf_vfio_user_endpoint		*endpoint;
165 	struct nvmf_vfio_user_transport		*transport;
166 
167 	/* Connected queue pairs list */
168 	TAILQ_HEAD(, nvmf_vfio_user_qpair)	connected_qps;
169 
170 	struct spdk_thread			*thread;
171 	struct spdk_poller			*vfu_ctx_poller;
172 
173 	uint16_t				cntlid;
174 
175 	struct nvmf_vfio_user_qpair		*qp[NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR];
176 
177 	TAILQ_ENTRY(nvmf_vfio_user_ctrlr)	link;
178 
179 	volatile uint32_t			*doorbells;
180 
181 	/* internal CSTS.CFS register for vfio-user fatal errors */
182 	uint32_t				cfs : 1;
183 };
184 
185 struct nvmf_vfio_user_endpoint {
186 	vfu_ctx_t				*vfu_ctx;
187 	struct msixcap				*msix;
188 	vfu_pci_config_space_t			*pci_config_space;
189 	int					devmem_fd;
190 	volatile uint32_t			*doorbells;
191 
192 	struct spdk_nvme_transport_id		trid;
193 	const struct spdk_nvmf_subsystem	*subsystem;
194 
195 	struct nvmf_vfio_user_ctrlr		*ctrlr;
196 	pthread_mutex_t				lock;
197 
198 	TAILQ_ENTRY(nvmf_vfio_user_endpoint)	link;
199 };
200 
201 struct nvmf_vfio_user_transport_opts {
202 	bool					disable_mappable_bar0;
203 };
204 
205 struct nvmf_vfio_user_transport {
206 	struct spdk_nvmf_transport		transport;
207 	struct nvmf_vfio_user_transport_opts    transport_opts;
208 	pthread_mutex_t				lock;
209 	TAILQ_HEAD(, nvmf_vfio_user_endpoint)	endpoints;
210 };
211 
212 /*
213  * function prototypes
214  */
215 static volatile uint32_t *
216 hdbl(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvme_q *q);
217 
218 static volatile uint32_t *
219 tdbl(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvme_q *q);
220 
221 static int
222 nvmf_vfio_user_req_free(struct spdk_nvmf_request *req);
223 
224 static struct nvmf_vfio_user_req *
225 get_nvmf_vfio_user_req(struct nvmf_vfio_user_qpair *qpair);
226 
227 static int
228 nvme_cmd_map_prps(void *prv, struct spdk_nvme_cmd *cmd, struct iovec *iovs,
229 		  uint32_t max_iovcnt, uint32_t len, size_t mps,
230 		  void *(*gpa_to_vva)(void *prv, uint64_t addr, uint64_t len, int prot))
231 {
232 	uint64_t prp1, prp2;
233 	void *vva;
234 	uint32_t i;
235 	uint32_t residue_len, nents;
236 	uint64_t *prp_list;
237 	uint32_t iovcnt;
238 
239 	assert(max_iovcnt > 0);
240 
241 	prp1 = cmd->dptr.prp.prp1;
242 	prp2 = cmd->dptr.prp.prp2;
243 
244 	/* PRP1 may started with unaligned page address */
245 	residue_len = mps - (prp1 % mps);
246 	residue_len = spdk_min(len, residue_len);
247 
248 	vva = gpa_to_vva(prv, prp1, residue_len, PROT_READ | PROT_WRITE);
249 	if (spdk_unlikely(vva == NULL)) {
250 		SPDK_ERRLOG("GPA to VVA failed\n");
251 		return -EINVAL;
252 	}
253 	len -= residue_len;
254 	if (len && max_iovcnt < 2) {
255 		SPDK_ERRLOG("Too many page entries, at least two iovs are required\n");
256 		return -ERANGE;
257 	}
258 	iovs[0].iov_base = vva;
259 	iovs[0].iov_len = residue_len;
260 
261 	if (len) {
262 		if (spdk_unlikely(prp2 == 0)) {
263 			SPDK_ERRLOG("no PRP2, %d remaining\n", len);
264 			return -EINVAL;
265 		}
266 
267 		if (len <= mps) {
268 			/* 2 PRP used */
269 			iovcnt = 2;
270 			vva = gpa_to_vva(prv, prp2, len, PROT_READ | PROT_WRITE);
271 			if (spdk_unlikely(vva == NULL)) {
272 				SPDK_ERRLOG("no VVA for %#" PRIx64 ", len%#x\n",
273 					    prp2, len);
274 				return -EINVAL;
275 			}
276 			iovs[1].iov_base = vva;
277 			iovs[1].iov_len = len;
278 		} else {
279 			/* PRP list used */
280 			nents = (len + mps - 1) / mps;
281 			if (spdk_unlikely(nents + 1 > max_iovcnt)) {
282 				SPDK_ERRLOG("Too many page entries\n");
283 				return -ERANGE;
284 			}
285 
286 			vva = gpa_to_vva(prv, prp2, nents * sizeof(*prp_list), PROT_READ);
287 			if (spdk_unlikely(vva == NULL)) {
288 				SPDK_ERRLOG("no VVA for %#" PRIx64 ", nents=%#x\n",
289 					    prp2, nents);
290 				return -EINVAL;
291 			}
292 			prp_list = vva;
293 			i = 0;
294 			while (len != 0) {
295 				residue_len = spdk_min(len, mps);
296 				vva = gpa_to_vva(prv, prp_list[i], residue_len, PROT_READ | PROT_WRITE);
297 				if (spdk_unlikely(vva == NULL)) {
298 					SPDK_ERRLOG("no VVA for %#" PRIx64 ", residue_len=%#x\n",
299 						    prp_list[i], residue_len);
300 					return -EINVAL;
301 				}
302 				iovs[i + 1].iov_base = vva;
303 				iovs[i + 1].iov_len = residue_len;
304 				len -= residue_len;
305 				i++;
306 			}
307 			iovcnt = i + 1;
308 		}
309 	} else {
310 		/* 1 PRP used */
311 		iovcnt = 1;
312 	}
313 
314 	assert(iovcnt <= max_iovcnt);
315 	return iovcnt;
316 }
317 
318 static int
319 nvme_cmd_map_sgls_data(void *prv, struct spdk_nvme_sgl_descriptor *sgls, uint32_t num_sgls,
320 		       struct iovec *iovs, uint32_t max_iovcnt,
321 		       void *(*gpa_to_vva)(void *prv, uint64_t addr, uint64_t len, int prot))
322 {
323 	uint32_t i;
324 	void *vva;
325 
326 	if (spdk_unlikely(max_iovcnt < num_sgls)) {
327 		return -ERANGE;
328 	}
329 
330 	for (i = 0; i < num_sgls; i++) {
331 		if (spdk_unlikely(sgls[i].unkeyed.type != SPDK_NVME_SGL_TYPE_DATA_BLOCK)) {
332 			SPDK_ERRLOG("Invalid SGL type %u\n", sgls[i].unkeyed.type);
333 			return -EINVAL;
334 		}
335 		vva = gpa_to_vva(prv, sgls[i].address, sgls[i].unkeyed.length, PROT_READ | PROT_WRITE);
336 		if (spdk_unlikely(vva == NULL)) {
337 			SPDK_ERRLOG("GPA to VVA failed\n");
338 			return -EINVAL;
339 		}
340 		iovs[i].iov_base = vva;
341 		iovs[i].iov_len = sgls[i].unkeyed.length;
342 	}
343 
344 	return num_sgls;
345 }
346 
347 static int
348 nvme_cmd_map_sgls(void *prv, struct spdk_nvme_cmd *cmd, struct iovec *iovs, uint32_t max_iovcnt,
349 		  uint32_t len, size_t mps,
350 		  void *(*gpa_to_vva)(void *prv, uint64_t addr, uint64_t len, int prot))
351 {
352 	struct spdk_nvme_sgl_descriptor *sgl, *last_sgl;
353 	uint32_t num_sgls, seg_len;
354 	void *vva;
355 	int ret;
356 	uint32_t total_iovcnt = 0;
357 
358 	/* SGL cases */
359 	sgl = &cmd->dptr.sgl1;
360 
361 	/* only one SGL segment */
362 	if (sgl->unkeyed.type == SPDK_NVME_SGL_TYPE_DATA_BLOCK) {
363 		assert(max_iovcnt > 0);
364 		vva = gpa_to_vva(prv, sgl->address, sgl->unkeyed.length, PROT_READ | PROT_WRITE);
365 		if (spdk_unlikely(vva == NULL)) {
366 			SPDK_ERRLOG("GPA to VVA failed\n");
367 			return -EINVAL;
368 		}
369 		iovs[0].iov_base = vva;
370 		iovs[0].iov_len = sgl->unkeyed.length;
371 		assert(sgl->unkeyed.length == len);
372 
373 		return 1;
374 	}
375 
376 	for (;;) {
377 		if (spdk_unlikely((sgl->unkeyed.type != SPDK_NVME_SGL_TYPE_SEGMENT) &&
378 				  (sgl->unkeyed.type != SPDK_NVME_SGL_TYPE_LAST_SEGMENT))) {
379 			SPDK_ERRLOG("Invalid SGL type %u\n", sgl->unkeyed.type);
380 			return -EINVAL;
381 		}
382 
383 		seg_len = sgl->unkeyed.length;
384 		if (spdk_unlikely(seg_len % sizeof(struct spdk_nvme_sgl_descriptor))) {
385 			SPDK_ERRLOG("Invalid SGL segment len %u\n", seg_len);
386 			return -EINVAL;
387 		}
388 
389 		num_sgls = seg_len / sizeof(struct spdk_nvme_sgl_descriptor);
390 		vva = gpa_to_vva(prv, sgl->address, sgl->unkeyed.length, PROT_READ);
391 		if (spdk_unlikely(vva == NULL)) {
392 			SPDK_ERRLOG("GPA to VVA failed\n");
393 			return -EINVAL;
394 		}
395 
396 		/* sgl point to the first segment */
397 		sgl = (struct spdk_nvme_sgl_descriptor *)vva;
398 		last_sgl = &sgl[num_sgls - 1];
399 
400 		/* we are done */
401 		if (last_sgl->unkeyed.type == SPDK_NVME_SGL_TYPE_DATA_BLOCK) {
402 			/* map whole sgl list */
403 			ret = nvme_cmd_map_sgls_data(prv, sgl, num_sgls, &iovs[total_iovcnt],
404 						     max_iovcnt - total_iovcnt, gpa_to_vva);
405 			if (spdk_unlikely(ret < 0)) {
406 				return ret;
407 			}
408 			total_iovcnt += ret;
409 
410 			return total_iovcnt;
411 		}
412 
413 		if (num_sgls > 1) {
414 			/* map whole sgl exclude last_sgl */
415 			ret = nvme_cmd_map_sgls_data(prv, sgl, num_sgls - 1, &iovs[total_iovcnt],
416 						     max_iovcnt - total_iovcnt, gpa_to_vva);
417 			if (spdk_unlikely(ret < 0)) {
418 				return ret;
419 			}
420 			total_iovcnt += ret;
421 		}
422 
423 		/* move to next level's segments */
424 		sgl = last_sgl;
425 	}
426 
427 	return 0;
428 }
429 
430 static int
431 nvme_map_cmd(void *prv, struct spdk_nvme_cmd *cmd, struct iovec *iovs, uint32_t max_iovcnt,
432 	     uint32_t len, size_t mps,
433 	     void *(*gpa_to_vva)(void *prv, uint64_t addr, uint64_t len, int prot))
434 {
435 	if (cmd->psdt == SPDK_NVME_PSDT_PRP) {
436 		return nvme_cmd_map_prps(prv, cmd, iovs, max_iovcnt, len, mps, gpa_to_vva);
437 	}
438 
439 	return nvme_cmd_map_sgls(prv, cmd, iovs, max_iovcnt, len, mps, gpa_to_vva);
440 }
441 
442 static char *
443 endpoint_id(struct nvmf_vfio_user_endpoint *endpoint)
444 {
445 	return endpoint->trid.traddr;
446 }
447 
448 static char *
449 ctrlr_id(struct nvmf_vfio_user_ctrlr *ctrlr)
450 {
451 	if (!ctrlr || !ctrlr->endpoint) {
452 		return "Null Ctrlr";
453 	}
454 
455 	return endpoint_id(ctrlr->endpoint);
456 }
457 
458 static inline uint16_t
459 io_q_id(struct nvme_q *q)
460 {
461 
462 	struct nvmf_vfio_user_qpair *vu_qpair;
463 
464 	assert(q);
465 
466 	if (q->is_cq) {
467 		vu_qpair = SPDK_CONTAINEROF(q, struct nvmf_vfio_user_qpair, cq);
468 	} else {
469 		vu_qpair = SPDK_CONTAINEROF(q, struct nvmf_vfio_user_qpair, sq);
470 	}
471 	assert(vu_qpair);
472 	return vu_qpair->qpair.qid;
473 }
474 
475 static void
476 fail_ctrlr(struct nvmf_vfio_user_ctrlr *ctrlr)
477 {
478 	assert(ctrlr != NULL);
479 
480 	if (ctrlr->cfs == 0) {
481 		SPDK_ERRLOG(":%s failing controller\n", ctrlr_id(ctrlr));
482 	}
483 
484 	ctrlr->cfs = 1U;
485 }
486 
487 static inline bool
488 ctrlr_interrupt_enabled(struct nvmf_vfio_user_ctrlr *vu_ctrlr)
489 {
490 	assert(vu_ctrlr != NULL);
491 	assert(vu_ctrlr->endpoint != NULL);
492 
493 	vfu_pci_config_space_t *pci = vu_ctrlr->endpoint->pci_config_space;
494 
495 	return (!pci->hdr.cmd.id || vu_ctrlr->endpoint->msix->mxc.mxe);
496 }
497 
498 static void
499 nvmf_vfio_user_destroy_endpoint(struct nvmf_vfio_user_endpoint *endpoint)
500 {
501 	if (endpoint->doorbells) {
502 		munmap((void *)endpoint->doorbells, NVMF_VFIO_USER_DOORBELLS_SIZE);
503 	}
504 
505 	if (endpoint->devmem_fd > 0) {
506 		close(endpoint->devmem_fd);
507 	}
508 
509 	vfu_destroy_ctx(endpoint->vfu_ctx);
510 
511 	pthread_mutex_destroy(&endpoint->lock);
512 	free(endpoint);
513 }
514 
515 /* called when process exits */
516 static int
517 nvmf_vfio_user_destroy(struct spdk_nvmf_transport *transport,
518 		       spdk_nvmf_transport_destroy_done_cb cb_fn, void *cb_arg)
519 {
520 	struct nvmf_vfio_user_transport *vu_transport;
521 	struct nvmf_vfio_user_endpoint *endpoint, *tmp;
522 
523 	SPDK_DEBUGLOG(nvmf_vfio, "destroy transport\n");
524 
525 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport,
526 					transport);
527 
528 	(void)pthread_mutex_destroy(&vu_transport->lock);
529 
530 	TAILQ_FOREACH_SAFE(endpoint, &vu_transport->endpoints, link, tmp) {
531 		TAILQ_REMOVE(&vu_transport->endpoints, endpoint, link);
532 		nvmf_vfio_user_destroy_endpoint(endpoint);
533 	}
534 
535 	free(vu_transport);
536 
537 	if (cb_fn) {
538 		cb_fn(cb_arg);
539 	}
540 
541 	return 0;
542 }
543 
544 static const struct spdk_json_object_decoder vfio_user_transport_opts_decoder[] = {
545 	{
546 		"disable_mappable_bar0",
547 		offsetof(struct nvmf_vfio_user_transport, transport_opts.disable_mappable_bar0),
548 		spdk_json_decode_bool, true
549 	},
550 };
551 
552 static struct spdk_nvmf_transport *
553 nvmf_vfio_user_create(struct spdk_nvmf_transport_opts *opts)
554 {
555 	struct nvmf_vfio_user_transport *vu_transport;
556 	int err;
557 
558 	vu_transport = calloc(1, sizeof(*vu_transport));
559 	if (vu_transport == NULL) {
560 		SPDK_ERRLOG("Transport alloc fail: %m\n");
561 		return NULL;
562 	}
563 
564 	err = pthread_mutex_init(&vu_transport->lock, NULL);
565 	if (err != 0) {
566 		SPDK_ERRLOG("Pthread initialisation failed (%d)\n", err);
567 		goto err;
568 	}
569 
570 	TAILQ_INIT(&vu_transport->endpoints);
571 
572 	if (opts->transport_specific != NULL &&
573 	    spdk_json_decode_object_relaxed(opts->transport_specific, vfio_user_transport_opts_decoder,
574 					    SPDK_COUNTOF(vfio_user_transport_opts_decoder),
575 					    vu_transport)) {
576 		SPDK_ERRLOG("spdk_json_decode_object_relaxed failed\n");
577 		free(vu_transport);
578 		return NULL;
579 	}
580 
581 	SPDK_DEBUGLOG(nvmf_vfio, "vfio_user transport: disable_mappable_bar0=%d\n",
582 		      vu_transport->transport_opts.disable_mappable_bar0);
583 
584 	return &vu_transport->transport;
585 
586 err:
587 	free(vu_transport);
588 
589 	return NULL;
590 }
591 
592 static uint32_t
593 max_queue_size(struct nvmf_vfio_user_ctrlr const *ctrlr)
594 {
595 	assert(ctrlr != NULL);
596 	assert(ctrlr->qp[0] != NULL);
597 	assert(ctrlr->qp[0]->qpair.ctrlr != NULL);
598 
599 	return ctrlr->qp[0]->qpair.ctrlr->vcprop.cap.bits.mqes + 1;
600 }
601 
602 static void *
603 map_one(vfu_ctx_t *ctx, uint64_t addr, uint64_t len, dma_sg_t *sg, struct iovec *iov, int prot)
604 {
605 	int ret;
606 
607 	assert(ctx != NULL);
608 	assert(sg != NULL);
609 	assert(iov != NULL);
610 
611 	ret = vfu_addr_to_sg(ctx, (void *)(uintptr_t)addr, len, sg, 1, prot);
612 	if (ret < 0) {
613 		return NULL;
614 	}
615 
616 	ret = vfu_map_sg(ctx, sg, iov, 1, 0);
617 	if (ret != 0) {
618 		return NULL;
619 	}
620 
621 	assert(iov->iov_base != NULL);
622 	return iov->iov_base;
623 }
624 
625 static inline uint32_t
626 sq_head(struct nvmf_vfio_user_qpair *qpair)
627 {
628 	assert(qpair != NULL);
629 	return qpair->sq.head;
630 }
631 
632 static inline void
633 sqhd_advance(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvmf_vfio_user_qpair *qpair)
634 {
635 	assert(ctrlr != NULL);
636 	assert(qpair != NULL);
637 	qpair->sq.head = (qpair->sq.head + 1) % qpair->sq.size;
638 }
639 
640 static int
641 map_q(struct nvmf_vfio_user_ctrlr *vu_ctrlr, struct nvme_q *q, bool is_cq, bool unmap)
642 {
643 	uint64_t len;
644 
645 	assert(q->size);
646 	assert(q->addr == NULL);
647 
648 	if (is_cq) {
649 		len = q->size * sizeof(struct spdk_nvme_cpl);
650 	} else {
651 		len = q->size * sizeof(struct spdk_nvme_cmd);
652 	}
653 
654 	q->addr = map_one(vu_ctrlr->endpoint->vfu_ctx, q->prp1, len, q->sg,
655 			  &q->iov, is_cq ? PROT_READ | PROT_WRITE : PROT_READ);
656 	if (q->addr == NULL) {
657 		return -EFAULT;
658 	}
659 
660 	if (unmap) {
661 		memset(q->addr, 0, len);
662 	}
663 
664 	return 0;
665 }
666 
667 static int
668 asq_setup(struct nvmf_vfio_user_ctrlr *ctrlr)
669 {
670 	struct nvme_q *sq;
671 	const struct spdk_nvmf_registers *regs;
672 	int ret;
673 
674 	assert(ctrlr != NULL);
675 	assert(ctrlr->qp[0] != NULL);
676 	assert(ctrlr->qp[0]->sq.addr == NULL);
677 	/* XXX ctrlr->asq == 0 is a valid memory address */
678 
679 	regs = spdk_nvmf_ctrlr_get_regs(ctrlr->qp[0]->qpair.ctrlr);
680 	sq = &ctrlr->qp[0]->sq;
681 	sq->size = regs->aqa.bits.asqs + 1;
682 	sq->prp1 = regs->asq;
683 	sq->head = 0;
684 	sq->cqid = 0;
685 	sq->is_cq = false;
686 
687 	ret = map_q(ctrlr, sq, false, true);
688 	if (ret) {
689 		return ret;
690 	}
691 
692 	*tdbl(ctrlr, sq) = 0;
693 
694 	return 0;
695 }
696 
697 static inline int
698 queue_index(uint16_t qid, int is_cq)
699 {
700 	return (qid * 2) + is_cq;
701 }
702 
703 static volatile uint32_t *
704 tdbl(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvme_q *q)
705 {
706 	assert(ctrlr != NULL);
707 	assert(q != NULL);
708 	assert(!q->is_cq);
709 
710 	return &ctrlr->doorbells[queue_index(io_q_id(q), false)];
711 }
712 
713 static volatile uint32_t *
714 hdbl(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvme_q *q)
715 {
716 	assert(ctrlr != NULL);
717 	assert(q != NULL);
718 	assert(q->is_cq);
719 
720 	return &ctrlr->doorbells[queue_index(io_q_id(q), true)];
721 }
722 
723 static inline bool
724 cq_is_full(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvme_q *q)
725 {
726 	assert(ctrlr != NULL);
727 	assert(q != NULL);
728 	assert(q->is_cq);
729 
730 	return ((q->tail + 1) % q->size) == *hdbl(ctrlr, q);
731 }
732 
733 static inline void
734 cq_tail_advance(struct nvme_q *q)
735 {
736 	assert(q != NULL);
737 	assert(q->is_cq);
738 
739 	assert(q->tail < q->size);
740 	q->tail++;
741 
742 	if (spdk_unlikely(q->tail == q->size)) {
743 		q->tail = 0;
744 		q->phase = !q->phase;
745 	}
746 }
747 
748 static int
749 acq_setup(struct nvmf_vfio_user_ctrlr *ctrlr)
750 {
751 	struct nvme_q *cq;
752 	const struct spdk_nvmf_registers *regs;
753 	int ret;
754 
755 	assert(ctrlr != NULL);
756 	assert(ctrlr->qp[0] != NULL);
757 	assert(ctrlr->qp[0]->cq.addr == NULL);
758 
759 	regs = spdk_nvmf_ctrlr_get_regs(ctrlr->qp[0]->qpair.ctrlr);
760 	assert(regs != NULL);
761 	cq = &ctrlr->qp[0]->cq;
762 	cq->size = regs->aqa.bits.acqs + 1;
763 	cq->prp1 = regs->acq;
764 	cq->tail = 0;
765 	cq->is_cq = true;
766 	cq->ien = true;
767 	cq->phase = true;
768 
769 	ret = map_q(ctrlr, cq, true, true);
770 	if (ret) {
771 		return ret;
772 	}
773 	*hdbl(ctrlr, cq) = 0;
774 
775 	return 0;
776 }
777 
778 static inline dma_sg_t *
779 vu_req_to_sg_t(struct nvmf_vfio_user_req *vu_req, uint32_t iovcnt)
780 {
781 	return (dma_sg_t *)((uintptr_t)vu_req->sg + iovcnt * dma_sg_size());
782 }
783 
784 static void *
785 _map_one(void *prv, uint64_t addr, uint64_t len, int prot)
786 {
787 	struct spdk_nvmf_request *req = (struct spdk_nvmf_request *)prv;
788 	struct spdk_nvmf_qpair *qpair;
789 	struct nvmf_vfio_user_req *vu_req;
790 	struct nvmf_vfio_user_qpair *vu_qpair;
791 	void *ret;
792 
793 	assert(req != NULL);
794 	qpair = req->qpair;
795 	vu_req = SPDK_CONTAINEROF(req, struct nvmf_vfio_user_req, req);
796 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
797 
798 	assert(vu_req->iovcnt < NVMF_VFIO_USER_MAX_IOVECS);
799 	ret = map_one(vu_qpair->ctrlr->endpoint->vfu_ctx, addr, len,
800 		      vu_req_to_sg_t(vu_req, vu_req->iovcnt),
801 		      &vu_req->iov[vu_req->iovcnt], prot);
802 	if (spdk_likely(ret != NULL)) {
803 		vu_req->iovcnt++;
804 	}
805 	return ret;
806 }
807 
808 static int
809 vfio_user_map_cmd(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvmf_request *req,
810 		  struct iovec *iov, uint32_t length)
811 {
812 	/* Map PRP list to from Guest physical memory to
813 	 * virtual memory address.
814 	 */
815 	return nvme_map_cmd(req, &req->cmd->nvme_cmd, iov, NVMF_REQ_MAX_BUFFERS,
816 			    length, 4096, _map_one);
817 }
818 
819 static struct spdk_nvmf_request *
820 get_nvmf_req(struct nvmf_vfio_user_qpair *qp);
821 
822 static int
823 handle_cmd_req(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvme_cmd *cmd,
824 	       struct spdk_nvmf_request *req);
825 
826 /*
827  * Posts a CQE in the completion queue.
828  *
829  * @ctrlr: the vfio-user controller
830  * @cq: the completion queue
831  * @cdw0: cdw0 as reported by NVMf
832  * @sqid: submission queue ID
833  * @cid: command identifier in NVMe command
834  * @sc: the NVMe CQE status code
835  * @sct: the NVMe CQE status code type
836  */
837 static int
838 post_completion(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvme_q *cq,
839 		uint32_t cdw0, uint16_t sqid, uint16_t cid, uint16_t sc, uint16_t sct)
840 {
841 	struct spdk_nvme_cpl *cpl;
842 	const struct spdk_nvmf_registers *regs;
843 	int err;
844 
845 	assert(ctrlr != NULL);
846 
847 	if (spdk_unlikely(cq == NULL || cq->addr == NULL)) {
848 		return 0;
849 	}
850 
851 	regs = spdk_nvmf_ctrlr_get_regs(ctrlr->qp[0]->qpair.ctrlr);
852 	if (regs->csts.bits.shst != SPDK_NVME_SHST_NORMAL) {
853 		SPDK_DEBUGLOG(nvmf_vfio,
854 			      "%s: ignore completion SQ%d cid=%d status=%#x\n",
855 			      ctrlr_id(ctrlr), sqid, cid, sc);
856 		return 0;
857 	}
858 
859 	if (cq_is_full(ctrlr, cq)) {
860 		SPDK_ERRLOG("%s: CQ%d full (tail=%d, head=%d)\n",
861 			    ctrlr_id(ctrlr), io_q_id(cq), cq->tail, *hdbl(ctrlr, cq));
862 		return -1;
863 	}
864 
865 	cpl = ((struct spdk_nvme_cpl *)cq->addr) + cq->tail;
866 
867 	assert(ctrlr->qp[sqid] != NULL);
868 	SPDK_DEBUGLOG(nvmf_vfio,
869 		      "%s: request complete SQ%d cid=%d status=%#x SQ head=%#x CQ tail=%#x\n",
870 		      ctrlr_id(ctrlr), sqid, cid, sc, sq_head(ctrlr->qp[sqid]),
871 		      cq->tail);
872 
873 	cpl->sqhd = sq_head(ctrlr->qp[sqid]);
874 	cpl->sqid = sqid;
875 	cpl->cid = cid;
876 	cpl->cdw0 = cdw0;
877 	cpl->status.dnr = 0x0;
878 	cpl->status.m = 0x0;
879 	cpl->status.sct = sct;
880 	cpl->status.p = cq->phase;
881 	cpl->status.sc = sc;
882 
883 	cq_tail_advance(cq);
884 
885 	/*
886 	 * this function now executes at SPDK thread context, we
887 	 * might be triggerring interrupts from vfio-user thread context so
888 	 * check for race conditions.
889 	 */
890 	if (ctrlr_interrupt_enabled(ctrlr) && cq->ien) {
891 		err = vfu_irq_trigger(ctrlr->endpoint->vfu_ctx, cq->iv);
892 		if (err != 0) {
893 			SPDK_ERRLOG("%s: failed to trigger interrupt: %m\n",
894 				    ctrlr_id(ctrlr));
895 			return err;
896 		}
897 	}
898 
899 	return 0;
900 }
901 
902 static bool
903 io_q_exists(struct nvmf_vfio_user_ctrlr *vu_ctrlr, const uint16_t qid, const bool is_cq)
904 {
905 	assert(vu_ctrlr != NULL);
906 
907 	if (qid == 0 || qid >= NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR) {
908 		return false;
909 	}
910 
911 	if (vu_ctrlr->qp[qid] == NULL) {
912 		return false;
913 	}
914 
915 	if (!is_cq) {
916 		if (vu_ctrlr->qp[qid]->state == VFIO_USER_QPAIR_SQ_DELETED ||
917 		    vu_ctrlr->qp[qid]->state == VFIO_USER_QPAIR_UNINITIALIZED) {
918 			return false;
919 		}
920 	}
921 
922 	return true;
923 }
924 
925 static void
926 unmap_qp(struct nvmf_vfio_user_qpair *qp)
927 {
928 	struct nvmf_vfio_user_ctrlr *ctrlr;
929 
930 	if (qp->ctrlr == NULL) {
931 		return;
932 	}
933 	ctrlr = qp->ctrlr;
934 
935 	SPDK_DEBUGLOG(nvmf_vfio, "%s: unmap QP%d\n",
936 		      ctrlr_id(ctrlr), qp->qpair.qid);
937 
938 	if (qp->sq.addr != NULL) {
939 		vfu_unmap_sg(ctrlr->endpoint->vfu_ctx, qp->sq.sg, &qp->sq.iov, 1);
940 		qp->sq.addr = NULL;
941 	}
942 
943 	if (qp->cq.addr != NULL) {
944 		vfu_unmap_sg(ctrlr->endpoint->vfu_ctx, qp->cq.sg, &qp->cq.iov, 1);
945 		qp->cq.addr = NULL;
946 	}
947 }
948 
949 static int
950 remap_qp(struct nvmf_vfio_user_qpair *vu_qpair)
951 {
952 	struct nvme_q *sq, *cq;
953 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
954 	int ret;
955 
956 	vu_ctrlr = vu_qpair->ctrlr;
957 	sq = &vu_qpair->sq;
958 	cq = &vu_qpair->cq;
959 
960 	if (sq->size) {
961 		ret = map_q(vu_ctrlr, sq, false, false);
962 		if (ret) {
963 			SPDK_DEBUGLOG(nvmf_vfio, "Memory isn't ready to remap SQID %d %#lx-%#lx\n",
964 				      io_q_id(sq), sq->prp1, sq->prp1 + sq->size * sizeof(struct spdk_nvme_cmd));
965 			return -EFAULT;
966 		}
967 	}
968 
969 	if (cq->size) {
970 		ret = map_q(vu_ctrlr, cq, true, false);
971 		if (ret) {
972 			SPDK_DEBUGLOG(nvmf_vfio, "Memory isn't ready to remap CQID %d %#lx-%#lx\n",
973 				      io_q_id(cq), cq->prp1, cq->prp1 + cq->size * sizeof(struct spdk_nvme_cpl));
974 			return -EFAULT;
975 		}
976 
977 	}
978 
979 	return 0;
980 }
981 
982 static void
983 free_qp(struct nvmf_vfio_user_ctrlr *ctrlr, uint16_t qid)
984 {
985 	struct nvmf_vfio_user_qpair *qpair;
986 	struct nvmf_vfio_user_req *vu_req;
987 	uint32_t i;
988 
989 	if (ctrlr == NULL) {
990 		return;
991 	}
992 
993 	qpair = ctrlr->qp[qid];
994 	if (qpair == NULL) {
995 		return;
996 	}
997 
998 	SPDK_DEBUGLOG(nvmf_vfio, "%s: destroy QP%d=%p\n", ctrlr_id(ctrlr),
999 		      qid, qpair);
1000 
1001 	unmap_qp(qpair);
1002 
1003 	for (i = 0; i < qpair->qsize; i++) {
1004 		vu_req = &qpair->reqs_internal[i];
1005 		free(vu_req->sg);
1006 	}
1007 	free(qpair->reqs_internal);
1008 
1009 	free(qpair->sq.sg);
1010 	free(qpair->cq.sg);
1011 	free(qpair);
1012 
1013 	ctrlr->qp[qid] = NULL;
1014 }
1015 
1016 /* This function can only fail because of memory allocation errors. */
1017 static int
1018 init_qp(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvmf_transport *transport,
1019 	const uint32_t qsize, const uint16_t id)
1020 {
1021 	uint32_t i;
1022 	struct nvmf_vfio_user_qpair *qpair;
1023 	struct nvmf_vfio_user_req *vu_req, *tmp;
1024 	struct spdk_nvmf_request *req;
1025 
1026 	assert(ctrlr != NULL);
1027 	assert(transport != NULL);
1028 
1029 	qpair = calloc(1, sizeof(*qpair));
1030 	if (qpair == NULL) {
1031 		return -ENOMEM;
1032 	}
1033 	qpair->sq.sg = calloc(1, dma_sg_size());
1034 	if (qpair->sq.sg == NULL) {
1035 		free(qpair);
1036 		return -ENOMEM;
1037 	}
1038 	qpair->cq.sg = calloc(1, dma_sg_size());
1039 	if (qpair->cq.sg == NULL) {
1040 		free(qpair->sq.sg);
1041 		free(qpair);
1042 		return -ENOMEM;
1043 	}
1044 
1045 	qpair->qpair.qid = id;
1046 	qpair->qpair.transport = transport;
1047 	qpair->ctrlr = ctrlr;
1048 	qpair->qsize = qsize;
1049 
1050 	TAILQ_INIT(&qpair->reqs);
1051 
1052 	qpair->reqs_internal = calloc(qsize, sizeof(struct nvmf_vfio_user_req));
1053 	if (qpair->reqs_internal == NULL) {
1054 		SPDK_ERRLOG("%s: error allocating reqs: %m\n", ctrlr_id(ctrlr));
1055 		goto reqs_err;
1056 	}
1057 
1058 	for (i = 0; i < qsize; i++) {
1059 		vu_req = &qpair->reqs_internal[i];
1060 		vu_req->sg = calloc(NVMF_VFIO_USER_MAX_IOVECS, dma_sg_size());
1061 		if (vu_req->sg == NULL) {
1062 			goto sg_err;
1063 		}
1064 
1065 		req = &vu_req->req;
1066 		req->qpair = &qpair->qpair;
1067 		req->rsp = (union nvmf_c2h_msg *)&vu_req->rsp;
1068 		req->cmd = (union nvmf_h2c_msg *)&vu_req->cmd;
1069 
1070 		TAILQ_INSERT_TAIL(&qpair->reqs, vu_req, link);
1071 	}
1072 
1073 	ctrlr->qp[id] = qpair;
1074 	return 0;
1075 
1076 sg_err:
1077 	TAILQ_FOREACH_SAFE(vu_req, &qpair->reqs, link, tmp) {
1078 		free(vu_req->sg);
1079 	}
1080 	free(qpair->reqs_internal);
1081 
1082 reqs_err:
1083 	free(qpair->sq.sg);
1084 	free(qpair->cq.sg);
1085 	free(qpair);
1086 	return -ENOMEM;
1087 }
1088 
1089 /*
1090  * Creates a completion or submission I/O queue. Returns 0 on success, -errno
1091  * on error.
1092  */
1093 static int
1094 handle_create_io_q(struct nvmf_vfio_user_ctrlr *ctrlr,
1095 		   struct spdk_nvme_cmd *cmd, const bool is_cq)
1096 {
1097 	uint16_t qid;
1098 	uint32_t qsize;
1099 	uint16_t sc = SPDK_NVME_SC_SUCCESS;
1100 	uint16_t sct = SPDK_NVME_SCT_GENERIC;
1101 	int err = 0;
1102 	struct nvmf_vfio_user_qpair *vu_qpair;
1103 	struct nvme_q *io_q;
1104 
1105 	assert(ctrlr != NULL);
1106 	assert(cmd != NULL);
1107 
1108 	qid = cmd->cdw10_bits.create_io_q.qid;
1109 	if (qid == 0 || qid >= NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR) {
1110 		SPDK_ERRLOG("%s: invalid QID=%d, max=%d\n", ctrlr_id(ctrlr),
1111 			    qid, NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR);
1112 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1113 		sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1114 		goto out;
1115 	}
1116 
1117 	if (io_q_exists(ctrlr, qid, is_cq)) {
1118 		SPDK_ERRLOG("%s: %cQ%d already exists\n", ctrlr_id(ctrlr),
1119 			    is_cq ? 'C' : 'S', qid);
1120 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1121 		sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1122 		goto out;
1123 	}
1124 
1125 	qsize = cmd->cdw10_bits.create_io_q.qsize + 1;
1126 	if (qsize == 1 || qsize > max_queue_size(ctrlr)) {
1127 		SPDK_ERRLOG("%s: invalid I/O queue size %u\n", ctrlr_id(ctrlr), qsize);
1128 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1129 		sc = SPDK_NVME_SC_INVALID_QUEUE_SIZE;
1130 		goto out;
1131 	}
1132 
1133 	SPDK_DEBUGLOG(nvmf_vfio,
1134 		      "%s: create I/O %cQ%d: QSIZE=%#x\n", ctrlr_id(ctrlr),
1135 		      is_cq ? 'C' : 'S', qid, qsize);
1136 
1137 	if (is_cq) {
1138 		err = init_qp(ctrlr, ctrlr->qp[0]->qpair.transport, qsize, qid);
1139 		if (err != 0) {
1140 			sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
1141 			goto out;
1142 		}
1143 
1144 		io_q = &ctrlr->qp[qid]->cq;
1145 		if (cmd->cdw11_bits.create_io_cq.pc != 0x1) {
1146 			SPDK_ERRLOG("%s: non-PC CQ not supporred\n", ctrlr_id(ctrlr));
1147 			sc = SPDK_NVME_SC_INVALID_CONTROLLER_MEM_BUF;
1148 			goto out;
1149 		}
1150 		io_q->ien = cmd->cdw11_bits.create_io_cq.ien;
1151 		io_q->iv = cmd->cdw11_bits.create_io_cq.iv;
1152 		io_q->phase = true;
1153 	} else {
1154 		if (cmd->cdw11_bits.create_io_sq.cqid == 0) {
1155 			SPDK_ERRLOG("%s: invalid CQID 0\n", ctrlr_id(ctrlr));
1156 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1157 			sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1158 			goto out;
1159 
1160 		}
1161 		/* CQ must be created before SQ */
1162 		if (!io_q_exists(ctrlr, cmd->cdw11_bits.create_io_sq.cqid, true)) {
1163 			SPDK_ERRLOG("%s: CQ%d does not exist\n", ctrlr_id(ctrlr),
1164 				    cmd->cdw11_bits.create_io_sq.cqid);
1165 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1166 			sc = SPDK_NVME_SC_COMPLETION_QUEUE_INVALID;
1167 			goto out;
1168 		}
1169 
1170 		if (cmd->cdw11_bits.create_io_sq.pc != 0x1) {
1171 			SPDK_ERRLOG("%s: non-PC SQ not supported\n", ctrlr_id(ctrlr));
1172 			sc = SPDK_NVME_SC_INVALID_CONTROLLER_MEM_BUF;
1173 			goto out;
1174 		}
1175 		/* TODO: support shared IO CQ */
1176 		if (qid != cmd->cdw11_bits.create_io_sq.cqid) {
1177 			SPDK_ERRLOG("%s: doesn't support shared CQ now\n", ctrlr_id(ctrlr));
1178 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1179 			sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1180 		}
1181 
1182 		io_q = &ctrlr->qp[qid]->sq;
1183 		io_q->cqid = cmd->cdw11_bits.create_io_sq.cqid;
1184 		SPDK_DEBUGLOG(nvmf_vfio, "%s: SQ%d CQID=%d\n", ctrlr_id(ctrlr),
1185 			      qid, io_q->cqid);
1186 	}
1187 
1188 	io_q->is_cq = is_cq;
1189 	io_q->size = qsize;
1190 	io_q->prp1 = cmd->dptr.prp.prp1;
1191 
1192 	err = map_q(ctrlr, io_q, is_cq, true);
1193 	if (err) {
1194 		sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
1195 		SPDK_ERRLOG("%s: failed to map I/O queue: %m\n", ctrlr_id(ctrlr));
1196 		goto out;
1197 	}
1198 
1199 	SPDK_DEBUGLOG(nvmf_vfio, "%s: mapped %cQ%d IOVA=%#lx vaddr=%#llx\n",
1200 		      ctrlr_id(ctrlr), is_cq ? 'C' : 'S',
1201 		      qid, cmd->dptr.prp.prp1, (unsigned long long)io_q->addr);
1202 
1203 	if (is_cq) {
1204 		*hdbl(ctrlr, io_q) = 0;
1205 	} else {
1206 		vu_qpair = ctrlr->qp[qid];
1207 		*tdbl(ctrlr, io_q) = 0;
1208 		vu_qpair->sq.head = 0;
1209 
1210 		if (vu_qpair->state == VFIO_USER_QPAIR_SQ_DELETED) {
1211 			vu_qpair->state = VFIO_USER_QPAIR_ACTIVE;
1212 		} else {
1213 			/*
1214 			 * Create our new I/O qpair. This asynchronously invokes, on a
1215 			 * suitable poll group, the nvmf_vfio_user_poll_group_add()
1216 			 * callback, which will call spdk_nvmf_request_exec_fabrics()
1217 			 * with a generated fabrics connect command. This command is
1218 			 * then eventually completed via handle_queue_connect_rsp().
1219 			 */
1220 			vu_qpair->create_io_sq_cmd = *cmd;
1221 			spdk_nvmf_tgt_new_qpair(ctrlr->transport->transport.tgt,
1222 						&vu_qpair->qpair);
1223 			return 0;
1224 		}
1225 	}
1226 
1227 out:
1228 	return post_completion(ctrlr, &ctrlr->qp[0]->cq, 0, 0, cmd->cid, sc, sct);
1229 }
1230 
1231 /* For ADMIN I/O DELETE COMPLETION QUEUE the NVMf library will disconnect and free
1232  * queue pair, so save the command in a context.
1233  */
1234 struct vfio_user_delete_cq_ctx {
1235 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
1236 	struct spdk_nvme_cmd delete_io_cq_cmd;
1237 };
1238 
1239 static void
1240 vfio_user_qpair_delete_cb(void *cb_arg)
1241 {
1242 	struct vfio_user_delete_cq_ctx *ctx = cb_arg;
1243 	struct nvmf_vfio_user_ctrlr *vu_ctrlr = ctx->vu_ctrlr;
1244 
1245 	post_completion(vu_ctrlr, &vu_ctrlr->qp[0]->cq, 0, 0, ctx->delete_io_cq_cmd.cid,
1246 			SPDK_NVME_SC_SUCCESS, SPDK_NVME_SCT_GENERIC);
1247 	free(ctx);
1248 }
1249 
1250 /*
1251  * Deletes a completion or submission I/O queue.
1252  */
1253 static int
1254 handle_del_io_q(struct nvmf_vfio_user_ctrlr *ctrlr,
1255 		struct spdk_nvme_cmd *cmd, const bool is_cq)
1256 {
1257 	uint16_t sct = SPDK_NVME_SCT_GENERIC;
1258 	uint16_t sc = SPDK_NVME_SC_SUCCESS;
1259 	struct nvmf_vfio_user_qpair *vu_qpair;
1260 	struct vfio_user_delete_cq_ctx *ctx;
1261 
1262 	SPDK_DEBUGLOG(nvmf_vfio, "%s: delete I/O %cQ: QID=%d\n",
1263 		      ctrlr_id(ctrlr), is_cq ? 'C' : 'S',
1264 		      cmd->cdw10_bits.delete_io_q.qid);
1265 
1266 	if (!io_q_exists(ctrlr, cmd->cdw10_bits.delete_io_q.qid, is_cq)) {
1267 		SPDK_ERRLOG("%s: I/O %cQ%d does not exist\n", ctrlr_id(ctrlr),
1268 			    is_cq ? 'C' : 'S', cmd->cdw10_bits.delete_io_q.qid);
1269 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1270 		sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1271 		goto out;
1272 	}
1273 
1274 	vu_qpair = ctrlr->qp[cmd->cdw10_bits.delete_io_q.qid];
1275 	if (is_cq) {
1276 		/* SQ must have been deleted first */
1277 		if (vu_qpair->state != VFIO_USER_QPAIR_SQ_DELETED) {
1278 			SPDK_ERRLOG("%s: the associated SQ must be deleted first\n", ctrlr_id(ctrlr));
1279 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1280 			sc = SPDK_NVME_SC_INVALID_QUEUE_DELETION;
1281 			goto out;
1282 		}
1283 		ctx = calloc(1, sizeof(*ctx));
1284 		if (!ctx) {
1285 			sct = SPDK_NVME_SCT_GENERIC;
1286 			sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
1287 			goto out;
1288 		}
1289 		ctx->vu_ctrlr = ctrlr;
1290 		ctx->delete_io_cq_cmd = *cmd;
1291 		spdk_nvmf_qpair_disconnect(&vu_qpair->qpair, vfio_user_qpair_delete_cb, ctx);
1292 		return 0;
1293 	} else {
1294 		if (vu_qpair->state == VFIO_USER_QPAIR_SQ_DELETED) {
1295 			SPDK_DEBUGLOG(nvmf_vfio, "%s: SQ%u is already deleted\n", ctrlr_id(ctrlr),
1296 				      cmd->cdw10_bits.delete_io_q.qid);
1297 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1298 			sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1299 			goto out;
1300 		}
1301 
1302 		/*
1303 		 * This doesn't actually delete the SQ, We're merely telling the poll_group_poll
1304 		 * function to skip checking this SQ.  The queue pair will be disconnected in Delete
1305 		 * IO CQ command.
1306 		 */
1307 		vu_qpair->state = VFIO_USER_QPAIR_SQ_DELETED;
1308 		vfu_unmap_sg(ctrlr->endpoint->vfu_ctx, vu_qpair->sq.sg, &vu_qpair->sq.iov, 1);
1309 		vu_qpair->sq.addr = NULL;
1310 	}
1311 
1312 out:
1313 	return post_completion(ctrlr, &ctrlr->qp[0]->cq, 0, 0, cmd->cid, sc, sct);
1314 }
1315 
1316 /*
1317  * Returns 0 on success and -errno on error.
1318  */
1319 static int
1320 consume_admin_cmd(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvme_cmd *cmd)
1321 {
1322 	assert(ctrlr != NULL);
1323 	assert(cmd != NULL);
1324 
1325 	if (cmd->fuse != 0) {
1326 		/* Fused admin commands are not supported. */
1327 		return post_completion(ctrlr, &ctrlr->qp[0]->cq, 0, 0, cmd->cid,
1328 				       SPDK_NVME_SC_INVALID_FIELD,
1329 				       SPDK_NVME_SCT_GENERIC);
1330 	}
1331 
1332 	switch (cmd->opc) {
1333 	case SPDK_NVME_OPC_CREATE_IO_CQ:
1334 	case SPDK_NVME_OPC_CREATE_IO_SQ:
1335 		return handle_create_io_q(ctrlr, cmd,
1336 					  cmd->opc == SPDK_NVME_OPC_CREATE_IO_CQ);
1337 	case SPDK_NVME_OPC_DELETE_IO_SQ:
1338 	case SPDK_NVME_OPC_DELETE_IO_CQ:
1339 		return handle_del_io_q(ctrlr, cmd,
1340 				       cmd->opc == SPDK_NVME_OPC_DELETE_IO_CQ);
1341 	default:
1342 		return handle_cmd_req(ctrlr, cmd, get_nvmf_req(ctrlr->qp[0]));
1343 	}
1344 }
1345 
1346 static int
1347 handle_cmd_rsp(struct nvmf_vfio_user_req *vu_req, void *cb_arg)
1348 {
1349 	struct nvmf_vfio_user_qpair *vu_qpair = cb_arg;
1350 	struct nvmf_vfio_user_ctrlr *vu_ctrlr = vu_qpair->ctrlr;
1351 	uint16_t sqid, cqid;
1352 
1353 	assert(vu_qpair != NULL);
1354 	assert(vu_req != NULL);
1355 	assert(vu_ctrlr != NULL);
1356 
1357 	if (spdk_likely(vu_req->iovcnt)) {
1358 		vfu_unmap_sg(vu_ctrlr->endpoint->vfu_ctx, vu_req->sg, vu_req->iov, vu_req->iovcnt);
1359 	}
1360 	sqid = vu_qpair->qpair.qid;
1361 	cqid = vu_ctrlr->qp[sqid]->sq.cqid;
1362 
1363 	return post_completion(vu_ctrlr, &vu_ctrlr->qp[cqid]->cq,
1364 			       vu_req->req.rsp->nvme_cpl.cdw0,
1365 			       sqid,
1366 			       vu_req->req.cmd->nvme_cmd.cid,
1367 			       vu_req->req.rsp->nvme_cpl.status.sc,
1368 			       vu_req->req.rsp->nvme_cpl.status.sct);
1369 }
1370 
1371 static int
1372 consume_cmd(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvmf_vfio_user_qpair *qpair,
1373 	    struct spdk_nvme_cmd *cmd)
1374 {
1375 	assert(qpair != NULL);
1376 	if (nvmf_qpair_is_admin_queue(&qpair->qpair)) {
1377 		return consume_admin_cmd(ctrlr, cmd);
1378 	}
1379 
1380 	return handle_cmd_req(ctrlr, cmd, get_nvmf_req(qpair));
1381 }
1382 
1383 /* Returns the number of commands processed, or a negative value on error. */
1384 static int
1385 handle_sq_tdbl_write(struct nvmf_vfio_user_ctrlr *ctrlr, const uint32_t new_tail,
1386 		     struct nvmf_vfio_user_qpair *qpair)
1387 {
1388 	struct spdk_nvme_cmd *queue;
1389 	int count = 0;
1390 
1391 	assert(ctrlr != NULL);
1392 	assert(qpair != NULL);
1393 
1394 	queue = qpair->sq.addr;
1395 	while (sq_head(qpair) != new_tail) {
1396 		int err;
1397 		struct spdk_nvme_cmd *cmd = &queue[sq_head(qpair)];
1398 
1399 		count++;
1400 
1401 		/*
1402 		 * SQHD must contain the new head pointer, so we must increase
1403 		 * it before we generate a completion.
1404 		 */
1405 		sqhd_advance(ctrlr, qpair);
1406 
1407 		err = consume_cmd(ctrlr, qpair, cmd);
1408 		if (err != 0) {
1409 			return err;
1410 		}
1411 	}
1412 
1413 	return count;
1414 }
1415 
1416 static int
1417 enable_admin_queue(struct nvmf_vfio_user_ctrlr *ctrlr)
1418 {
1419 	int err;
1420 
1421 	assert(ctrlr != NULL);
1422 
1423 	err = acq_setup(ctrlr);
1424 	if (err != 0) {
1425 		return err;
1426 	}
1427 
1428 	err = asq_setup(ctrlr);
1429 	if (err != 0) {
1430 		return err;
1431 	}
1432 
1433 	return 0;
1434 }
1435 
1436 static void
1437 disable_admin_queue(struct nvmf_vfio_user_ctrlr *ctrlr)
1438 {
1439 	assert(ctrlr->qp[0] != NULL);
1440 
1441 	unmap_qp(ctrlr->qp[0]);
1442 }
1443 
1444 static void
1445 memory_region_add_cb(vfu_ctx_t *vfu_ctx, vfu_dma_info_t *info)
1446 {
1447 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1448 	struct nvmf_vfio_user_ctrlr *ctrlr;
1449 	struct nvmf_vfio_user_qpair *qpair;
1450 	int ret;
1451 
1452 	/*
1453 	 * We're not interested in any DMA regions that aren't mappable (we don't
1454 	 * support clients that don't share their memory).
1455 	 */
1456 	if (!info->vaddr) {
1457 		return;
1458 	}
1459 
1460 	if (((uintptr_t)info->mapping.iov_base & MASK_2MB) ||
1461 	    (info->mapping.iov_len & MASK_2MB)) {
1462 		SPDK_DEBUGLOG(nvmf_vfio, "Invalid memory region vaddr %p, IOVA %#lx-%#lx\n", info->vaddr,
1463 			      (uintptr_t)info->mapping.iov_base,
1464 			      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1465 		return;
1466 	}
1467 
1468 	assert(endpoint != NULL);
1469 	if (endpoint->ctrlr == NULL) {
1470 		return;
1471 	}
1472 	ctrlr = endpoint->ctrlr;
1473 
1474 	SPDK_DEBUGLOG(nvmf_vfio, "%s: map IOVA %#lx-%#lx\n", ctrlr_id(ctrlr),
1475 		      (uintptr_t)info->mapping.iov_base,
1476 		      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1477 
1478 	/* VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE are enabled when registering to VFIO, here we also
1479 	 * check the protection bits before registering.
1480 	 */
1481 	if (info->prot == (PROT_WRITE | PROT_READ)) {
1482 		ret = spdk_mem_register(info->mapping.iov_base, info->mapping.iov_len);
1483 		if (ret) {
1484 			SPDK_ERRLOG("Memory region register %#lx-%#lx failed, ret=%d\n",
1485 				    (uint64_t)(uintptr_t)info->mapping.iov_base,
1486 				    (uint64_t)(uintptr_t)info->mapping.iov_base + info->mapping.iov_len,
1487 				    ret);
1488 		}
1489 	}
1490 
1491 	pthread_mutex_lock(&endpoint->lock);
1492 	TAILQ_FOREACH(qpair, &ctrlr->connected_qps, tailq) {
1493 		if (qpair->state != VFIO_USER_QPAIR_INACTIVE) {
1494 			continue;
1495 		}
1496 
1497 		ret = remap_qp(qpair);
1498 		if (ret) {
1499 			continue;
1500 		}
1501 		qpair->state = VFIO_USER_QPAIR_ACTIVE;
1502 		SPDK_DEBUGLOG(nvmf_vfio, "Remap QP %u successfully\n", qpair->qpair.qid);
1503 	}
1504 	pthread_mutex_unlock(&endpoint->lock);
1505 }
1506 
1507 static int
1508 memory_region_remove_cb(vfu_ctx_t *vfu_ctx, vfu_dma_info_t *info)
1509 {
1510 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1511 	struct nvmf_vfio_user_ctrlr *ctrlr;
1512 	struct nvmf_vfio_user_qpair *qpair;
1513 	void *map_start, *map_end;
1514 	int ret = 0;
1515 
1516 	if (!info->vaddr) {
1517 		return 0;
1518 	}
1519 
1520 	if (((uintptr_t)info->mapping.iov_base & MASK_2MB) ||
1521 	    (info->mapping.iov_len & MASK_2MB)) {
1522 		SPDK_DEBUGLOG(nvmf_vfio, "Invalid memory region vaddr %p, IOVA %#lx-%#lx\n", info->vaddr,
1523 			      (uintptr_t)info->mapping.iov_base,
1524 			      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1525 		return 0;
1526 	}
1527 
1528 	assert(endpoint != NULL);
1529 	if (endpoint->ctrlr == NULL) {
1530 		return 0;
1531 	}
1532 	ctrlr = endpoint->ctrlr;
1533 
1534 	SPDK_DEBUGLOG(nvmf_vfio, "%s: unmap IOVA %#lx-%#lx\n", ctrlr_id(ctrlr),
1535 		      (uintptr_t)info->mapping.iov_base,
1536 		      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1537 
1538 	map_start = info->mapping.iov_base;
1539 	map_end = info->mapping.iov_base + info->mapping.iov_len;
1540 
1541 	pthread_mutex_lock(&endpoint->lock);
1542 	TAILQ_FOREACH(qpair, &ctrlr->connected_qps, tailq) {
1543 		if ((qpair->cq.addr >= map_start && qpair->cq.addr <= map_end) ||
1544 		    (qpair->sq.addr >= map_start && qpair->sq.addr <= map_end)) {
1545 			/* TODO: Ideally we should disconnect this queue pair
1546 			 * before returning to caller.
1547 			 */
1548 			unmap_qp(qpair);
1549 			qpair->state = VFIO_USER_QPAIR_INACTIVE;
1550 		}
1551 	}
1552 	pthread_mutex_unlock(&endpoint->lock);
1553 
1554 	if (info->prot == (PROT_WRITE | PROT_READ)) {
1555 		ret = spdk_mem_unregister(info->mapping.iov_base, info->mapping.iov_len);
1556 		if (ret) {
1557 			SPDK_ERRLOG("Memory region unregister %#lx-%#lx failed, ret=%d\n",
1558 				    (uint64_t)(uintptr_t)info->mapping.iov_base,
1559 				    (uint64_t)(uintptr_t)info->mapping.iov_base + info->mapping.iov_len,
1560 				    ret);
1561 		}
1562 	}
1563 
1564 	return 0;
1565 }
1566 
1567 static int
1568 nvmf_vfio_user_prop_req_rsp(struct nvmf_vfio_user_req *req, void *cb_arg)
1569 {
1570 	struct nvmf_vfio_user_qpair *vu_qpair = cb_arg;
1571 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
1572 	bool disable_admin = false;
1573 	int ret;
1574 
1575 	assert(vu_qpair != NULL);
1576 	assert(req != NULL);
1577 
1578 	if (req->req.cmd->prop_get_cmd.fctype == SPDK_NVMF_FABRIC_COMMAND_PROPERTY_GET) {
1579 		assert(vu_qpair->ctrlr != NULL);
1580 		assert(req != NULL);
1581 
1582 		memcpy(req->req.data,
1583 		       &req->req.rsp->prop_get_rsp.value.u64,
1584 		       req->req.length);
1585 	} else {
1586 		assert(req->req.cmd->prop_set_cmd.fctype == SPDK_NVMF_FABRIC_COMMAND_PROPERTY_SET);
1587 		assert(vu_qpair->ctrlr != NULL);
1588 		vu_ctrlr = vu_qpair->ctrlr;
1589 
1590 		if (req->req.cmd->prop_set_cmd.ofst == offsetof(struct spdk_nvme_registers, cc)) {
1591 			union spdk_nvme_cc_register cc, diff;
1592 
1593 			cc.raw = req->req.cmd->prop_set_cmd.value.u64;
1594 			diff.raw = cc.raw ^ req->cc.raw;
1595 
1596 			if (diff.bits.en) {
1597 				if (cc.bits.en) {
1598 					SPDK_DEBUGLOG(nvmf_vfio, "%s: MAP Admin queue\n", ctrlr_id(vu_ctrlr));
1599 					ret = enable_admin_queue(vu_ctrlr);
1600 					if (ret) {
1601 						SPDK_ERRLOG("%s: failed to map Admin queue\n", ctrlr_id(vu_ctrlr));
1602 						return ret;
1603 					}
1604 					vu_qpair->state = VFIO_USER_QPAIR_ACTIVE;
1605 				} else {
1606 					disable_admin = true;
1607 				}
1608 			}
1609 
1610 			if (diff.bits.shn) {
1611 				if (cc.bits.shn == SPDK_NVME_SHN_NORMAL || cc.bits.shn == SPDK_NVME_SHN_ABRUPT) {
1612 					disable_admin = true;
1613 				}
1614 			}
1615 
1616 			if (disable_admin) {
1617 				SPDK_DEBUGLOG(nvmf_vfio,
1618 					      "%s: UNMAP Admin queue\n",
1619 					      ctrlr_id(vu_ctrlr));
1620 				vu_qpair->state = VFIO_USER_QPAIR_INACTIVE;
1621 				disable_admin_queue(vu_ctrlr);
1622 				/* For PCIe controller reset or shutdown, we will drop all AER responses */
1623 				nvmf_ctrlr_abort_aer(vu_qpair->qpair.ctrlr);
1624 			}
1625 		}
1626 	}
1627 
1628 	return 0;
1629 }
1630 
1631 /*
1632  * Handles a write at offset 0x1000 or more; this is the non-mapped path when a
1633  * doorbell is written via access_bar0_fn().
1634  *
1635  * DSTRD is set to fixed value 0 for NVMf.
1636  *
1637  */
1638 static int
1639 handle_dbl_access(struct nvmf_vfio_user_ctrlr *ctrlr, uint32_t *buf,
1640 		  const size_t count, loff_t pos, const bool is_write)
1641 {
1642 	assert(ctrlr != NULL);
1643 	assert(buf != NULL);
1644 
1645 	if (count != sizeof(uint32_t)) {
1646 		SPDK_ERRLOG("%s: bad doorbell buffer size %ld\n",
1647 			    ctrlr_id(ctrlr), count);
1648 		errno = EINVAL;
1649 		return -1;
1650 	}
1651 
1652 	pos -= NVMF_VFIO_USER_DOORBELLS_OFFSET;
1653 
1654 	/* pos must be dword aligned */
1655 	if ((pos & 0x3) != 0) {
1656 		SPDK_ERRLOG("%s: bad doorbell offset %#lx\n", ctrlr_id(ctrlr), pos);
1657 		errno = EINVAL;
1658 		return -1;
1659 	}
1660 
1661 	/* convert byte offset to array index */
1662 	pos >>= 2;
1663 
1664 	if (pos >= NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR * 2) {
1665 		SPDK_ERRLOG("%s: bad doorbell index %#lx\n", ctrlr_id(ctrlr), pos);
1666 		errno = EINVAL;
1667 		return -1;
1668 	}
1669 
1670 	if (is_write) {
1671 		ctrlr->doorbells[pos] = *buf;
1672 		spdk_wmb();
1673 	} else {
1674 		spdk_rmb();
1675 		*buf = ctrlr->doorbells[pos];
1676 	}
1677 	return 0;
1678 }
1679 
1680 static ssize_t
1681 access_bar0_fn(vfu_ctx_t *vfu_ctx, char *buf, size_t count, loff_t pos,
1682 	       bool is_write)
1683 {
1684 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1685 	struct nvmf_vfio_user_ctrlr *ctrlr;
1686 	struct nvmf_vfio_user_req *req;
1687 	const struct spdk_nvmf_registers *regs;
1688 	int ret;
1689 
1690 	ctrlr = endpoint->ctrlr;
1691 
1692 	SPDK_DEBUGLOG(nvmf_vfio,
1693 		      "%s: bar0 %s ctrlr: %p, count=%zu, pos=%"PRIX64"\n",
1694 		      endpoint_id(endpoint), is_write ? "write" : "read",
1695 		      ctrlr, count, pos);
1696 
1697 	if (pos >= NVMF_VFIO_USER_DOORBELLS_OFFSET) {
1698 		/*
1699 		 * The fact that the doorbells can be memory mapped doesn't mean
1700 		 * that the client (VFIO in QEMU) is obliged to memory map them,
1701 		 * it might still elect to access them via regular read/write;
1702 		 * we might also have had disable_mappable_bar0 set.
1703 		 */
1704 		ret = handle_dbl_access(ctrlr, (uint32_t *)buf, count,
1705 					pos, is_write);
1706 		if (ret == 0) {
1707 			return count;
1708 		}
1709 		return ret;
1710 	}
1711 
1712 	/* Construct a Fabric Property Get/Set command and send it */
1713 	req = get_nvmf_vfio_user_req(ctrlr->qp[0]);
1714 	if (req == NULL) {
1715 		errno = ENOBUFS;
1716 		return -1;
1717 	}
1718 	regs = spdk_nvmf_ctrlr_get_regs(ctrlr->qp[0]->qpair.ctrlr);
1719 	req->cc.raw = regs->cc.raw;
1720 
1721 	req->cb_fn = nvmf_vfio_user_prop_req_rsp;
1722 	req->cb_arg = ctrlr->qp[0];
1723 	req->req.cmd->prop_set_cmd.opcode = SPDK_NVME_OPC_FABRIC;
1724 	req->req.cmd->prop_set_cmd.cid = 0;
1725 	req->req.cmd->prop_set_cmd.attrib.size = (count / 4) - 1;
1726 	req->req.cmd->prop_set_cmd.ofst = pos;
1727 	if (is_write) {
1728 		req->req.cmd->prop_set_cmd.fctype = SPDK_NVMF_FABRIC_COMMAND_PROPERTY_SET;
1729 		if (req->req.cmd->prop_set_cmd.attrib.size) {
1730 			req->req.cmd->prop_set_cmd.value.u64 = *(uint64_t *)buf;
1731 		} else {
1732 			req->req.cmd->prop_set_cmd.value.u32.high = 0;
1733 			req->req.cmd->prop_set_cmd.value.u32.low = *(uint32_t *)buf;
1734 		}
1735 	} else {
1736 		req->req.cmd->prop_get_cmd.fctype = SPDK_NVMF_FABRIC_COMMAND_PROPERTY_GET;
1737 	}
1738 	req->req.length = count;
1739 	req->req.data = buf;
1740 
1741 	spdk_nvmf_request_exec_fabrics(&req->req);
1742 
1743 	return count;
1744 }
1745 
1746 /*
1747  * NVMe driver reads 4096 bytes, which is the extended PCI configuration space
1748  * available on PCI-X 2.0 and PCI Express buses
1749  */
1750 static ssize_t
1751 access_pci_config(vfu_ctx_t *vfu_ctx, char *buf, size_t count, loff_t offset,
1752 		  bool is_write)
1753 {
1754 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1755 
1756 	if (is_write) {
1757 		SPDK_ERRLOG("%s: write %#lx-%#lx not supported\n",
1758 			    endpoint_id(endpoint), offset, offset + count);
1759 		errno = EINVAL;
1760 		return -1;
1761 	}
1762 
1763 	if (offset + count > PCI_CFG_SPACE_EXP_SIZE) {
1764 		SPDK_ERRLOG("%s: access past end of extended PCI configuration space, want=%ld+%ld, max=%d\n",
1765 			    endpoint_id(endpoint), offset, count,
1766 			    PCI_CFG_SPACE_EXP_SIZE);
1767 		errno = ERANGE;
1768 		return -1;
1769 	}
1770 
1771 	memcpy(buf, ((unsigned char *)endpoint->pci_config_space) + offset, count);
1772 
1773 	return count;
1774 }
1775 
1776 static void
1777 vfio_user_log(vfu_ctx_t *vfu_ctx, int level, char const *msg)
1778 {
1779 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1780 
1781 	if (level >= LOG_DEBUG) {
1782 		SPDK_DEBUGLOG(nvmf_vfio, "%s: %s\n", endpoint_id(endpoint), msg);
1783 	} else if (level >= LOG_INFO) {
1784 		SPDK_INFOLOG(nvmf_vfio, "%s: %s\n", endpoint_id(endpoint), msg);
1785 	} else if (level >= LOG_NOTICE) {
1786 		SPDK_NOTICELOG("%s: %s\n", endpoint_id(endpoint), msg);
1787 	} else if (level >= LOG_WARNING) {
1788 		SPDK_WARNLOG("%s: %s\n", endpoint_id(endpoint), msg);
1789 	} else {
1790 		SPDK_ERRLOG("%s: %s\n", endpoint_id(endpoint), msg);
1791 	}
1792 }
1793 
1794 static int
1795 vfio_user_get_log_level(void)
1796 {
1797 	int level;
1798 
1799 	if (SPDK_DEBUGLOG_FLAG_ENABLED("nvmf_vfio")) {
1800 		return LOG_DEBUG;
1801 	}
1802 
1803 	level = spdk_log_to_syslog_level(spdk_log_get_level());
1804 	if (level < 0) {
1805 		return LOG_ERR;
1806 	}
1807 
1808 	return level;
1809 }
1810 
1811 static void
1812 init_pci_config_space(vfu_pci_config_space_t *p)
1813 {
1814 	/* MLBAR */
1815 	p->hdr.bars[0].raw = 0x0;
1816 	/* MUBAR */
1817 	p->hdr.bars[1].raw = 0x0;
1818 
1819 	/* vendor specific, let's set them to zero for now */
1820 	p->hdr.bars[3].raw = 0x0;
1821 	p->hdr.bars[4].raw = 0x0;
1822 	p->hdr.bars[5].raw = 0x0;
1823 
1824 	/* enable INTx */
1825 	p->hdr.intr.ipin = 0x1;
1826 }
1827 
1828 static int
1829 vfio_user_dev_info_fill(struct nvmf_vfio_user_transport *vu_transport,
1830 			struct nvmf_vfio_user_endpoint *endpoint)
1831 {
1832 	int ret;
1833 	ssize_t cap_offset;
1834 	vfu_ctx_t *vfu_ctx = endpoint->vfu_ctx;
1835 
1836 	struct pmcap pmcap = { .hdr.id = PCI_CAP_ID_PM, .pmcs.nsfrst = 0x1 };
1837 	struct pxcap pxcap = {
1838 		.hdr.id = PCI_CAP_ID_EXP,
1839 		.pxcaps.ver = 0x2,
1840 		.pxdcap = {.rer = 0x1, .flrc = 0x1},
1841 		.pxdcap2.ctds = 0x1
1842 	};
1843 
1844 	struct msixcap msixcap = {
1845 		.hdr.id = PCI_CAP_ID_MSIX,
1846 		.mxc.ts = NVME_IRQ_MSIX_NUM - 1,
1847 		.mtab = {.tbir = 0x4, .to = 0x0},
1848 		.mpba = {.pbir = 0x5, .pbao = 0x0}
1849 	};
1850 
1851 	static struct iovec sparse_mmap[] = {
1852 		{
1853 			.iov_base = (void *)NVMF_VFIO_USER_DOORBELLS_OFFSET,
1854 			.iov_len = NVMF_VFIO_USER_DOORBELLS_SIZE,
1855 		},
1856 	};
1857 
1858 	ret = vfu_pci_init(vfu_ctx, VFU_PCI_TYPE_EXPRESS, PCI_HEADER_TYPE_NORMAL, 0);
1859 	if (ret < 0) {
1860 		SPDK_ERRLOG("vfu_ctx %p failed to initialize PCI\n", vfu_ctx);
1861 		return ret;
1862 	}
1863 	vfu_pci_set_id(vfu_ctx, 0x4e58, 0x0001, 0, 0);
1864 	/*
1865 	 * 0x02, controller uses the NVM Express programming interface
1866 	 * 0x08, non-volatile memory controller
1867 	 * 0x01, mass storage controller
1868 	 */
1869 	vfu_pci_set_class(vfu_ctx, 0x01, 0x08, 0x02);
1870 
1871 	cap_offset = vfu_pci_add_capability(vfu_ctx, 0, 0, &pmcap);
1872 	if (cap_offset < 0) {
1873 		SPDK_ERRLOG("vfu_ctx %p failed add pmcap\n", vfu_ctx);
1874 		return ret;
1875 	}
1876 
1877 	cap_offset = vfu_pci_add_capability(vfu_ctx, 0, 0, &pxcap);
1878 	if (cap_offset < 0) {
1879 		SPDK_ERRLOG("vfu_ctx %p failed add pxcap\n", vfu_ctx);
1880 		return ret;
1881 	}
1882 
1883 	cap_offset = vfu_pci_add_capability(vfu_ctx, 0, 0, &msixcap);
1884 	if (cap_offset < 0) {
1885 		SPDK_ERRLOG("vfu_ctx %p failed add msixcap\n", vfu_ctx);
1886 		return ret;
1887 	}
1888 
1889 	ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_CFG_REGION_IDX, NVME_REG_CFG_SIZE,
1890 			       access_pci_config, VFU_REGION_FLAG_RW, NULL, 0, -1, 0);
1891 	if (ret < 0) {
1892 		SPDK_ERRLOG("vfu_ctx %p failed to setup cfg\n", vfu_ctx);
1893 		return ret;
1894 	}
1895 
1896 	if (vu_transport->transport_opts.disable_mappable_bar0) {
1897 		ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR0_REGION_IDX, NVME_REG_BAR0_SIZE,
1898 				       access_bar0_fn, VFU_REGION_FLAG_RW | VFU_REGION_FLAG_MEM,
1899 				       NULL, 0, -1, 0);
1900 	} else {
1901 		ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR0_REGION_IDX, NVME_REG_BAR0_SIZE,
1902 				       access_bar0_fn, VFU_REGION_FLAG_RW | VFU_REGION_FLAG_MEM,
1903 				       sparse_mmap, 1, endpoint->devmem_fd, 0);
1904 	}
1905 
1906 	if (ret < 0) {
1907 		SPDK_ERRLOG("vfu_ctx %p failed to setup bar 0\n", vfu_ctx);
1908 		return ret;
1909 	}
1910 
1911 	ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR4_REGION_IDX, PAGE_SIZE,
1912 			       NULL, VFU_REGION_FLAG_RW, NULL, 0, -1, 0);
1913 	if (ret < 0) {
1914 		SPDK_ERRLOG("vfu_ctx %p failed to setup bar 4\n", vfu_ctx);
1915 		return ret;
1916 	}
1917 
1918 	ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR5_REGION_IDX, PAGE_SIZE,
1919 			       NULL, VFU_REGION_FLAG_RW, NULL, 0, -1, 0);
1920 	if (ret < 0) {
1921 		SPDK_ERRLOG("vfu_ctx %p failed to setup bar 5\n", vfu_ctx);
1922 		return ret;
1923 	}
1924 
1925 	ret = vfu_setup_device_dma(vfu_ctx, memory_region_add_cb, memory_region_remove_cb);
1926 	if (ret < 0) {
1927 		SPDK_ERRLOG("vfu_ctx %p failed to setup dma callback\n", vfu_ctx);
1928 		return ret;
1929 	}
1930 
1931 	ret = vfu_setup_device_nr_irqs(vfu_ctx, VFU_DEV_INTX_IRQ, 1);
1932 	if (ret < 0) {
1933 		SPDK_ERRLOG("vfu_ctx %p failed to setup INTX\n", vfu_ctx);
1934 		return ret;
1935 	}
1936 
1937 	ret = vfu_setup_device_nr_irqs(vfu_ctx, VFU_DEV_MSIX_IRQ, NVME_IRQ_MSIX_NUM);
1938 	if (ret < 0) {
1939 		SPDK_ERRLOG("vfu_ctx %p failed to setup MSIX\n", vfu_ctx);
1940 		return ret;
1941 	}
1942 
1943 	ret = vfu_realize_ctx(vfu_ctx);
1944 	if (ret < 0) {
1945 		SPDK_ERRLOG("vfu_ctx %p failed to realize\n", vfu_ctx);
1946 		return ret;
1947 	}
1948 
1949 	endpoint->pci_config_space = vfu_pci_get_config_space(endpoint->vfu_ctx);
1950 	assert(endpoint->pci_config_space != NULL);
1951 	init_pci_config_space(endpoint->pci_config_space);
1952 
1953 	assert(cap_offset != 0);
1954 	endpoint->msix = (struct msixcap *)((uint8_t *)endpoint->pci_config_space + cap_offset);
1955 
1956 	return 0;
1957 }
1958 
1959 static void
1960 _free_ctrlr(void *ctx)
1961 {
1962 	struct nvmf_vfio_user_ctrlr *ctrlr = ctx;
1963 
1964 	spdk_poller_unregister(&ctrlr->vfu_ctx_poller);
1965 	free(ctrlr);
1966 }
1967 
1968 static void
1969 free_ctrlr(struct nvmf_vfio_user_ctrlr *ctrlr, bool free_qps)
1970 {
1971 	int i;
1972 	assert(ctrlr != NULL);
1973 
1974 	SPDK_DEBUGLOG(nvmf_vfio, "free %s\n", ctrlr_id(ctrlr));
1975 
1976 	if (free_qps) {
1977 		for (i = 0; i < NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR; i++) {
1978 			free_qp(ctrlr, i);
1979 		}
1980 	}
1981 
1982 	if (ctrlr->thread == spdk_get_thread()) {
1983 		_free_ctrlr(ctrlr);
1984 	} else {
1985 		spdk_thread_send_msg(ctrlr->thread, _free_ctrlr, ctrlr);
1986 	}
1987 }
1988 
1989 static void
1990 nvmf_vfio_user_create_ctrlr(struct nvmf_vfio_user_transport *transport,
1991 			    struct nvmf_vfio_user_endpoint *endpoint)
1992 {
1993 	struct nvmf_vfio_user_ctrlr *ctrlr;
1994 	int err = 0;
1995 
1996 	/* First, construct a vfio-user CUSTOM transport controller */
1997 	ctrlr = calloc(1, sizeof(*ctrlr));
1998 	if (ctrlr == NULL) {
1999 		err = -ENOMEM;
2000 		goto out;
2001 	}
2002 	ctrlr->cntlid = 0xffff;
2003 	ctrlr->transport = transport;
2004 	ctrlr->endpoint = endpoint;
2005 	ctrlr->doorbells = endpoint->doorbells;
2006 	TAILQ_INIT(&ctrlr->connected_qps);
2007 
2008 	/* Then, construct an admin queue pair */
2009 	err = init_qp(ctrlr, &transport->transport, NVMF_VFIO_USER_DEFAULT_AQ_DEPTH, 0);
2010 	if (err != 0) {
2011 		free(ctrlr);
2012 		goto out;
2013 	}
2014 	endpoint->ctrlr = ctrlr;
2015 
2016 	/* Notify the generic layer about the new admin queue pair */
2017 	spdk_nvmf_tgt_new_qpair(transport->transport.tgt, &ctrlr->qp[0]->qpair);
2018 
2019 out:
2020 	if (err != 0) {
2021 		SPDK_ERRLOG("%s: failed to create vfio-user controller: %s\n",
2022 			    endpoint_id(endpoint), strerror(-err));
2023 	}
2024 }
2025 
2026 static int
2027 nvmf_vfio_user_listen(struct spdk_nvmf_transport *transport,
2028 		      const struct spdk_nvme_transport_id *trid,
2029 		      struct spdk_nvmf_listen_opts *listen_opts)
2030 {
2031 	struct nvmf_vfio_user_transport *vu_transport;
2032 	struct nvmf_vfio_user_endpoint *endpoint, *tmp;
2033 	char *path = NULL;
2034 	char uuid[PATH_MAX] = {};
2035 	int fd;
2036 	int err;
2037 
2038 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport,
2039 					transport);
2040 
2041 	TAILQ_FOREACH_SAFE(endpoint, &vu_transport->endpoints, link, tmp) {
2042 		/* Only compare traddr */
2043 		if (strncmp(endpoint->trid.traddr, trid->traddr, sizeof(endpoint->trid.traddr)) == 0) {
2044 			return -EEXIST;
2045 		}
2046 	}
2047 
2048 	endpoint = calloc(1, sizeof(*endpoint));
2049 	if (!endpoint) {
2050 		return -ENOMEM;
2051 	}
2052 
2053 	endpoint->devmem_fd = -1;
2054 	memcpy(&endpoint->trid, trid, sizeof(endpoint->trid));
2055 
2056 	err = asprintf(&path, "%s/bar0", endpoint_id(endpoint));
2057 	if (err == -1) {
2058 		goto out;
2059 	}
2060 
2061 	fd = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
2062 	if (fd == -1) {
2063 		SPDK_ERRLOG("%s: failed to open device memory at %s: %m\n",
2064 			    endpoint_id(endpoint), path);
2065 		err = fd;
2066 		free(path);
2067 		goto out;
2068 	}
2069 	free(path);
2070 
2071 	endpoint->devmem_fd = fd;
2072 	err = ftruncate(fd, NVMF_VFIO_USER_DOORBELLS_OFFSET + NVMF_VFIO_USER_DOORBELLS_SIZE);
2073 	if (err != 0) {
2074 		goto out;
2075 	}
2076 
2077 	endpoint->doorbells = mmap(NULL, NVMF_VFIO_USER_DOORBELLS_SIZE,
2078 				   PROT_READ | PROT_WRITE, MAP_SHARED, fd, NVMF_VFIO_USER_DOORBELLS_OFFSET);
2079 	if (endpoint->doorbells == MAP_FAILED) {
2080 		endpoint->doorbells = NULL;
2081 		err = -errno;
2082 		goto out;
2083 	}
2084 
2085 	snprintf(uuid, PATH_MAX, "%s/cntrl", endpoint_id(endpoint));
2086 
2087 	endpoint->vfu_ctx = vfu_create_ctx(VFU_TRANS_SOCK, uuid, LIBVFIO_USER_FLAG_ATTACH_NB,
2088 					   endpoint, VFU_DEV_TYPE_PCI);
2089 	if (endpoint->vfu_ctx == NULL) {
2090 		SPDK_ERRLOG("%s: error creating libmuser context: %m\n",
2091 			    endpoint_id(endpoint));
2092 		err = -1;
2093 		goto out;
2094 	}
2095 	vfu_setup_log(endpoint->vfu_ctx, vfio_user_log, vfio_user_get_log_level());
2096 
2097 	err = vfio_user_dev_info_fill(vu_transport, endpoint);
2098 	if (err < 0) {
2099 		goto out;
2100 	}
2101 
2102 	pthread_mutex_init(&endpoint->lock, NULL);
2103 	TAILQ_INSERT_TAIL(&vu_transport->endpoints, endpoint, link);
2104 	SPDK_DEBUGLOG(nvmf_vfio, "%s: doorbells %p\n", uuid, endpoint->doorbells);
2105 
2106 out:
2107 	if (err != 0) {
2108 		nvmf_vfio_user_destroy_endpoint(endpoint);
2109 	}
2110 
2111 	return err;
2112 }
2113 
2114 static void
2115 nvmf_vfio_user_stop_listen(struct spdk_nvmf_transport *transport,
2116 			   const struct spdk_nvme_transport_id *trid)
2117 {
2118 	struct nvmf_vfio_user_transport *vu_transport;
2119 	struct nvmf_vfio_user_endpoint *endpoint, *tmp;
2120 
2121 	assert(trid != NULL);
2122 	assert(trid->traddr != NULL);
2123 
2124 	SPDK_DEBUGLOG(nvmf_vfio, "%s: stop listen\n", trid->traddr);
2125 
2126 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport,
2127 					transport);
2128 
2129 	pthread_mutex_lock(&vu_transport->lock);
2130 	TAILQ_FOREACH_SAFE(endpoint, &vu_transport->endpoints, link, tmp) {
2131 		if (strcmp(trid->traddr, endpoint->trid.traddr) == 0) {
2132 			TAILQ_REMOVE(&vu_transport->endpoints, endpoint, link);
2133 			if (endpoint->ctrlr) {
2134 				/* Users may kill NVMeoF target while VM
2135 				 * is connected, free all resources.
2136 				 */
2137 				free_ctrlr(endpoint->ctrlr, true);
2138 			}
2139 			nvmf_vfio_user_destroy_endpoint(endpoint);
2140 			pthread_mutex_unlock(&vu_transport->lock);
2141 
2142 			return;
2143 		}
2144 	}
2145 	pthread_mutex_unlock(&vu_transport->lock);
2146 
2147 	SPDK_DEBUGLOG(nvmf_vfio, "%s: not found\n", trid->traddr);
2148 }
2149 
2150 static void
2151 nvmf_vfio_user_cdata_init(struct spdk_nvmf_transport *transport,
2152 			  struct spdk_nvmf_subsystem *subsystem,
2153 			  struct spdk_nvmf_ctrlr_data *cdata)
2154 {
2155 	memset(&cdata->sgls, 0, sizeof(struct spdk_nvme_cdata_sgls));
2156 	cdata->sgls.supported = SPDK_NVME_SGLS_SUPPORTED_DWORD_ALIGNED;
2157 	/* libvfio-user can only support 1 connection for now */
2158 	cdata->oncs.reservations = 0;
2159 }
2160 
2161 static int
2162 nvmf_vfio_user_listen_associate(struct spdk_nvmf_transport *transport,
2163 				const struct spdk_nvmf_subsystem *subsystem,
2164 				const struct spdk_nvme_transport_id *trid)
2165 {
2166 	struct nvmf_vfio_user_transport *vu_transport;
2167 	struct nvmf_vfio_user_endpoint *endpoint;
2168 
2169 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport, transport);
2170 
2171 	TAILQ_FOREACH(endpoint, &vu_transport->endpoints, link) {
2172 		if (strncmp(endpoint->trid.traddr, trid->traddr, sizeof(endpoint->trid.traddr)) == 0) {
2173 			break;
2174 		}
2175 	}
2176 
2177 	if (endpoint == NULL) {
2178 		return -ENOENT;
2179 	}
2180 
2181 	endpoint->subsystem = subsystem;
2182 
2183 	return 0;
2184 }
2185 
2186 /*
2187  * Executed periodically at a default SPDK_NVMF_DEFAULT_ACCEPT_POLL_RATE_US
2188  * frequency.
2189  *
2190  * For each transport endpoint (which at the libvfio-user level corresponds to
2191  * a socket), if we don't currently have a controller set up, peek to see if the
2192  * socket is able to accept a new connection.
2193  *
2194  * This poller also takes care of handling the creation of any pending new
2195  * qpairs.
2196  *
2197  * Returns the number of events handled.
2198  */
2199 static uint32_t
2200 nvmf_vfio_user_accept(struct spdk_nvmf_transport *transport)
2201 {
2202 	struct nvmf_vfio_user_transport *vu_transport;
2203 	struct nvmf_vfio_user_endpoint *endpoint;
2204 	uint32_t count = 0;
2205 	int err;
2206 
2207 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport,
2208 					transport);
2209 
2210 	pthread_mutex_lock(&vu_transport->lock);
2211 
2212 	TAILQ_FOREACH(endpoint, &vu_transport->endpoints, link) {
2213 		if (endpoint->ctrlr != NULL) {
2214 			continue;
2215 		}
2216 
2217 		err = vfu_attach_ctx(endpoint->vfu_ctx);
2218 		if (err != 0) {
2219 			if (errno == EAGAIN || errno == EWOULDBLOCK) {
2220 				continue;
2221 			}
2222 
2223 			pthread_mutex_unlock(&vu_transport->lock);
2224 			return 1;
2225 		}
2226 
2227 		count++;
2228 
2229 		/* Construct a controller */
2230 		nvmf_vfio_user_create_ctrlr(vu_transport, endpoint);
2231 	}
2232 
2233 	pthread_mutex_unlock(&vu_transport->lock);
2234 
2235 	return count;
2236 }
2237 
2238 static void
2239 nvmf_vfio_user_discover(struct spdk_nvmf_transport *transport,
2240 			struct spdk_nvme_transport_id *trid,
2241 			struct spdk_nvmf_discovery_log_page_entry *entry)
2242 { }
2243 
2244 static struct spdk_nvmf_transport_poll_group *
2245 nvmf_vfio_user_poll_group_create(struct spdk_nvmf_transport *transport)
2246 {
2247 	struct nvmf_vfio_user_poll_group *vu_group;
2248 
2249 	SPDK_DEBUGLOG(nvmf_vfio, "create poll group\n");
2250 
2251 	vu_group = calloc(1, sizeof(*vu_group));
2252 	if (vu_group == NULL) {
2253 		SPDK_ERRLOG("Error allocating poll group: %m");
2254 		return NULL;
2255 	}
2256 
2257 	TAILQ_INIT(&vu_group->qps);
2258 
2259 	return &vu_group->group;
2260 }
2261 
2262 /* called when process exits */
2263 static void
2264 nvmf_vfio_user_poll_group_destroy(struct spdk_nvmf_transport_poll_group *group)
2265 {
2266 	struct nvmf_vfio_user_poll_group *vu_group;
2267 
2268 	SPDK_DEBUGLOG(nvmf_vfio, "destroy poll group\n");
2269 
2270 	vu_group = SPDK_CONTAINEROF(group, struct nvmf_vfio_user_poll_group, group);
2271 
2272 	free(vu_group);
2273 }
2274 
2275 static void
2276 vfio_user_qpair_disconnect_cb(void *ctx)
2277 {
2278 	struct nvmf_vfio_user_endpoint *endpoint = ctx;
2279 	struct nvmf_vfio_user_ctrlr *ctrlr;
2280 
2281 	pthread_mutex_lock(&endpoint->lock);
2282 	ctrlr = endpoint->ctrlr;
2283 	if (!ctrlr) {
2284 		pthread_mutex_unlock(&endpoint->lock);
2285 		return;
2286 	}
2287 
2288 	if (TAILQ_EMPTY(&ctrlr->connected_qps)) {
2289 		endpoint->ctrlr = NULL;
2290 		free_ctrlr(ctrlr, false);
2291 		pthread_mutex_unlock(&endpoint->lock);
2292 		return;
2293 	}
2294 	pthread_mutex_unlock(&endpoint->lock);
2295 }
2296 
2297 static int
2298 vfio_user_destroy_ctrlr(struct nvmf_vfio_user_ctrlr *ctrlr)
2299 {
2300 	struct nvmf_vfio_user_qpair *qpair;
2301 	struct nvmf_vfio_user_endpoint *endpoint;
2302 
2303 	SPDK_DEBUGLOG(nvmf_vfio, "%s stop processing\n", ctrlr_id(ctrlr));
2304 
2305 	endpoint = ctrlr->endpoint;
2306 	assert(endpoint != NULL);
2307 
2308 	pthread_mutex_lock(&endpoint->lock);
2309 	if (TAILQ_EMPTY(&ctrlr->connected_qps)) {
2310 		endpoint->ctrlr = NULL;
2311 		free_ctrlr(ctrlr, false);
2312 		pthread_mutex_unlock(&endpoint->lock);
2313 		return 0;
2314 	}
2315 
2316 	TAILQ_FOREACH(qpair, &ctrlr->connected_qps, tailq) {
2317 		spdk_nvmf_qpair_disconnect(&qpair->qpair, vfio_user_qpair_disconnect_cb, endpoint);
2318 	}
2319 	pthread_mutex_unlock(&endpoint->lock);
2320 
2321 	return 0;
2322 }
2323 
2324 /*
2325  * Poll for and process any incoming vfio-user messages.
2326  */
2327 static int
2328 vfio_user_poll_vfu_ctx(void *ctx)
2329 {
2330 	struct nvmf_vfio_user_ctrlr *ctrlr = ctx;
2331 	int ret;
2332 
2333 	assert(ctrlr != NULL);
2334 
2335 	/* This will call access_bar0_fn() if there are any writes
2336 	 * to the portion of the BAR that is not mmap'd */
2337 	ret = vfu_run_ctx(ctrlr->endpoint->vfu_ctx);
2338 	if (spdk_unlikely(ret == -1)) {
2339 		spdk_poller_unregister(&ctrlr->vfu_ctx_poller);
2340 
2341 		/* initiator shutdown or reset, waiting for another re-connect */
2342 		if (errno == ENOTCONN) {
2343 			vfio_user_destroy_ctrlr(ctrlr);
2344 			return SPDK_POLLER_BUSY;
2345 		}
2346 
2347 		fail_ctrlr(ctrlr);
2348 	}
2349 
2350 	return ret != 0 ? SPDK_POLLER_BUSY : SPDK_POLLER_IDLE;
2351 }
2352 
2353 static int
2354 handle_queue_connect_rsp(struct nvmf_vfio_user_req *req, void *cb_arg)
2355 {
2356 	struct nvmf_vfio_user_poll_group *vu_group;
2357 	struct nvmf_vfio_user_qpair *qpair = cb_arg;
2358 	struct nvmf_vfio_user_ctrlr *ctrlr;
2359 	struct nvmf_vfio_user_endpoint *endpoint;
2360 
2361 	assert(qpair != NULL);
2362 	assert(req != NULL);
2363 
2364 	ctrlr = qpair->ctrlr;
2365 	endpoint = ctrlr->endpoint;
2366 	assert(ctrlr != NULL);
2367 	assert(endpoint != NULL);
2368 
2369 	if (spdk_nvme_cpl_is_error(&req->req.rsp->nvme_cpl)) {
2370 		SPDK_ERRLOG("SC %u, SCT %u\n", req->req.rsp->nvme_cpl.status.sc, req->req.rsp->nvme_cpl.status.sct);
2371 		endpoint->ctrlr = NULL;
2372 		free_ctrlr(ctrlr, true);
2373 		return -1;
2374 	}
2375 
2376 	vu_group = SPDK_CONTAINEROF(qpair->group, struct nvmf_vfio_user_poll_group, group);
2377 	TAILQ_INSERT_TAIL(&vu_group->qps, qpair, link);
2378 	qpair->state = VFIO_USER_QPAIR_ACTIVE;
2379 
2380 	pthread_mutex_lock(&endpoint->lock);
2381 	if (nvmf_qpair_is_admin_queue(&qpair->qpair)) {
2382 		ctrlr->cntlid = qpair->qpair.ctrlr->cntlid;
2383 		ctrlr->thread = spdk_get_thread();
2384 		ctrlr->vfu_ctx_poller = SPDK_POLLER_REGISTER(vfio_user_poll_vfu_ctx, ctrlr, 0);
2385 	} else {
2386 		/* For I/O queues this command was generated in response to an
2387 		 * ADMIN I/O CREATE SUBMISSION QUEUE command which has not yet
2388 		 * been completed. Complete it now.
2389 		 */
2390 		post_completion(ctrlr, &ctrlr->qp[0]->cq, 0, 0,
2391 				qpair->create_io_sq_cmd.cid, SPDK_NVME_SC_SUCCESS, SPDK_NVME_SCT_GENERIC);
2392 	}
2393 	TAILQ_INSERT_TAIL(&ctrlr->connected_qps, qpair, tailq);
2394 	pthread_mutex_unlock(&endpoint->lock);
2395 
2396 	free(req->req.data);
2397 	req->req.data = NULL;
2398 
2399 	return 0;
2400 }
2401 
2402 /*
2403  * Add the given qpair to the given poll group. New qpairs are added via
2404  * spdk_nvmf_tgt_new_qpair(), which picks a poll group, then calls back
2405  * here via nvmf_transport_poll_group_add().
2406  */
2407 static int
2408 nvmf_vfio_user_poll_group_add(struct spdk_nvmf_transport_poll_group *group,
2409 			      struct spdk_nvmf_qpair *qpair)
2410 {
2411 	struct nvmf_vfio_user_qpair *vu_qpair;
2412 	struct nvmf_vfio_user_req *vu_req;
2413 	struct nvmf_vfio_user_ctrlr *ctrlr;
2414 	struct spdk_nvmf_request *req;
2415 	struct spdk_nvmf_fabric_connect_data *data;
2416 	bool admin;
2417 
2418 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2419 	vu_qpair->group = group;
2420 	ctrlr = vu_qpair->ctrlr;
2421 
2422 	SPDK_DEBUGLOG(nvmf_vfio, "%s: add QP%d=%p(%p) to poll_group=%p\n",
2423 		      ctrlr_id(ctrlr), vu_qpair->qpair.qid,
2424 		      vu_qpair, qpair, group);
2425 
2426 	admin = nvmf_qpair_is_admin_queue(&vu_qpair->qpair);
2427 
2428 	vu_req = get_nvmf_vfio_user_req(vu_qpair);
2429 	if (vu_req == NULL) {
2430 		return -1;
2431 	}
2432 
2433 	req = &vu_req->req;
2434 	req->cmd->connect_cmd.opcode = SPDK_NVME_OPC_FABRIC;
2435 	req->cmd->connect_cmd.cid = 0;
2436 	req->cmd->connect_cmd.fctype = SPDK_NVMF_FABRIC_COMMAND_CONNECT;
2437 	req->cmd->connect_cmd.recfmt = 0;
2438 	req->cmd->connect_cmd.sqsize = vu_qpair->qsize - 1;
2439 	req->cmd->connect_cmd.qid = admin ? 0 : qpair->qid;
2440 
2441 	req->length = sizeof(struct spdk_nvmf_fabric_connect_data);
2442 	req->data = calloc(1, req->length);
2443 	if (req->data == NULL) {
2444 		nvmf_vfio_user_req_free(req);
2445 		return -ENOMEM;
2446 	}
2447 
2448 	data = (struct spdk_nvmf_fabric_connect_data *)req->data;
2449 	data->cntlid = admin ? 0xFFFF : ctrlr->cntlid;
2450 	snprintf(data->subnqn, sizeof(data->subnqn), "%s",
2451 		 spdk_nvmf_subsystem_get_nqn(ctrlr->endpoint->subsystem));
2452 
2453 	vu_req->cb_fn = handle_queue_connect_rsp;
2454 	vu_req->cb_arg = vu_qpair;
2455 
2456 	SPDK_DEBUGLOG(nvmf_vfio,
2457 		      "%s: sending connect fabrics command for QID=%#x cntlid=%#x\n",
2458 		      ctrlr_id(ctrlr), qpair->qid, data->cntlid);
2459 
2460 	spdk_nvmf_request_exec_fabrics(req);
2461 	return 0;
2462 }
2463 
2464 static int
2465 nvmf_vfio_user_poll_group_remove(struct spdk_nvmf_transport_poll_group *group,
2466 				 struct spdk_nvmf_qpair *qpair)
2467 {
2468 	struct nvmf_vfio_user_qpair *vu_qpair;
2469 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
2470 	struct nvmf_vfio_user_endpoint *endpoint;
2471 	struct nvmf_vfio_user_poll_group *vu_group;
2472 
2473 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2474 	vu_ctrlr = vu_qpair->ctrlr;
2475 	endpoint = vu_ctrlr->endpoint;
2476 
2477 	SPDK_DEBUGLOG(nvmf_vfio,
2478 		      "%s: remove NVMf QP%d=%p from NVMf poll_group=%p\n",
2479 		      ctrlr_id(vu_qpair->ctrlr), qpair->qid, qpair, group);
2480 
2481 
2482 	vu_group = SPDK_CONTAINEROF(group, struct nvmf_vfio_user_poll_group, group);
2483 	TAILQ_REMOVE(&vu_group->qps, vu_qpair, link);
2484 
2485 	pthread_mutex_lock(&endpoint->lock);
2486 	TAILQ_REMOVE(&vu_ctrlr->connected_qps, vu_qpair, tailq);
2487 	pthread_mutex_unlock(&endpoint->lock);
2488 
2489 	return 0;
2490 }
2491 
2492 static void
2493 _nvmf_vfio_user_req_free(struct nvmf_vfio_user_qpair *vu_qpair, struct nvmf_vfio_user_req *vu_req)
2494 {
2495 	memset(&vu_req->cmd, 0, sizeof(vu_req->cmd));
2496 	memset(&vu_req->rsp, 0, sizeof(vu_req->rsp));
2497 	vu_req->iovcnt = 0;
2498 	vu_req->state = VFIO_USER_REQUEST_STATE_FREE;
2499 
2500 	TAILQ_INSERT_TAIL(&vu_qpair->reqs, vu_req, link);
2501 }
2502 
2503 static int
2504 nvmf_vfio_user_req_free(struct spdk_nvmf_request *req)
2505 {
2506 	struct nvmf_vfio_user_qpair *vu_qpair;
2507 	struct nvmf_vfio_user_req *vu_req;
2508 
2509 	assert(req != NULL);
2510 
2511 	vu_req = SPDK_CONTAINEROF(req, struct nvmf_vfio_user_req, req);
2512 	vu_qpair = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2513 
2514 	_nvmf_vfio_user_req_free(vu_qpair, vu_req);
2515 
2516 	return 0;
2517 }
2518 
2519 static int
2520 nvmf_vfio_user_req_complete(struct spdk_nvmf_request *req)
2521 {
2522 	struct nvmf_vfio_user_qpair *vu_qpair;
2523 	struct nvmf_vfio_user_req *vu_req;
2524 
2525 	assert(req != NULL);
2526 
2527 	vu_req = SPDK_CONTAINEROF(req, struct nvmf_vfio_user_req, req);
2528 	vu_qpair = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2529 
2530 	if (vu_req->cb_fn != NULL) {
2531 		if (vu_req->cb_fn(vu_req, vu_req->cb_arg) != 0) {
2532 			fail_ctrlr(vu_qpair->ctrlr);
2533 		}
2534 	}
2535 
2536 	_nvmf_vfio_user_req_free(vu_qpair, vu_req);
2537 
2538 	return 0;
2539 }
2540 
2541 static void
2542 nvmf_vfio_user_close_qpair(struct spdk_nvmf_qpair *qpair,
2543 			   spdk_nvmf_transport_qpair_fini_cb cb_fn, void *cb_arg)
2544 {
2545 	struct nvmf_vfio_user_qpair *vu_qpair;
2546 
2547 	assert(qpair != NULL);
2548 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2549 	free_qp(vu_qpair->ctrlr, qpair->qid);
2550 
2551 	if (cb_fn) {
2552 		cb_fn(cb_arg);
2553 	}
2554 }
2555 
2556 /**
2557  * Returns a preallocated spdk_nvmf_request or NULL if there isn't one available.
2558  */
2559 static struct nvmf_vfio_user_req *
2560 get_nvmf_vfio_user_req(struct nvmf_vfio_user_qpair *qpair)
2561 {
2562 	struct nvmf_vfio_user_req *req;
2563 
2564 	assert(qpair != NULL);
2565 
2566 	if (TAILQ_EMPTY(&qpair->reqs)) {
2567 		return NULL;
2568 	}
2569 
2570 	req = TAILQ_FIRST(&qpair->reqs);
2571 	TAILQ_REMOVE(&qpair->reqs, req, link);
2572 
2573 	return req;
2574 }
2575 
2576 static struct spdk_nvmf_request *
2577 get_nvmf_req(struct nvmf_vfio_user_qpair *qpair)
2578 {
2579 	struct nvmf_vfio_user_req *req = get_nvmf_vfio_user_req(qpair);
2580 
2581 	if (req == NULL) {
2582 		return NULL;
2583 	}
2584 	return &req->req;
2585 }
2586 
2587 static int
2588 get_nvmf_io_req_length(struct spdk_nvmf_request *req)
2589 {
2590 	uint16_t nr;
2591 	uint32_t nlb, nsid;
2592 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2593 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2594 	struct spdk_nvmf_ns *ns;
2595 
2596 	nsid = cmd->nsid;
2597 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
2598 	if (ns == NULL || ns->bdev == NULL) {
2599 		SPDK_ERRLOG("unsuccessful query for nsid %u\n", cmd->nsid);
2600 		return -EINVAL;
2601 	}
2602 
2603 	if (cmd->opc == SPDK_NVME_OPC_DATASET_MANAGEMENT) {
2604 		nr = cmd->cdw10_bits.dsm.nr + 1;
2605 		return nr * sizeof(struct spdk_nvme_dsm_range);
2606 	}
2607 
2608 	nlb = (cmd->cdw12 & 0x0000ffffu) + 1;
2609 	return nlb * spdk_bdev_get_block_size(ns->bdev);
2610 }
2611 
2612 static int
2613 map_admin_cmd_req(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvmf_request *req)
2614 {
2615 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2616 	uint32_t len = 0;
2617 	uint8_t fid;
2618 	int iovcnt;
2619 
2620 	req->xfer = spdk_nvme_opc_get_data_transfer(cmd->opc);
2621 	req->length = 0;
2622 	req->data = NULL;
2623 
2624 	if (req->xfer == SPDK_NVME_DATA_NONE) {
2625 		return 0;
2626 	}
2627 
2628 	switch (cmd->opc) {
2629 	case SPDK_NVME_OPC_IDENTIFY:
2630 		len = 4096;
2631 		break;
2632 	case SPDK_NVME_OPC_GET_LOG_PAGE:
2633 		len = (((cmd->cdw11_bits.get_log_page.numdu << 16) | cmd->cdw10_bits.get_log_page.numdl) + 1) * 4;
2634 		break;
2635 	case SPDK_NVME_OPC_GET_FEATURES:
2636 	case SPDK_NVME_OPC_SET_FEATURES:
2637 		fid = cmd->cdw10_bits.set_features.fid;
2638 		switch (fid) {
2639 		case SPDK_NVME_FEAT_LBA_RANGE_TYPE:
2640 			len = 4096;
2641 			break;
2642 		case SPDK_NVME_FEAT_AUTONOMOUS_POWER_STATE_TRANSITION:
2643 			len = 256;
2644 			break;
2645 		case SPDK_NVME_FEAT_TIMESTAMP:
2646 			len = 8;
2647 			break;
2648 		case SPDK_NVME_FEAT_HOST_BEHAVIOR_SUPPORT:
2649 			len = 512;
2650 			break;
2651 		case SPDK_NVME_FEAT_HOST_IDENTIFIER:
2652 			if (cmd->cdw11_bits.feat_host_identifier.bits.exhid) {
2653 				len = 16;
2654 			} else {
2655 				len = 8;
2656 			}
2657 			break;
2658 		default:
2659 			return 0;
2660 		}
2661 		break;
2662 	default:
2663 		return 0;
2664 	}
2665 
2666 	/* ADMIN command will not use SGL */
2667 	if (cmd->psdt != 0) {
2668 		return -EINVAL;
2669 	}
2670 
2671 	iovcnt = vfio_user_map_cmd(ctrlr, req, req->iov, len);
2672 	if (iovcnt < 0) {
2673 		SPDK_ERRLOG("%s: map Admin Opc %x failed\n",
2674 			    ctrlr_id(ctrlr), cmd->opc);
2675 		return -1;
2676 	}
2677 	req->length = len;
2678 	req->data = req->iov[0].iov_base;
2679 	req->iovcnt = iovcnt;
2680 
2681 	return 0;
2682 }
2683 
2684 /*
2685  * Map an I/O command's buffers.
2686  *
2687  * Returns 0 on success and -errno on failure.
2688  */
2689 static int
2690 map_io_cmd_req(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvmf_request *req)
2691 {
2692 	int len, iovcnt;
2693 	struct spdk_nvme_cmd *cmd;
2694 
2695 	assert(ctrlr != NULL);
2696 	assert(req != NULL);
2697 
2698 	cmd = &req->cmd->nvme_cmd;
2699 	req->xfer = spdk_nvme_opc_get_data_transfer(cmd->opc);
2700 	req->length = 0;
2701 	req->data = NULL;
2702 
2703 	if (spdk_unlikely(req->xfer == SPDK_NVME_DATA_NONE)) {
2704 		return 0;
2705 	}
2706 
2707 	len = get_nvmf_io_req_length(req);
2708 	if (len < 0) {
2709 		return -EINVAL;
2710 	}
2711 	req->length = len;
2712 
2713 	iovcnt = vfio_user_map_cmd(ctrlr, req, req->iov, req->length);
2714 	if (iovcnt < 0) {
2715 		SPDK_ERRLOG("%s: failed to map IO OPC %u\n", ctrlr_id(ctrlr), cmd->opc);
2716 		return -EFAULT;
2717 	}
2718 	req->data = req->iov[0].iov_base;
2719 	req->iovcnt = iovcnt;
2720 
2721 	return 0;
2722 }
2723 
2724 static int
2725 handle_cmd_req(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvme_cmd *cmd,
2726 	       struct spdk_nvmf_request *req)
2727 {
2728 	int err;
2729 	struct nvmf_vfio_user_req *vu_req;
2730 
2731 	assert(ctrlr != NULL);
2732 	assert(cmd != NULL);
2733 
2734 	/*
2735 	 * TODO: this means that there are no free requests available,
2736 	 * returning -1 will fail the controller. Theoretically this error can
2737 	 * be avoided completely by ensuring we have as many requests as slots
2738 	 * in the SQ, plus one for the the property request.
2739 	 */
2740 	if (spdk_unlikely(req == NULL)) {
2741 		return -1;
2742 	}
2743 
2744 	assert(req->qpair != NULL);
2745 	SPDK_DEBUGLOG(nvmf_vfio, "%s: handle qid%u, req opc=%#x cid=%d\n",
2746 		      ctrlr_id(ctrlr), req->qpair->qid, cmd->opc, cmd->cid);
2747 
2748 	vu_req = SPDK_CONTAINEROF(req, struct nvmf_vfio_user_req, req);
2749 	vu_req->cb_fn = handle_cmd_rsp;
2750 	vu_req->cb_arg = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2751 	req->cmd->nvme_cmd = *cmd;
2752 
2753 	if (nvmf_qpair_is_admin_queue(req->qpair)) {
2754 		err = map_admin_cmd_req(ctrlr, req);
2755 	} else {
2756 		switch (cmd->opc) {
2757 		case SPDK_NVME_OPC_RESERVATION_REGISTER:
2758 		case SPDK_NVME_OPC_RESERVATION_REPORT:
2759 		case SPDK_NVME_OPC_RESERVATION_ACQUIRE:
2760 		case SPDK_NVME_OPC_RESERVATION_RELEASE:
2761 			err = -ENOTSUP;
2762 			break;
2763 		default:
2764 			err = map_io_cmd_req(ctrlr, req);
2765 			break;
2766 		}
2767 	}
2768 
2769 	if (spdk_unlikely(err < 0)) {
2770 		struct nvmf_vfio_user_qpair *vu_qpair;
2771 
2772 		SPDK_ERRLOG("%s: process NVMe command opc 0x%x failed\n",
2773 			    ctrlr_id(ctrlr), cmd->opc);
2774 		req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
2775 		req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
2776 		err = handle_cmd_rsp(vu_req, vu_req->cb_arg);
2777 		vu_qpair = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2778 		_nvmf_vfio_user_req_free(vu_qpair, vu_req);
2779 		return err;
2780 	}
2781 
2782 	vu_req->state = VFIO_USER_REQUEST_STATE_EXECUTING;
2783 	spdk_nvmf_request_exec(req);
2784 
2785 	return 0;
2786 }
2787 
2788 /* Returns the number of commands processed, or a negative value on error. */
2789 static int
2790 nvmf_vfio_user_qpair_poll(struct nvmf_vfio_user_qpair *qpair)
2791 {
2792 	struct nvmf_vfio_user_ctrlr *ctrlr;
2793 	uint32_t new_tail;
2794 	int count = 0;
2795 
2796 	assert(qpair != NULL);
2797 
2798 	ctrlr = qpair->ctrlr;
2799 
2800 	/* Load-Acquire. */
2801 	new_tail = *tdbl(ctrlr, &qpair->sq);
2802 
2803 	/*
2804 	 * Ensure that changes to the queue are visible to us.
2805 	 * The host driver should write the queue first, do a wmb(), and then
2806 	 * update the SQ tail doorbell (their Store-Release).
2807 	 */
2808 	spdk_rmb();
2809 
2810 	new_tail = new_tail & 0xffffu;
2811 	if (spdk_unlikely(new_tail >= qpair->sq.size)) {
2812 		union spdk_nvme_async_event_completion event = {};
2813 
2814 		SPDK_DEBUGLOG(nvmf_vfio, "%s: invalid SQ%u doorbell value %u\n", ctrlr_id(ctrlr), qpair->qpair.qid,
2815 			      new_tail);
2816 		event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_ERROR;
2817 		event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_INVALID_DB_WRITE;
2818 		nvmf_ctrlr_async_event_error_event(qpair->qpair.ctrlr, event);
2819 
2820 		return 0;
2821 	}
2822 
2823 	if (sq_head(qpair) == new_tail) {
2824 		return 0;
2825 	}
2826 
2827 	count = handle_sq_tdbl_write(ctrlr, new_tail, qpair);
2828 	if (count < 0) {
2829 		fail_ctrlr(ctrlr);
2830 	}
2831 
2832 	return count;
2833 }
2834 
2835 /*
2836  * vfio-user transport poll handler. Note that the library context is polled in
2837  * a separate poller (->vfu_ctx_poller), so this poller only needs to poll the
2838  * active qpairs.
2839  *
2840  * Returns the number of commands processed, or a negative value on error.
2841  */
2842 static int
2843 nvmf_vfio_user_poll_group_poll(struct spdk_nvmf_transport_poll_group *group)
2844 {
2845 	struct nvmf_vfio_user_poll_group *vu_group;
2846 	struct nvmf_vfio_user_qpair *vu_qpair, *tmp;
2847 	int count = 0;
2848 
2849 	assert(group != NULL);
2850 
2851 	spdk_rmb();
2852 
2853 	vu_group = SPDK_CONTAINEROF(group, struct nvmf_vfio_user_poll_group, group);
2854 
2855 	TAILQ_FOREACH_SAFE(vu_qpair, &vu_group->qps, link, tmp) {
2856 		int ret;
2857 
2858 		if (spdk_unlikely(vu_qpair->state != VFIO_USER_QPAIR_ACTIVE || !vu_qpair->sq.size)) {
2859 			continue;
2860 		}
2861 
2862 		ret = nvmf_vfio_user_qpair_poll(vu_qpair);
2863 
2864 		if (ret < 0) {
2865 			return ret;
2866 		}
2867 
2868 		count += ret;
2869 	}
2870 
2871 	return count;
2872 }
2873 
2874 static int
2875 nvmf_vfio_user_qpair_get_local_trid(struct spdk_nvmf_qpair *qpair,
2876 				    struct spdk_nvme_transport_id *trid)
2877 {
2878 	struct nvmf_vfio_user_qpair *vu_qpair;
2879 	struct nvmf_vfio_user_ctrlr *ctrlr;
2880 
2881 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2882 	ctrlr = vu_qpair->ctrlr;
2883 
2884 	memcpy(trid, &ctrlr->endpoint->trid, sizeof(*trid));
2885 	return 0;
2886 }
2887 
2888 static int
2889 nvmf_vfio_user_qpair_get_peer_trid(struct spdk_nvmf_qpair *qpair,
2890 				   struct spdk_nvme_transport_id *trid)
2891 {
2892 	return 0;
2893 }
2894 
2895 static int
2896 nvmf_vfio_user_qpair_get_listen_trid(struct spdk_nvmf_qpair *qpair,
2897 				     struct spdk_nvme_transport_id *trid)
2898 {
2899 	struct nvmf_vfio_user_qpair *vu_qpair;
2900 	struct nvmf_vfio_user_ctrlr *ctrlr;
2901 
2902 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2903 	ctrlr = vu_qpair->ctrlr;
2904 
2905 	memcpy(trid, &ctrlr->endpoint->trid, sizeof(*trid));
2906 	return 0;
2907 }
2908 
2909 static void
2910 nvmf_vfio_user_qpair_abort_request(struct spdk_nvmf_qpair *qpair,
2911 				   struct spdk_nvmf_request *req)
2912 {
2913 	struct nvmf_vfio_user_qpair *vu_qpair;
2914 	struct nvmf_vfio_user_req *vu_req, *vu_req_to_abort = NULL;
2915 	uint32_t i;
2916 	uint16_t cid;
2917 
2918 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2919 
2920 	cid = req->cmd->nvme_cmd.cdw10_bits.abort.cid;
2921 	for (i = 0; i < vu_qpair->qsize; i++) {
2922 		vu_req = &vu_qpair->reqs_internal[i];
2923 		if (vu_req->state == VFIO_USER_REQUEST_STATE_EXECUTING && vu_req->cmd.cid == cid) {
2924 			vu_req_to_abort = vu_req;
2925 			break;
2926 		}
2927 	}
2928 
2929 	if (vu_req_to_abort == NULL) {
2930 		spdk_nvmf_request_complete(req);
2931 		return;
2932 	}
2933 
2934 	req->req_to_abort = &vu_req_to_abort->req;
2935 	nvmf_ctrlr_abort_request(req);
2936 }
2937 
2938 static void
2939 nvmf_vfio_user_opts_init(struct spdk_nvmf_transport_opts *opts)
2940 {
2941 	opts->max_queue_depth =		NVMF_VFIO_USER_DEFAULT_MAX_QUEUE_DEPTH;
2942 	opts->max_qpairs_per_ctrlr =	NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR;
2943 	opts->in_capsule_data_size =	0;
2944 	opts->max_io_size =		NVMF_VFIO_USER_DEFAULT_MAX_IO_SIZE;
2945 	opts->io_unit_size =		NVMF_VFIO_USER_DEFAULT_IO_UNIT_SIZE;
2946 	opts->max_aq_depth =		NVMF_VFIO_USER_DEFAULT_AQ_DEPTH;
2947 	opts->num_shared_buffers =	0;
2948 	opts->buf_cache_size =		0;
2949 	opts->association_timeout =	0;
2950 	opts->transport_specific =      NULL;
2951 }
2952 
2953 const struct spdk_nvmf_transport_ops spdk_nvmf_transport_vfio_user = {
2954 	.name = "VFIOUSER",
2955 	.type = SPDK_NVME_TRANSPORT_VFIOUSER,
2956 	.opts_init = nvmf_vfio_user_opts_init,
2957 	.create = nvmf_vfio_user_create,
2958 	.destroy = nvmf_vfio_user_destroy,
2959 
2960 	.listen = nvmf_vfio_user_listen,
2961 	.stop_listen = nvmf_vfio_user_stop_listen,
2962 	.accept = nvmf_vfio_user_accept,
2963 	.cdata_init = nvmf_vfio_user_cdata_init,
2964 	.listen_associate = nvmf_vfio_user_listen_associate,
2965 
2966 	.listener_discover = nvmf_vfio_user_discover,
2967 
2968 	.poll_group_create = nvmf_vfio_user_poll_group_create,
2969 	.poll_group_destroy = nvmf_vfio_user_poll_group_destroy,
2970 	.poll_group_add = nvmf_vfio_user_poll_group_add,
2971 	.poll_group_remove = nvmf_vfio_user_poll_group_remove,
2972 	.poll_group_poll = nvmf_vfio_user_poll_group_poll,
2973 
2974 	.req_free = nvmf_vfio_user_req_free,
2975 	.req_complete = nvmf_vfio_user_req_complete,
2976 
2977 	.qpair_fini = nvmf_vfio_user_close_qpair,
2978 	.qpair_get_local_trid = nvmf_vfio_user_qpair_get_local_trid,
2979 	.qpair_get_peer_trid = nvmf_vfio_user_qpair_get_peer_trid,
2980 	.qpair_get_listen_trid = nvmf_vfio_user_qpair_get_listen_trid,
2981 	.qpair_abort_request = nvmf_vfio_user_qpair_abort_request,
2982 };
2983 
2984 SPDK_NVMF_TRANSPORT_REGISTER(muser, &spdk_nvmf_transport_vfio_user);
2985 SPDK_LOG_REGISTER_COMPONENT(nvmf_vfio)
2986