xref: /spdk/lib/nvmf/vfio_user.c (revision d919a197d60e407aa1137d7512f8b0af92f3d593)
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_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 	uint16_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 uint16_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 struct nvme_q *
903 lookup_io_q(struct nvmf_vfio_user_ctrlr *ctrlr, const uint16_t qid, const bool is_cq)
904 {
905 	struct nvme_q *q;
906 
907 	assert(ctrlr != NULL);
908 
909 	if (qid == 0 || qid >= NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR) {
910 		return NULL;
911 	}
912 
913 	if (ctrlr->qp[qid] == NULL) {
914 		return NULL;
915 	}
916 
917 	if (is_cq) {
918 		q = &ctrlr->qp[qid]->cq;
919 	} else {
920 		q = &ctrlr->qp[qid]->sq;
921 	}
922 
923 	if (q->addr == NULL) {
924 		return NULL;
925 	}
926 
927 	return q;
928 }
929 
930 static void
931 unmap_qp(struct nvmf_vfio_user_qpair *qp)
932 {
933 	struct nvmf_vfio_user_ctrlr *ctrlr;
934 
935 	if (qp->ctrlr == NULL) {
936 		return;
937 	}
938 	ctrlr = qp->ctrlr;
939 
940 	SPDK_DEBUGLOG(nvmf_vfio, "%s: unmap QP%d\n",
941 		      ctrlr_id(ctrlr), qp->qpair.qid);
942 
943 	if (qp->sq.addr != NULL) {
944 		vfu_unmap_sg(ctrlr->endpoint->vfu_ctx, qp->sq.sg, &qp->sq.iov, 1);
945 		qp->sq.addr = NULL;
946 	}
947 
948 	if (qp->cq.addr != NULL) {
949 		vfu_unmap_sg(ctrlr->endpoint->vfu_ctx, qp->cq.sg, &qp->cq.iov, 1);
950 		qp->cq.addr = NULL;
951 	}
952 }
953 
954 static int
955 remap_qp(struct nvmf_vfio_user_qpair *vu_qpair)
956 {
957 	struct nvme_q *sq, *cq;
958 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
959 	int ret;
960 
961 	vu_ctrlr = vu_qpair->ctrlr;
962 	sq = &vu_qpair->sq;
963 	cq = &vu_qpair->cq;
964 
965 	if (sq->size) {
966 		ret = map_q(vu_ctrlr, sq, false, false);
967 		if (ret) {
968 			SPDK_DEBUGLOG(nvmf_vfio, "Memory isn't ready to remap SQID %d %#lx-%#lx\n",
969 				      io_q_id(sq), sq->prp1, sq->prp1 + sq->size * sizeof(struct spdk_nvme_cmd));
970 			return -EFAULT;
971 		}
972 	}
973 
974 	if (cq->size) {
975 		ret = map_q(vu_ctrlr, cq, true, false);
976 		if (ret) {
977 			SPDK_DEBUGLOG(nvmf_vfio, "Memory isn't ready to remap CQID %d %#lx-%#lx\n",
978 				      io_q_id(cq), cq->prp1, cq->prp1 + cq->size * sizeof(struct spdk_nvme_cpl));
979 			return -EFAULT;
980 		}
981 
982 	}
983 
984 	return 0;
985 }
986 
987 static void
988 free_qp(struct nvmf_vfio_user_ctrlr *ctrlr, uint16_t qid)
989 {
990 	struct nvmf_vfio_user_qpair *qpair;
991 	struct nvmf_vfio_user_req *vu_req;
992 	uint32_t i;
993 
994 	if (ctrlr == NULL) {
995 		return;
996 	}
997 
998 	qpair = ctrlr->qp[qid];
999 	if (qpair == NULL) {
1000 		return;
1001 	}
1002 
1003 	SPDK_DEBUGLOG(nvmf_vfio, "%s: destroy QP%d=%p\n", ctrlr_id(ctrlr),
1004 		      qid, qpair);
1005 
1006 	unmap_qp(qpair);
1007 
1008 	for (i = 0; i < qpair->qsize; i++) {
1009 		vu_req = &qpair->reqs_internal[i];
1010 		free(vu_req->sg);
1011 	}
1012 	free(qpair->reqs_internal);
1013 
1014 	free(qpair->sq.sg);
1015 	free(qpair->cq.sg);
1016 	free(qpair);
1017 
1018 	ctrlr->qp[qid] = NULL;
1019 }
1020 
1021 /* This function can only fail because of memory allocation errors. */
1022 static int
1023 init_qp(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvmf_transport *transport,
1024 	const uint16_t qsize, const uint16_t id)
1025 {
1026 	uint16_t i;
1027 	struct nvmf_vfio_user_qpair *qpair;
1028 	struct nvmf_vfio_user_req *vu_req, *tmp;
1029 	struct spdk_nvmf_request *req;
1030 
1031 	assert(ctrlr != NULL);
1032 	assert(transport != NULL);
1033 
1034 	qpair = calloc(1, sizeof(*qpair));
1035 	if (qpair == NULL) {
1036 		return -ENOMEM;
1037 	}
1038 	qpair->sq.sg = calloc(1, dma_sg_size());
1039 	if (qpair->sq.sg == NULL) {
1040 		free(qpair);
1041 		return -ENOMEM;
1042 	}
1043 	qpair->cq.sg = calloc(1, dma_sg_size());
1044 	if (qpair->cq.sg == NULL) {
1045 		free(qpair->sq.sg);
1046 		free(qpair);
1047 		return -ENOMEM;
1048 	}
1049 
1050 	qpair->qpair.qid = id;
1051 	qpair->qpair.transport = transport;
1052 	qpair->ctrlr = ctrlr;
1053 	qpair->qsize = qsize;
1054 
1055 	TAILQ_INIT(&qpair->reqs);
1056 
1057 	qpair->reqs_internal = calloc(qsize, sizeof(struct nvmf_vfio_user_req));
1058 	if (qpair->reqs_internal == NULL) {
1059 		SPDK_ERRLOG("%s: error allocating reqs: %m\n", ctrlr_id(ctrlr));
1060 		goto reqs_err;
1061 	}
1062 
1063 	for (i = 0; i < qsize; i++) {
1064 		vu_req = &qpair->reqs_internal[i];
1065 		vu_req->sg = calloc(NVMF_VFIO_USER_MAX_IOVECS, dma_sg_size());
1066 		if (vu_req->sg == NULL) {
1067 			goto sg_err;
1068 		}
1069 
1070 		req = &vu_req->req;
1071 		req->qpair = &qpair->qpair;
1072 		req->rsp = (union nvmf_c2h_msg *)&vu_req->rsp;
1073 		req->cmd = (union nvmf_h2c_msg *)&vu_req->cmd;
1074 
1075 		TAILQ_INSERT_TAIL(&qpair->reqs, vu_req, link);
1076 	}
1077 
1078 	ctrlr->qp[id] = qpair;
1079 	return 0;
1080 
1081 sg_err:
1082 	TAILQ_FOREACH_SAFE(vu_req, &qpair->reqs, link, tmp) {
1083 		free(vu_req->sg);
1084 	}
1085 	free(qpair->reqs_internal);
1086 
1087 reqs_err:
1088 	free(qpair->sq.sg);
1089 	free(qpair->cq.sg);
1090 	free(qpair);
1091 	return -ENOMEM;
1092 }
1093 
1094 /*
1095  * Creates a completion or submission I/O queue. Returns 0 on success, -errno
1096  * on error.
1097  */
1098 static int
1099 handle_create_io_q(struct nvmf_vfio_user_ctrlr *ctrlr,
1100 		   struct spdk_nvme_cmd *cmd, const bool is_cq)
1101 {
1102 	uint16_t qid, qsize;
1103 	uint16_t sc = SPDK_NVME_SC_SUCCESS;
1104 	uint16_t sct = SPDK_NVME_SCT_GENERIC;
1105 	int err = 0;
1106 	struct nvmf_vfio_user_qpair *vu_qpair;
1107 	struct nvme_q *io_q;
1108 
1109 	assert(ctrlr != NULL);
1110 	assert(cmd != NULL);
1111 
1112 	qid = cmd->cdw10_bits.create_io_q.qid;
1113 	if (qid == 0 || qid >= NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR) {
1114 		SPDK_ERRLOG("%s: invalid QID=%d, max=%d\n", ctrlr_id(ctrlr),
1115 			    qid, NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR);
1116 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1117 		sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1118 		goto out;
1119 	}
1120 
1121 	if (lookup_io_q(ctrlr, qid, is_cq)) {
1122 		SPDK_ERRLOG("%s: %cQ%d already exists\n", ctrlr_id(ctrlr),
1123 			    is_cq ? 'C' : 'S', qid);
1124 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1125 		sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1126 		goto out;
1127 	}
1128 
1129 	qsize = cmd->cdw10_bits.create_io_q.qsize + 1;
1130 	if (qsize > max_queue_size(ctrlr)) {
1131 		SPDK_ERRLOG("%s: queue too big, want=%d, max=%d\n", ctrlr_id(ctrlr),
1132 			    qsize, max_queue_size(ctrlr));
1133 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1134 		sc = SPDK_NVME_SC_INVALID_QUEUE_SIZE;
1135 		goto out;
1136 	}
1137 
1138 	SPDK_DEBUGLOG(nvmf_vfio,
1139 		      "%s: create I/O %cQ%d: QSIZE=%#x\n", ctrlr_id(ctrlr),
1140 		      is_cq ? 'C' : 'S', qid, qsize);
1141 
1142 	if (is_cq) {
1143 		err = init_qp(ctrlr, ctrlr->qp[0]->qpair.transport, qsize, qid);
1144 		if (err != 0) {
1145 			sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
1146 			goto out;
1147 		}
1148 
1149 		io_q = &ctrlr->qp[qid]->cq;
1150 		if (cmd->cdw11_bits.create_io_cq.pc != 0x1) {
1151 			SPDK_ERRLOG("%s: non-PC CQ not supporred\n", ctrlr_id(ctrlr));
1152 			sc = SPDK_NVME_SC_INVALID_CONTROLLER_MEM_BUF;
1153 			goto out;
1154 		}
1155 		io_q->ien = cmd->cdw11_bits.create_io_cq.ien;
1156 		io_q->iv = cmd->cdw11_bits.create_io_cq.iv;
1157 		io_q->phase = true;
1158 	} else {
1159 		if (cmd->cdw11_bits.create_io_sq.cqid == 0) {
1160 			SPDK_ERRLOG("%s: invalid CQID 0\n", ctrlr_id(ctrlr));
1161 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1162 			sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1163 			goto out;
1164 
1165 		}
1166 		/* CQ must be created before SQ */
1167 		if (!lookup_io_q(ctrlr, cmd->cdw11_bits.create_io_sq.cqid, true)) {
1168 			SPDK_ERRLOG("%s: CQ%d does not exist\n", ctrlr_id(ctrlr),
1169 				    cmd->cdw11_bits.create_io_sq.cqid);
1170 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1171 			sc = SPDK_NVME_SC_COMPLETION_QUEUE_INVALID;
1172 			goto out;
1173 		}
1174 
1175 		if (cmd->cdw11_bits.create_io_sq.pc != 0x1) {
1176 			SPDK_ERRLOG("%s: non-PC SQ not supported\n", ctrlr_id(ctrlr));
1177 			sc = SPDK_NVME_SC_INVALID_CONTROLLER_MEM_BUF;
1178 			goto out;
1179 		}
1180 		/* TODO: support shared IO CQ */
1181 		if (qid != cmd->cdw11_bits.create_io_sq.cqid) {
1182 			SPDK_ERRLOG("%s: doesn't support shared CQ now\n", ctrlr_id(ctrlr));
1183 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1184 			sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1185 		}
1186 
1187 		io_q = &ctrlr->qp[qid]->sq;
1188 		io_q->cqid = cmd->cdw11_bits.create_io_sq.cqid;
1189 		SPDK_DEBUGLOG(nvmf_vfio, "%s: SQ%d CQID=%d\n", ctrlr_id(ctrlr),
1190 			      qid, io_q->cqid);
1191 	}
1192 
1193 	io_q->is_cq = is_cq;
1194 	io_q->size = qsize;
1195 	io_q->prp1 = cmd->dptr.prp.prp1;
1196 
1197 	err = map_q(ctrlr, io_q, is_cq, true);
1198 	if (err) {
1199 		sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
1200 		SPDK_ERRLOG("%s: failed to map I/O queue: %m\n", ctrlr_id(ctrlr));
1201 		goto out;
1202 	}
1203 
1204 	SPDK_DEBUGLOG(nvmf_vfio, "%s: mapped %cQ%d IOVA=%#lx vaddr=%#llx\n",
1205 		      ctrlr_id(ctrlr), is_cq ? 'C' : 'S',
1206 		      qid, cmd->dptr.prp.prp1, (unsigned long long)io_q->addr);
1207 
1208 	if (is_cq) {
1209 		*hdbl(ctrlr, io_q) = 0;
1210 	} else {
1211 		/*
1212 		 * Create our new I/O qpair. This asynchronously invokes, on a
1213 		 * suitable poll group, the nvmf_vfio_user_poll_group_add()
1214 		 * callback, which will call spdk_nvmf_request_exec_fabrics()
1215 		 * with a generated fabrics connect command. This command is
1216 		 * then eventually completed via handle_queue_connect_rsp().
1217 		 */
1218 		vu_qpair = ctrlr->qp[qid];
1219 		vu_qpair->create_io_sq_cmd = *cmd;
1220 		spdk_nvmf_tgt_new_qpair(ctrlr->transport->transport.tgt,
1221 					&vu_qpair->qpair);
1222 		*tdbl(ctrlr, io_q) = 0;
1223 		return 0;
1224 	}
1225 
1226 out:
1227 	return post_completion(ctrlr, &ctrlr->qp[0]->cq, 0, 0, cmd->cid, sc, sct);
1228 }
1229 
1230 /* For ADMIN I/O DELETE COMPLETION QUEUE the NVMf library will disconnect and free
1231  * queue pair, so save the command in a context.
1232  */
1233 struct vfio_user_delete_cq_ctx {
1234 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
1235 	struct spdk_nvme_cmd delete_io_cq_cmd;
1236 };
1237 
1238 static void
1239 vfio_user_qpair_delete_cb(void *cb_arg)
1240 {
1241 	struct vfio_user_delete_cq_ctx *ctx = cb_arg;
1242 	struct nvmf_vfio_user_ctrlr *vu_ctrlr = ctx->vu_ctrlr;
1243 
1244 	post_completion(vu_ctrlr, &vu_ctrlr->qp[0]->cq, 0, 0, ctx->delete_io_cq_cmd.cid,
1245 			SPDK_NVME_SC_SUCCESS, SPDK_NVME_SCT_GENERIC);
1246 	free(ctx);
1247 }
1248 
1249 /*
1250  * Deletes a completion or submission I/O queue.
1251  */
1252 static int
1253 handle_del_io_q(struct nvmf_vfio_user_ctrlr *ctrlr,
1254 		struct spdk_nvme_cmd *cmd, const bool is_cq)
1255 {
1256 	uint16_t sct = SPDK_NVME_SCT_GENERIC;
1257 	uint16_t sc = SPDK_NVME_SC_SUCCESS;
1258 	struct nvmf_vfio_user_qpair *vu_qpair;
1259 	struct vfio_user_delete_cq_ctx *ctx;
1260 
1261 	SPDK_DEBUGLOG(nvmf_vfio, "%s: delete I/O %cQ: QID=%d\n",
1262 		      ctrlr_id(ctrlr), is_cq ? 'C' : 'S',
1263 		      cmd->cdw10_bits.delete_io_q.qid);
1264 
1265 	if (lookup_io_q(ctrlr, cmd->cdw10_bits.delete_io_q.qid, is_cq) == NULL) {
1266 		SPDK_ERRLOG("%s: I/O %cQ%d does not exist\n", ctrlr_id(ctrlr),
1267 			    is_cq ? 'C' : 'S', cmd->cdw10_bits.delete_io_q.qid);
1268 		sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1269 		sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
1270 		goto out;
1271 	}
1272 
1273 	vu_qpair = ctrlr->qp[cmd->cdw10_bits.delete_io_q.qid];
1274 	if (is_cq) {
1275 		/* SQ must have been deleted first */
1276 		if (vu_qpair->state != VFIO_USER_QPAIR_DELETED) {
1277 			SPDK_ERRLOG("%s: the associated SQ must be deleted first\n", ctrlr_id(ctrlr));
1278 			sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1279 			sc = SPDK_NVME_SC_INVALID_QUEUE_DELETION;
1280 			goto out;
1281 		}
1282 		ctx = calloc(1, sizeof(*ctx));
1283 		if (!ctx) {
1284 			sct = SPDK_NVME_SCT_GENERIC;
1285 			sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
1286 			goto out;
1287 		}
1288 		ctx->vu_ctrlr = ctrlr;
1289 		ctx->delete_io_cq_cmd = *cmd;
1290 		spdk_nvmf_qpair_disconnect(&vu_qpair->qpair, vfio_user_qpair_delete_cb, ctx);
1291 		return 0;
1292 	} else {
1293 		/*
1294 		 * This doesn't actually delete the SQ, We're merely telling the poll_group_poll
1295 		 * function to skip checking this SQ.  The queue pair will be disconnected in Delete
1296 		 * IO CQ command.
1297 		 */
1298 		assert(vu_qpair->state == VFIO_USER_QPAIR_ACTIVE);
1299 		vu_qpair->state = VFIO_USER_QPAIR_DELETED;
1300 	}
1301 
1302 out:
1303 	return post_completion(ctrlr, &ctrlr->qp[0]->cq, 0, 0, cmd->cid, sc, sct);
1304 }
1305 
1306 /*
1307  * Returns 0 on success and -errno on error.
1308  */
1309 static int
1310 consume_admin_cmd(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvme_cmd *cmd)
1311 {
1312 	assert(ctrlr != NULL);
1313 	assert(cmd != NULL);
1314 
1315 	switch (cmd->opc) {
1316 	case SPDK_NVME_OPC_CREATE_IO_CQ:
1317 	case SPDK_NVME_OPC_CREATE_IO_SQ:
1318 		return handle_create_io_q(ctrlr, cmd,
1319 					  cmd->opc == SPDK_NVME_OPC_CREATE_IO_CQ);
1320 	case SPDK_NVME_OPC_DELETE_IO_SQ:
1321 	case SPDK_NVME_OPC_DELETE_IO_CQ:
1322 		return handle_del_io_q(ctrlr, cmd,
1323 				       cmd->opc == SPDK_NVME_OPC_DELETE_IO_CQ);
1324 	default:
1325 		return handle_cmd_req(ctrlr, cmd, get_nvmf_req(ctrlr->qp[0]));
1326 	}
1327 }
1328 
1329 static int
1330 handle_cmd_rsp(struct nvmf_vfio_user_req *vu_req, void *cb_arg)
1331 {
1332 	struct nvmf_vfio_user_qpair *vu_qpair = cb_arg;
1333 	struct nvmf_vfio_user_ctrlr *vu_ctrlr = vu_qpair->ctrlr;
1334 	uint16_t sqid, cqid;
1335 
1336 	assert(vu_qpair != NULL);
1337 	assert(vu_req != NULL);
1338 	assert(vu_ctrlr != NULL);
1339 
1340 	if (spdk_likely(vu_req->iovcnt)) {
1341 		vfu_unmap_sg(vu_ctrlr->endpoint->vfu_ctx, vu_req->sg, vu_req->iov, vu_req->iovcnt);
1342 	}
1343 	sqid = vu_qpair->qpair.qid;
1344 	cqid = vu_ctrlr->qp[sqid]->sq.cqid;
1345 
1346 	return post_completion(vu_ctrlr, &vu_ctrlr->qp[cqid]->cq,
1347 			       vu_req->req.rsp->nvme_cpl.cdw0,
1348 			       sqid,
1349 			       vu_req->req.cmd->nvme_cmd.cid,
1350 			       vu_req->req.rsp->nvme_cpl.status.sc,
1351 			       vu_req->req.rsp->nvme_cpl.status.sct);
1352 }
1353 
1354 static int
1355 consume_cmd(struct nvmf_vfio_user_ctrlr *ctrlr, struct nvmf_vfio_user_qpair *qpair,
1356 	    struct spdk_nvme_cmd *cmd)
1357 {
1358 	assert(qpair != NULL);
1359 	if (nvmf_qpair_is_admin_queue(&qpair->qpair)) {
1360 		return consume_admin_cmd(ctrlr, cmd);
1361 	}
1362 
1363 	return handle_cmd_req(ctrlr, cmd, get_nvmf_req(qpair));
1364 }
1365 
1366 /* Returns the number of commands processed, or a negative value on error. */
1367 static int
1368 handle_sq_tdbl_write(struct nvmf_vfio_user_ctrlr *ctrlr, const uint32_t new_tail,
1369 		     struct nvmf_vfio_user_qpair *qpair)
1370 {
1371 	struct spdk_nvme_cmd *queue;
1372 	int count = 0;
1373 
1374 	assert(ctrlr != NULL);
1375 	assert(qpair != NULL);
1376 
1377 	queue = qpair->sq.addr;
1378 	while (sq_head(qpair) != new_tail) {
1379 		int err;
1380 		struct spdk_nvme_cmd *cmd = &queue[sq_head(qpair)];
1381 
1382 		count++;
1383 
1384 		/*
1385 		 * SQHD must contain the new head pointer, so we must increase
1386 		 * it before we generate a completion.
1387 		 */
1388 		sqhd_advance(ctrlr, qpair);
1389 
1390 		err = consume_cmd(ctrlr, qpair, cmd);
1391 		if (err != 0) {
1392 			return err;
1393 		}
1394 	}
1395 
1396 	return count;
1397 }
1398 
1399 static int
1400 enable_admin_queue(struct nvmf_vfio_user_ctrlr *ctrlr)
1401 {
1402 	int err;
1403 
1404 	assert(ctrlr != NULL);
1405 
1406 	err = acq_setup(ctrlr);
1407 	if (err != 0) {
1408 		return err;
1409 	}
1410 
1411 	err = asq_setup(ctrlr);
1412 	if (err != 0) {
1413 		return err;
1414 	}
1415 
1416 	return 0;
1417 }
1418 
1419 static void
1420 disable_admin_queue(struct nvmf_vfio_user_ctrlr *ctrlr)
1421 {
1422 	assert(ctrlr->qp[0] != NULL);
1423 
1424 	unmap_qp(ctrlr->qp[0]);
1425 }
1426 
1427 static void
1428 memory_region_add_cb(vfu_ctx_t *vfu_ctx, vfu_dma_info_t *info)
1429 {
1430 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1431 	struct nvmf_vfio_user_ctrlr *ctrlr;
1432 	struct nvmf_vfio_user_qpair *qpair;
1433 	int ret;
1434 
1435 	/*
1436 	 * We're not interested in any DMA regions that aren't mappable (we don't
1437 	 * support clients that don't share their memory).
1438 	 */
1439 	if (!info->vaddr) {
1440 		return;
1441 	}
1442 
1443 	if (((uintptr_t)info->mapping.iov_base & MASK_2MB) ||
1444 	    (info->mapping.iov_len & MASK_2MB)) {
1445 		SPDK_DEBUGLOG(nvmf_vfio, "Invalid memory region vaddr %p, IOVA %#lx-%#lx\n", info->vaddr,
1446 			      (uintptr_t)info->mapping.iov_base,
1447 			      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1448 		return;
1449 	}
1450 
1451 	assert(endpoint != NULL);
1452 	if (endpoint->ctrlr == NULL) {
1453 		return;
1454 	}
1455 	ctrlr = endpoint->ctrlr;
1456 
1457 	SPDK_DEBUGLOG(nvmf_vfio, "%s: map IOVA %#lx-%#lx\n", ctrlr_id(ctrlr),
1458 		      (uintptr_t)info->mapping.iov_base,
1459 		      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1460 
1461 	/* VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE are enabled when registering to VFIO, here we also
1462 	 * check the protection bits before registering.
1463 	 */
1464 	if (info->prot == (PROT_WRITE | PROT_READ)) {
1465 		ret = spdk_mem_register(info->mapping.iov_base, info->mapping.iov_len);
1466 		if (ret) {
1467 			SPDK_ERRLOG("Memory region register %#lx-%#lx failed, ret=%d\n",
1468 				    (uint64_t)(uintptr_t)info->mapping.iov_base,
1469 				    (uint64_t)(uintptr_t)info->mapping.iov_base + info->mapping.iov_len,
1470 				    ret);
1471 		}
1472 	}
1473 
1474 	pthread_mutex_lock(&endpoint->lock);
1475 	TAILQ_FOREACH(qpair, &ctrlr->connected_qps, tailq) {
1476 		if (qpair->state != VFIO_USER_QPAIR_INACTIVE) {
1477 			continue;
1478 		}
1479 
1480 		ret = remap_qp(qpair);
1481 		if (ret) {
1482 			continue;
1483 		}
1484 		qpair->state = VFIO_USER_QPAIR_ACTIVE;
1485 		SPDK_DEBUGLOG(nvmf_vfio, "Remap QP %u successfully\n", qpair->qpair.qid);
1486 	}
1487 	pthread_mutex_unlock(&endpoint->lock);
1488 }
1489 
1490 static int
1491 memory_region_remove_cb(vfu_ctx_t *vfu_ctx, vfu_dma_info_t *info)
1492 {
1493 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1494 	struct nvmf_vfio_user_ctrlr *ctrlr;
1495 	struct nvmf_vfio_user_qpair *qpair;
1496 	void *map_start, *map_end;
1497 	int ret = 0;
1498 
1499 	if (!info->vaddr) {
1500 		return 0;
1501 	}
1502 
1503 	if (((uintptr_t)info->mapping.iov_base & MASK_2MB) ||
1504 	    (info->mapping.iov_len & MASK_2MB)) {
1505 		SPDK_DEBUGLOG(nvmf_vfio, "Invalid memory region vaddr %p, IOVA %#lx-%#lx\n", info->vaddr,
1506 			      (uintptr_t)info->mapping.iov_base,
1507 			      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1508 		return 0;
1509 	}
1510 
1511 	assert(endpoint != NULL);
1512 	if (endpoint->ctrlr == NULL) {
1513 		return 0;
1514 	}
1515 	ctrlr = endpoint->ctrlr;
1516 
1517 	SPDK_DEBUGLOG(nvmf_vfio, "%s: unmap IOVA %#lx-%#lx\n", ctrlr_id(ctrlr),
1518 		      (uintptr_t)info->mapping.iov_base,
1519 		      (uintptr_t)info->mapping.iov_base + info->mapping.iov_len);
1520 
1521 	map_start = info->mapping.iov_base;
1522 	map_end = info->mapping.iov_base + info->mapping.iov_len;
1523 
1524 	pthread_mutex_lock(&endpoint->lock);
1525 	TAILQ_FOREACH(qpair, &ctrlr->connected_qps, tailq) {
1526 		if ((qpair->cq.addr >= map_start && qpair->cq.addr <= map_end) ||
1527 		    (qpair->sq.addr >= map_start && qpair->sq.addr <= map_end)) {
1528 			/* TODO: Ideally we should disconnect this queue pair
1529 			 * before returning to caller.
1530 			 */
1531 			unmap_qp(qpair);
1532 			qpair->state = VFIO_USER_QPAIR_INACTIVE;
1533 		}
1534 	}
1535 	pthread_mutex_unlock(&endpoint->lock);
1536 
1537 	if (info->prot == (PROT_WRITE | PROT_READ)) {
1538 		ret = spdk_mem_unregister(info->mapping.iov_base, info->mapping.iov_len);
1539 		if (ret) {
1540 			SPDK_ERRLOG("Memory region unregister %#lx-%#lx failed, ret=%d\n",
1541 				    (uint64_t)(uintptr_t)info->mapping.iov_base,
1542 				    (uint64_t)(uintptr_t)info->mapping.iov_base + info->mapping.iov_len,
1543 				    ret);
1544 		}
1545 	}
1546 
1547 	return 0;
1548 }
1549 
1550 static int
1551 nvmf_vfio_user_prop_req_rsp(struct nvmf_vfio_user_req *req, void *cb_arg)
1552 {
1553 	struct nvmf_vfio_user_qpair *vu_qpair = cb_arg;
1554 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
1555 	bool disable_admin = false;
1556 	int ret;
1557 
1558 	assert(vu_qpair != NULL);
1559 	assert(req != NULL);
1560 
1561 	if (req->req.cmd->prop_get_cmd.fctype == SPDK_NVMF_FABRIC_COMMAND_PROPERTY_GET) {
1562 		assert(vu_qpair->ctrlr != NULL);
1563 		assert(req != NULL);
1564 
1565 		memcpy(req->req.data,
1566 		       &req->req.rsp->prop_get_rsp.value.u64,
1567 		       req->req.length);
1568 	} else {
1569 		assert(req->req.cmd->prop_set_cmd.fctype == SPDK_NVMF_FABRIC_COMMAND_PROPERTY_SET);
1570 		assert(vu_qpair->ctrlr != NULL);
1571 		vu_ctrlr = vu_qpair->ctrlr;
1572 
1573 		if (req->req.cmd->prop_set_cmd.ofst == offsetof(struct spdk_nvme_registers, cc)) {
1574 			union spdk_nvme_cc_register cc, diff;
1575 
1576 			cc.raw = req->req.cmd->prop_set_cmd.value.u64;
1577 			diff.raw = cc.raw ^ req->cc.raw;
1578 
1579 			if (diff.bits.en) {
1580 				if (cc.bits.en) {
1581 					SPDK_DEBUGLOG(nvmf_vfio, "%s: MAP Admin queue\n", ctrlr_id(vu_ctrlr));
1582 					ret = enable_admin_queue(vu_ctrlr);
1583 					if (ret) {
1584 						SPDK_ERRLOG("%s: failed to map Admin queue\n", ctrlr_id(vu_ctrlr));
1585 						return ret;
1586 					}
1587 					vu_qpair->state = VFIO_USER_QPAIR_ACTIVE;
1588 				} else {
1589 					disable_admin = true;
1590 				}
1591 			}
1592 
1593 			if (diff.bits.shn) {
1594 				if (cc.bits.shn == SPDK_NVME_SHN_NORMAL || cc.bits.shn == SPDK_NVME_SHN_ABRUPT) {
1595 					disable_admin = true;
1596 				}
1597 			}
1598 
1599 			if (disable_admin) {
1600 				SPDK_DEBUGLOG(nvmf_vfio,
1601 					      "%s: UNMAP Admin queue\n",
1602 					      ctrlr_id(vu_ctrlr));
1603 				vu_qpair->state = VFIO_USER_QPAIR_INACTIVE;
1604 				disable_admin_queue(vu_ctrlr);
1605 				/* For PCIe controller reset or shutdown, we will drop all AER responses */
1606 				nvmf_ctrlr_abort_aer(vu_qpair->qpair.ctrlr);
1607 			}
1608 		}
1609 	}
1610 
1611 	return 0;
1612 }
1613 
1614 /*
1615  * Handles a write at offset 0x1000 or more; this is the non-mapped path when a
1616  * doorbell is written via access_bar0_fn().
1617  *
1618  * DSTRD is set to fixed value 0 for NVMf.
1619  *
1620  */
1621 static int
1622 handle_dbl_access(struct nvmf_vfio_user_ctrlr *ctrlr, uint32_t *buf,
1623 		  const size_t count, loff_t pos, const bool is_write)
1624 {
1625 	assert(ctrlr != NULL);
1626 	assert(buf != NULL);
1627 
1628 	if (count != sizeof(uint32_t)) {
1629 		SPDK_ERRLOG("%s: bad doorbell buffer size %ld\n",
1630 			    ctrlr_id(ctrlr), count);
1631 		errno = EINVAL;
1632 		return -1;
1633 	}
1634 
1635 	pos -= NVMF_VFIO_USER_DOORBELLS_OFFSET;
1636 
1637 	/* pos must be dword aligned */
1638 	if ((pos & 0x3) != 0) {
1639 		SPDK_ERRLOG("%s: bad doorbell offset %#lx\n", ctrlr_id(ctrlr), pos);
1640 		errno = EINVAL;
1641 		return -1;
1642 	}
1643 
1644 	/* convert byte offset to array index */
1645 	pos >>= 2;
1646 
1647 	if (pos >= NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR * 2) {
1648 		SPDK_ERRLOG("%s: bad doorbell index %#lx\n", ctrlr_id(ctrlr), pos);
1649 		errno = EINVAL;
1650 		return -1;
1651 	}
1652 
1653 	if (is_write) {
1654 		ctrlr->doorbells[pos] = *buf;
1655 		spdk_wmb();
1656 	} else {
1657 		spdk_rmb();
1658 		*buf = ctrlr->doorbells[pos];
1659 	}
1660 	return 0;
1661 }
1662 
1663 static ssize_t
1664 access_bar0_fn(vfu_ctx_t *vfu_ctx, char *buf, size_t count, loff_t pos,
1665 	       bool is_write)
1666 {
1667 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1668 	struct nvmf_vfio_user_ctrlr *ctrlr;
1669 	struct nvmf_vfio_user_req *req;
1670 	const struct spdk_nvmf_registers *regs;
1671 	int ret;
1672 
1673 	ctrlr = endpoint->ctrlr;
1674 
1675 	SPDK_DEBUGLOG(nvmf_vfio,
1676 		      "%s: bar0 %s ctrlr: %p, count=%zu, pos=%"PRIX64"\n",
1677 		      endpoint_id(endpoint), is_write ? "write" : "read",
1678 		      ctrlr, count, pos);
1679 
1680 	if (pos >= NVMF_VFIO_USER_DOORBELLS_OFFSET) {
1681 		/*
1682 		 * The fact that the doorbells can be memory mapped doesn't mean
1683 		 * that the client (VFIO in QEMU) is obliged to memory map them,
1684 		 * it might still elect to access them via regular read/write;
1685 		 * we might also have had disable_mappable_bar0 set.
1686 		 */
1687 		ret = handle_dbl_access(ctrlr, (uint32_t *)buf, count,
1688 					pos, is_write);
1689 		if (ret == 0) {
1690 			return count;
1691 		}
1692 		return ret;
1693 	}
1694 
1695 	/* Construct a Fabric Property Get/Set command and send it */
1696 	req = get_nvmf_vfio_user_req(ctrlr->qp[0]);
1697 	if (req == NULL) {
1698 		errno = ENOBUFS;
1699 		return -1;
1700 	}
1701 	regs = spdk_nvmf_ctrlr_get_regs(ctrlr->qp[0]->qpair.ctrlr);
1702 	req->cc.raw = regs->cc.raw;
1703 
1704 	req->cb_fn = nvmf_vfio_user_prop_req_rsp;
1705 	req->cb_arg = ctrlr->qp[0];
1706 	req->req.cmd->prop_set_cmd.opcode = SPDK_NVME_OPC_FABRIC;
1707 	req->req.cmd->prop_set_cmd.cid = 0;
1708 	req->req.cmd->prop_set_cmd.attrib.size = (count / 4) - 1;
1709 	req->req.cmd->prop_set_cmd.ofst = pos;
1710 	if (is_write) {
1711 		req->req.cmd->prop_set_cmd.fctype = SPDK_NVMF_FABRIC_COMMAND_PROPERTY_SET;
1712 		if (req->req.cmd->prop_set_cmd.attrib.size) {
1713 			req->req.cmd->prop_set_cmd.value.u64 = *(uint64_t *)buf;
1714 		} else {
1715 			req->req.cmd->prop_set_cmd.value.u32.high = 0;
1716 			req->req.cmd->prop_set_cmd.value.u32.low = *(uint32_t *)buf;
1717 		}
1718 	} else {
1719 		req->req.cmd->prop_get_cmd.fctype = SPDK_NVMF_FABRIC_COMMAND_PROPERTY_GET;
1720 	}
1721 	req->req.length = count;
1722 	req->req.data = buf;
1723 
1724 	spdk_nvmf_request_exec_fabrics(&req->req);
1725 
1726 	return count;
1727 }
1728 
1729 /*
1730  * NVMe driver reads 4096 bytes, which is the extended PCI configuration space
1731  * available on PCI-X 2.0 and PCI Express buses
1732  */
1733 static ssize_t
1734 access_pci_config(vfu_ctx_t *vfu_ctx, char *buf, size_t count, loff_t offset,
1735 		  bool is_write)
1736 {
1737 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1738 
1739 	if (is_write) {
1740 		SPDK_ERRLOG("%s: write %#lx-%#lx not supported\n",
1741 			    endpoint_id(endpoint), offset, offset + count);
1742 		errno = EINVAL;
1743 		return -1;
1744 	}
1745 
1746 	if (offset + count > PCI_CFG_SPACE_EXP_SIZE) {
1747 		SPDK_ERRLOG("%s: access past end of extended PCI configuration space, want=%ld+%ld, max=%d\n",
1748 			    endpoint_id(endpoint), offset, count,
1749 			    PCI_CFG_SPACE_EXP_SIZE);
1750 		errno = ERANGE;
1751 		return -1;
1752 	}
1753 
1754 	memcpy(buf, ((unsigned char *)endpoint->pci_config_space) + offset, count);
1755 
1756 	return count;
1757 }
1758 
1759 static void
1760 vfio_user_log(vfu_ctx_t *vfu_ctx, int level, char const *msg)
1761 {
1762 	struct nvmf_vfio_user_endpoint *endpoint = vfu_get_private(vfu_ctx);
1763 
1764 	if (level >= LOG_DEBUG) {
1765 		SPDK_DEBUGLOG(nvmf_vfio, "%s: %s\n", endpoint_id(endpoint), msg);
1766 	} else if (level >= LOG_INFO) {
1767 		SPDK_INFOLOG(nvmf_vfio, "%s: %s\n", endpoint_id(endpoint), msg);
1768 	} else if (level >= LOG_NOTICE) {
1769 		SPDK_NOTICELOG("%s: %s\n", endpoint_id(endpoint), msg);
1770 	} else if (level >= LOG_WARNING) {
1771 		SPDK_WARNLOG("%s: %s\n", endpoint_id(endpoint), msg);
1772 	} else {
1773 		SPDK_ERRLOG("%s: %s\n", endpoint_id(endpoint), msg);
1774 	}
1775 }
1776 
1777 static int
1778 vfio_user_get_log_level(void)
1779 {
1780 	int level;
1781 
1782 	if (SPDK_DEBUGLOG_FLAG_ENABLED("nvmf_vfio")) {
1783 		return LOG_DEBUG;
1784 	}
1785 
1786 	level = spdk_log_to_syslog_level(spdk_log_get_level());
1787 	if (level < 0) {
1788 		return LOG_ERR;
1789 	}
1790 
1791 	return level;
1792 }
1793 
1794 static void
1795 init_pci_config_space(vfu_pci_config_space_t *p)
1796 {
1797 	/* MLBAR */
1798 	p->hdr.bars[0].raw = 0x0;
1799 	/* MUBAR */
1800 	p->hdr.bars[1].raw = 0x0;
1801 
1802 	/* vendor specific, let's set them to zero for now */
1803 	p->hdr.bars[3].raw = 0x0;
1804 	p->hdr.bars[4].raw = 0x0;
1805 	p->hdr.bars[5].raw = 0x0;
1806 
1807 	/* enable INTx */
1808 	p->hdr.intr.ipin = 0x1;
1809 }
1810 
1811 static int
1812 vfio_user_dev_info_fill(struct nvmf_vfio_user_transport *vu_transport,
1813 			struct nvmf_vfio_user_endpoint *endpoint)
1814 {
1815 	int ret;
1816 	ssize_t cap_offset;
1817 	vfu_ctx_t *vfu_ctx = endpoint->vfu_ctx;
1818 
1819 	struct pmcap pmcap = { .hdr.id = PCI_CAP_ID_PM, .pmcs.nsfrst = 0x1 };
1820 	struct pxcap pxcap = {
1821 		.hdr.id = PCI_CAP_ID_EXP,
1822 		.pxcaps.ver = 0x2,
1823 		.pxdcap = {.rer = 0x1, .flrc = 0x1},
1824 		.pxdcap2.ctds = 0x1
1825 	};
1826 
1827 	struct msixcap msixcap = {
1828 		.hdr.id = PCI_CAP_ID_MSIX,
1829 		.mxc.ts = NVME_IRQ_MSIX_NUM - 1,
1830 		.mtab = {.tbir = 0x4, .to = 0x0},
1831 		.mpba = {.pbir = 0x5, .pbao = 0x0}
1832 	};
1833 
1834 	static struct iovec sparse_mmap[] = {
1835 		{
1836 			.iov_base = (void *)NVMF_VFIO_USER_DOORBELLS_OFFSET,
1837 			.iov_len = NVMF_VFIO_USER_DOORBELLS_SIZE,
1838 		},
1839 	};
1840 
1841 	ret = vfu_pci_init(vfu_ctx, VFU_PCI_TYPE_EXPRESS, PCI_HEADER_TYPE_NORMAL, 0);
1842 	if (ret < 0) {
1843 		SPDK_ERRLOG("vfu_ctx %p failed to initialize PCI\n", vfu_ctx);
1844 		return ret;
1845 	}
1846 	vfu_pci_set_id(vfu_ctx, 0x4e58, 0x0001, 0, 0);
1847 	/*
1848 	 * 0x02, controller uses the NVM Express programming interface
1849 	 * 0x08, non-volatile memory controller
1850 	 * 0x01, mass storage controller
1851 	 */
1852 	vfu_pci_set_class(vfu_ctx, 0x01, 0x08, 0x02);
1853 
1854 	cap_offset = vfu_pci_add_capability(vfu_ctx, 0, 0, &pmcap);
1855 	if (cap_offset < 0) {
1856 		SPDK_ERRLOG("vfu_ctx %p failed add pmcap\n", vfu_ctx);
1857 		return ret;
1858 	}
1859 
1860 	cap_offset = vfu_pci_add_capability(vfu_ctx, 0, 0, &pxcap);
1861 	if (cap_offset < 0) {
1862 		SPDK_ERRLOG("vfu_ctx %p failed add pxcap\n", vfu_ctx);
1863 		return ret;
1864 	}
1865 
1866 	cap_offset = vfu_pci_add_capability(vfu_ctx, 0, 0, &msixcap);
1867 	if (cap_offset < 0) {
1868 		SPDK_ERRLOG("vfu_ctx %p failed add msixcap\n", vfu_ctx);
1869 		return ret;
1870 	}
1871 
1872 	ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_CFG_REGION_IDX, NVME_REG_CFG_SIZE,
1873 			       access_pci_config, VFU_REGION_FLAG_RW, NULL, 0, -1, 0);
1874 	if (ret < 0) {
1875 		SPDK_ERRLOG("vfu_ctx %p failed to setup cfg\n", vfu_ctx);
1876 		return ret;
1877 	}
1878 
1879 	if (vu_transport->transport_opts.disable_mappable_bar0) {
1880 		ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR0_REGION_IDX, NVME_REG_BAR0_SIZE,
1881 				       access_bar0_fn, VFU_REGION_FLAG_RW | VFU_REGION_FLAG_MEM,
1882 				       NULL, 0, -1, 0);
1883 	} else {
1884 		ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR0_REGION_IDX, NVME_REG_BAR0_SIZE,
1885 				       access_bar0_fn, VFU_REGION_FLAG_RW | VFU_REGION_FLAG_MEM,
1886 				       sparse_mmap, 1, endpoint->devmem_fd, 0);
1887 	}
1888 
1889 	if (ret < 0) {
1890 		SPDK_ERRLOG("vfu_ctx %p failed to setup bar 0\n", vfu_ctx);
1891 		return ret;
1892 	}
1893 
1894 	ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR4_REGION_IDX, PAGE_SIZE,
1895 			       NULL, VFU_REGION_FLAG_RW, NULL, 0, -1, 0);
1896 	if (ret < 0) {
1897 		SPDK_ERRLOG("vfu_ctx %p failed to setup bar 4\n", vfu_ctx);
1898 		return ret;
1899 	}
1900 
1901 	ret = vfu_setup_region(vfu_ctx, VFU_PCI_DEV_BAR5_REGION_IDX, PAGE_SIZE,
1902 			       NULL, VFU_REGION_FLAG_RW, NULL, 0, -1, 0);
1903 	if (ret < 0) {
1904 		SPDK_ERRLOG("vfu_ctx %p failed to setup bar 5\n", vfu_ctx);
1905 		return ret;
1906 	}
1907 
1908 	ret = vfu_setup_device_dma(vfu_ctx, memory_region_add_cb, memory_region_remove_cb);
1909 	if (ret < 0) {
1910 		SPDK_ERRLOG("vfu_ctx %p failed to setup dma callback\n", vfu_ctx);
1911 		return ret;
1912 	}
1913 
1914 	ret = vfu_setup_device_nr_irqs(vfu_ctx, VFU_DEV_INTX_IRQ, 1);
1915 	if (ret < 0) {
1916 		SPDK_ERRLOG("vfu_ctx %p failed to setup INTX\n", vfu_ctx);
1917 		return ret;
1918 	}
1919 
1920 	ret = vfu_setup_device_nr_irqs(vfu_ctx, VFU_DEV_MSIX_IRQ, NVME_IRQ_MSIX_NUM);
1921 	if (ret < 0) {
1922 		SPDK_ERRLOG("vfu_ctx %p failed to setup MSIX\n", vfu_ctx);
1923 		return ret;
1924 	}
1925 
1926 	ret = vfu_realize_ctx(vfu_ctx);
1927 	if (ret < 0) {
1928 		SPDK_ERRLOG("vfu_ctx %p failed to realize\n", vfu_ctx);
1929 		return ret;
1930 	}
1931 
1932 	endpoint->pci_config_space = vfu_pci_get_config_space(endpoint->vfu_ctx);
1933 	assert(endpoint->pci_config_space != NULL);
1934 	init_pci_config_space(endpoint->pci_config_space);
1935 
1936 	assert(cap_offset != 0);
1937 	endpoint->msix = (struct msixcap *)((uint8_t *)endpoint->pci_config_space + cap_offset);
1938 
1939 	return 0;
1940 }
1941 
1942 static void
1943 _free_ctrlr(void *ctx)
1944 {
1945 	struct nvmf_vfio_user_ctrlr *ctrlr = ctx;
1946 
1947 	spdk_poller_unregister(&ctrlr->vfu_ctx_poller);
1948 	free(ctrlr);
1949 }
1950 
1951 static void
1952 free_ctrlr(struct nvmf_vfio_user_ctrlr *ctrlr, bool free_qps)
1953 {
1954 	int i;
1955 	assert(ctrlr != NULL);
1956 
1957 	SPDK_DEBUGLOG(nvmf_vfio, "free %s\n", ctrlr_id(ctrlr));
1958 
1959 	if (free_qps) {
1960 		for (i = 0; i < NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR; i++) {
1961 			free_qp(ctrlr, i);
1962 		}
1963 	}
1964 
1965 	if (ctrlr->thread == spdk_get_thread()) {
1966 		_free_ctrlr(ctrlr);
1967 	} else {
1968 		spdk_thread_send_msg(ctrlr->thread, _free_ctrlr, ctrlr);
1969 	}
1970 }
1971 
1972 static void
1973 nvmf_vfio_user_create_ctrlr(struct nvmf_vfio_user_transport *transport,
1974 			    struct nvmf_vfio_user_endpoint *endpoint)
1975 {
1976 	struct nvmf_vfio_user_ctrlr *ctrlr;
1977 	int err = 0;
1978 
1979 	/* First, construct a vfio-user CUSTOM transport controller */
1980 	ctrlr = calloc(1, sizeof(*ctrlr));
1981 	if (ctrlr == NULL) {
1982 		err = -ENOMEM;
1983 		goto out;
1984 	}
1985 	ctrlr->cntlid = 0xffff;
1986 	ctrlr->transport = transport;
1987 	ctrlr->endpoint = endpoint;
1988 	ctrlr->doorbells = endpoint->doorbells;
1989 	TAILQ_INIT(&ctrlr->connected_qps);
1990 
1991 	/* Then, construct an admin queue pair */
1992 	err = init_qp(ctrlr, &transport->transport, NVMF_VFIO_USER_DEFAULT_AQ_DEPTH, 0);
1993 	if (err != 0) {
1994 		free(ctrlr);
1995 		goto out;
1996 	}
1997 	endpoint->ctrlr = ctrlr;
1998 
1999 	/* Notify the generic layer about the new admin queue pair */
2000 	spdk_nvmf_tgt_new_qpair(transport->transport.tgt, &ctrlr->qp[0]->qpair);
2001 
2002 out:
2003 	if (err != 0) {
2004 		SPDK_ERRLOG("%s: failed to create vfio-user controller: %s\n",
2005 			    endpoint_id(endpoint), strerror(-err));
2006 	}
2007 }
2008 
2009 static int
2010 nvmf_vfio_user_listen(struct spdk_nvmf_transport *transport,
2011 		      const struct spdk_nvme_transport_id *trid,
2012 		      struct spdk_nvmf_listen_opts *listen_opts)
2013 {
2014 	struct nvmf_vfio_user_transport *vu_transport;
2015 	struct nvmf_vfio_user_endpoint *endpoint, *tmp;
2016 	char *path = NULL;
2017 	char uuid[PATH_MAX] = {};
2018 	int fd;
2019 	int err;
2020 
2021 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport,
2022 					transport);
2023 
2024 	TAILQ_FOREACH_SAFE(endpoint, &vu_transport->endpoints, link, tmp) {
2025 		/* Only compare traddr */
2026 		if (strncmp(endpoint->trid.traddr, trid->traddr, sizeof(endpoint->trid.traddr)) == 0) {
2027 			return -EEXIST;
2028 		}
2029 	}
2030 
2031 	endpoint = calloc(1, sizeof(*endpoint));
2032 	if (!endpoint) {
2033 		return -ENOMEM;
2034 	}
2035 
2036 	endpoint->devmem_fd = -1;
2037 	memcpy(&endpoint->trid, trid, sizeof(endpoint->trid));
2038 
2039 	err = asprintf(&path, "%s/bar0", endpoint_id(endpoint));
2040 	if (err == -1) {
2041 		goto out;
2042 	}
2043 
2044 	fd = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
2045 	if (fd == -1) {
2046 		SPDK_ERRLOG("%s: failed to open device memory at %s: %m\n",
2047 			    endpoint_id(endpoint), path);
2048 		err = fd;
2049 		free(path);
2050 		goto out;
2051 	}
2052 	free(path);
2053 
2054 	endpoint->devmem_fd = fd;
2055 	err = ftruncate(fd, NVMF_VFIO_USER_DOORBELLS_OFFSET + NVMF_VFIO_USER_DOORBELLS_SIZE);
2056 	if (err != 0) {
2057 		goto out;
2058 	}
2059 
2060 	endpoint->doorbells = mmap(NULL, NVMF_VFIO_USER_DOORBELLS_SIZE,
2061 				   PROT_READ | PROT_WRITE, MAP_SHARED, fd, NVMF_VFIO_USER_DOORBELLS_OFFSET);
2062 	if (endpoint->doorbells == MAP_FAILED) {
2063 		endpoint->doorbells = NULL;
2064 		err = -errno;
2065 		goto out;
2066 	}
2067 
2068 	snprintf(uuid, PATH_MAX, "%s/cntrl", endpoint_id(endpoint));
2069 
2070 	endpoint->vfu_ctx = vfu_create_ctx(VFU_TRANS_SOCK, uuid, LIBVFIO_USER_FLAG_ATTACH_NB,
2071 					   endpoint, VFU_DEV_TYPE_PCI);
2072 	if (endpoint->vfu_ctx == NULL) {
2073 		SPDK_ERRLOG("%s: error creating libmuser context: %m\n",
2074 			    endpoint_id(endpoint));
2075 		err = -1;
2076 		goto out;
2077 	}
2078 	vfu_setup_log(endpoint->vfu_ctx, vfio_user_log, vfio_user_get_log_level());
2079 
2080 	err = vfio_user_dev_info_fill(vu_transport, endpoint);
2081 	if (err < 0) {
2082 		goto out;
2083 	}
2084 
2085 	pthread_mutex_init(&endpoint->lock, NULL);
2086 	TAILQ_INSERT_TAIL(&vu_transport->endpoints, endpoint, link);
2087 	SPDK_DEBUGLOG(nvmf_vfio, "%s: doorbells %p\n", uuid, endpoint->doorbells);
2088 
2089 out:
2090 	if (err != 0) {
2091 		nvmf_vfio_user_destroy_endpoint(endpoint);
2092 	}
2093 
2094 	return err;
2095 }
2096 
2097 static void
2098 nvmf_vfio_user_stop_listen(struct spdk_nvmf_transport *transport,
2099 			   const struct spdk_nvme_transport_id *trid)
2100 {
2101 	struct nvmf_vfio_user_transport *vu_transport;
2102 	struct nvmf_vfio_user_endpoint *endpoint, *tmp;
2103 
2104 	assert(trid != NULL);
2105 	assert(trid->traddr != NULL);
2106 
2107 	SPDK_DEBUGLOG(nvmf_vfio, "%s: stop listen\n", trid->traddr);
2108 
2109 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport,
2110 					transport);
2111 
2112 	pthread_mutex_lock(&vu_transport->lock);
2113 	TAILQ_FOREACH_SAFE(endpoint, &vu_transport->endpoints, link, tmp) {
2114 		if (strcmp(trid->traddr, endpoint->trid.traddr) == 0) {
2115 			TAILQ_REMOVE(&vu_transport->endpoints, endpoint, link);
2116 			if (endpoint->ctrlr) {
2117 				/* Users may kill NVMeoF target while VM
2118 				 * is connected, free all resources.
2119 				 */
2120 				free_ctrlr(endpoint->ctrlr, true);
2121 			}
2122 			nvmf_vfio_user_destroy_endpoint(endpoint);
2123 			pthread_mutex_unlock(&vu_transport->lock);
2124 
2125 			return;
2126 		}
2127 	}
2128 	pthread_mutex_unlock(&vu_transport->lock);
2129 
2130 	SPDK_DEBUGLOG(nvmf_vfio, "%s: not found\n", trid->traddr);
2131 }
2132 
2133 static void
2134 nvmf_vfio_user_cdata_init(struct spdk_nvmf_transport *transport,
2135 			  struct spdk_nvmf_subsystem *subsystem,
2136 			  struct spdk_nvmf_ctrlr_data *cdata)
2137 {
2138 	memset(&cdata->sgls, 0, sizeof(struct spdk_nvme_cdata_sgls));
2139 	cdata->sgls.supported = SPDK_NVME_SGLS_SUPPORTED_DWORD_ALIGNED;
2140 	/* libvfio-user can only support 1 connection for now */
2141 	cdata->oncs.reservations = 0;
2142 }
2143 
2144 static int
2145 nvmf_vfio_user_listen_associate(struct spdk_nvmf_transport *transport,
2146 				const struct spdk_nvmf_subsystem *subsystem,
2147 				const struct spdk_nvme_transport_id *trid)
2148 {
2149 	struct nvmf_vfio_user_transport *vu_transport;
2150 	struct nvmf_vfio_user_endpoint *endpoint;
2151 
2152 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport, transport);
2153 
2154 	TAILQ_FOREACH(endpoint, &vu_transport->endpoints, link) {
2155 		if (strncmp(endpoint->trid.traddr, trid->traddr, sizeof(endpoint->trid.traddr)) == 0) {
2156 			break;
2157 		}
2158 	}
2159 
2160 	if (endpoint == NULL) {
2161 		return -ENOENT;
2162 	}
2163 
2164 	endpoint->subsystem = subsystem;
2165 
2166 	return 0;
2167 }
2168 
2169 /*
2170  * Executed periodically at a default SPDK_NVMF_DEFAULT_ACCEPT_POLL_RATE_US
2171  * frequency.
2172  *
2173  * For each transport endpoint (which at the libvfio-user level corresponds to
2174  * a socket), if we don't currently have a controller set up, peek to see if the
2175  * socket is able to accept a new connection.
2176  *
2177  * This poller also takes care of handling the creation of any pending new
2178  * qpairs.
2179  *
2180  * Returns the number of events handled.
2181  */
2182 static uint32_t
2183 nvmf_vfio_user_accept(struct spdk_nvmf_transport *transport)
2184 {
2185 	struct nvmf_vfio_user_transport *vu_transport;
2186 	struct nvmf_vfio_user_endpoint *endpoint;
2187 	uint32_t count = 0;
2188 	int err;
2189 
2190 	vu_transport = SPDK_CONTAINEROF(transport, struct nvmf_vfio_user_transport,
2191 					transport);
2192 
2193 	pthread_mutex_lock(&vu_transport->lock);
2194 
2195 	TAILQ_FOREACH(endpoint, &vu_transport->endpoints, link) {
2196 		if (endpoint->ctrlr != NULL) {
2197 			continue;
2198 		}
2199 
2200 		err = vfu_attach_ctx(endpoint->vfu_ctx);
2201 		if (err != 0) {
2202 			if (errno == EAGAIN || errno == EWOULDBLOCK) {
2203 				continue;
2204 			}
2205 
2206 			pthread_mutex_unlock(&vu_transport->lock);
2207 			return 1;
2208 		}
2209 
2210 		count++;
2211 
2212 		/* Construct a controller */
2213 		nvmf_vfio_user_create_ctrlr(vu_transport, endpoint);
2214 	}
2215 
2216 	pthread_mutex_unlock(&vu_transport->lock);
2217 
2218 	return count;
2219 }
2220 
2221 static void
2222 nvmf_vfio_user_discover(struct spdk_nvmf_transport *transport,
2223 			struct spdk_nvme_transport_id *trid,
2224 			struct spdk_nvmf_discovery_log_page_entry *entry)
2225 { }
2226 
2227 static struct spdk_nvmf_transport_poll_group *
2228 nvmf_vfio_user_poll_group_create(struct spdk_nvmf_transport *transport)
2229 {
2230 	struct nvmf_vfio_user_poll_group *vu_group;
2231 
2232 	SPDK_DEBUGLOG(nvmf_vfio, "create poll group\n");
2233 
2234 	vu_group = calloc(1, sizeof(*vu_group));
2235 	if (vu_group == NULL) {
2236 		SPDK_ERRLOG("Error allocating poll group: %m");
2237 		return NULL;
2238 	}
2239 
2240 	TAILQ_INIT(&vu_group->qps);
2241 
2242 	return &vu_group->group;
2243 }
2244 
2245 /* called when process exits */
2246 static void
2247 nvmf_vfio_user_poll_group_destroy(struct spdk_nvmf_transport_poll_group *group)
2248 {
2249 	struct nvmf_vfio_user_poll_group *vu_group;
2250 
2251 	SPDK_DEBUGLOG(nvmf_vfio, "destroy poll group\n");
2252 
2253 	vu_group = SPDK_CONTAINEROF(group, struct nvmf_vfio_user_poll_group, group);
2254 
2255 	free(vu_group);
2256 }
2257 
2258 static void
2259 vfio_user_qpair_disconnect_cb(void *ctx)
2260 {
2261 	struct nvmf_vfio_user_endpoint *endpoint = ctx;
2262 	struct nvmf_vfio_user_ctrlr *ctrlr;
2263 
2264 	pthread_mutex_lock(&endpoint->lock);
2265 	ctrlr = endpoint->ctrlr;
2266 	if (!ctrlr) {
2267 		pthread_mutex_unlock(&endpoint->lock);
2268 		return;
2269 	}
2270 
2271 	if (TAILQ_EMPTY(&ctrlr->connected_qps)) {
2272 		endpoint->ctrlr = NULL;
2273 		free_ctrlr(ctrlr, false);
2274 		pthread_mutex_unlock(&endpoint->lock);
2275 		return;
2276 	}
2277 	pthread_mutex_unlock(&endpoint->lock);
2278 }
2279 
2280 static int
2281 vfio_user_destroy_ctrlr(struct nvmf_vfio_user_ctrlr *ctrlr)
2282 {
2283 	struct nvmf_vfio_user_qpair *qpair;
2284 	struct nvmf_vfio_user_endpoint *endpoint;
2285 
2286 	SPDK_DEBUGLOG(nvmf_vfio, "%s stop processing\n", ctrlr_id(ctrlr));
2287 
2288 	endpoint = ctrlr->endpoint;
2289 	assert(endpoint != NULL);
2290 
2291 	pthread_mutex_lock(&endpoint->lock);
2292 	if (TAILQ_EMPTY(&ctrlr->connected_qps)) {
2293 		endpoint->ctrlr = NULL;
2294 		free_ctrlr(ctrlr, false);
2295 		pthread_mutex_unlock(&endpoint->lock);
2296 		return 0;
2297 	}
2298 
2299 	TAILQ_FOREACH(qpair, &ctrlr->connected_qps, tailq) {
2300 		spdk_nvmf_qpair_disconnect(&qpair->qpair, vfio_user_qpair_disconnect_cb, endpoint);
2301 	}
2302 	pthread_mutex_unlock(&endpoint->lock);
2303 
2304 	return 0;
2305 }
2306 
2307 /*
2308  * Poll for and process any incoming vfio-user messages.
2309  */
2310 static int
2311 vfio_user_poll_vfu_ctx(void *ctx)
2312 {
2313 	struct nvmf_vfio_user_ctrlr *ctrlr = ctx;
2314 	int ret;
2315 
2316 	assert(ctrlr != NULL);
2317 
2318 	/* This will call access_bar0_fn() if there are any writes
2319 	 * to the portion of the BAR that is not mmap'd */
2320 	ret = vfu_run_ctx(ctrlr->endpoint->vfu_ctx);
2321 	if (spdk_unlikely(ret == -1)) {
2322 		spdk_poller_unregister(&ctrlr->vfu_ctx_poller);
2323 
2324 		/* initiator shutdown or reset, waiting for another re-connect */
2325 		if (errno == ENOTCONN) {
2326 			vfio_user_destroy_ctrlr(ctrlr);
2327 			return SPDK_POLLER_BUSY;
2328 		}
2329 
2330 		fail_ctrlr(ctrlr);
2331 	}
2332 
2333 	return ret != 0 ? SPDK_POLLER_BUSY : SPDK_POLLER_IDLE;
2334 }
2335 
2336 static int
2337 handle_queue_connect_rsp(struct nvmf_vfio_user_req *req, void *cb_arg)
2338 {
2339 	struct nvmf_vfio_user_poll_group *vu_group;
2340 	struct nvmf_vfio_user_qpair *qpair = cb_arg;
2341 	struct nvmf_vfio_user_ctrlr *ctrlr;
2342 	struct nvmf_vfio_user_endpoint *endpoint;
2343 
2344 	assert(qpair != NULL);
2345 	assert(req != NULL);
2346 
2347 	ctrlr = qpair->ctrlr;
2348 	endpoint = ctrlr->endpoint;
2349 	assert(ctrlr != NULL);
2350 	assert(endpoint != NULL);
2351 
2352 	if (spdk_nvme_cpl_is_error(&req->req.rsp->nvme_cpl)) {
2353 		SPDK_ERRLOG("SC %u, SCT %u\n", req->req.rsp->nvme_cpl.status.sc, req->req.rsp->nvme_cpl.status.sct);
2354 		endpoint->ctrlr = NULL;
2355 		free_ctrlr(ctrlr, true);
2356 		return -1;
2357 	}
2358 
2359 	vu_group = SPDK_CONTAINEROF(qpair->group, struct nvmf_vfio_user_poll_group, group);
2360 	TAILQ_INSERT_TAIL(&vu_group->qps, qpair, link);
2361 	qpair->state = VFIO_USER_QPAIR_ACTIVE;
2362 
2363 	pthread_mutex_lock(&endpoint->lock);
2364 	if (nvmf_qpair_is_admin_queue(&qpair->qpair)) {
2365 		ctrlr->cntlid = qpair->qpair.ctrlr->cntlid;
2366 		ctrlr->thread = spdk_get_thread();
2367 		ctrlr->vfu_ctx_poller = SPDK_POLLER_REGISTER(vfio_user_poll_vfu_ctx, ctrlr, 0);
2368 	} else {
2369 		/* For I/O queues this command was generated in response to an
2370 		 * ADMIN I/O CREATE SUBMISSION QUEUE command which has not yet
2371 		 * been completed. Complete it now.
2372 		 */
2373 		post_completion(ctrlr, &ctrlr->qp[0]->cq, 0, 0,
2374 				qpair->create_io_sq_cmd.cid, SPDK_NVME_SC_SUCCESS, SPDK_NVME_SCT_GENERIC);
2375 	}
2376 	TAILQ_INSERT_TAIL(&ctrlr->connected_qps, qpair, tailq);
2377 	pthread_mutex_unlock(&endpoint->lock);
2378 
2379 	free(req->req.data);
2380 	req->req.data = NULL;
2381 
2382 	return 0;
2383 }
2384 
2385 /*
2386  * Add the given qpair to the given poll group. New qpairs are added via
2387  * spdk_nvmf_tgt_new_qpair(), which picks a poll group, then calls back
2388  * here via nvmf_transport_poll_group_add().
2389  */
2390 static int
2391 nvmf_vfio_user_poll_group_add(struct spdk_nvmf_transport_poll_group *group,
2392 			      struct spdk_nvmf_qpair *qpair)
2393 {
2394 	struct nvmf_vfio_user_qpair *vu_qpair;
2395 	struct nvmf_vfio_user_req *vu_req;
2396 	struct nvmf_vfio_user_ctrlr *ctrlr;
2397 	struct spdk_nvmf_request *req;
2398 	struct spdk_nvmf_fabric_connect_data *data;
2399 	bool admin;
2400 
2401 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2402 	vu_qpair->group = group;
2403 	ctrlr = vu_qpair->ctrlr;
2404 
2405 	SPDK_DEBUGLOG(nvmf_vfio, "%s: add QP%d=%p(%p) to poll_group=%p\n",
2406 		      ctrlr_id(ctrlr), vu_qpair->qpair.qid,
2407 		      vu_qpair, qpair, group);
2408 
2409 	admin = nvmf_qpair_is_admin_queue(&vu_qpair->qpair);
2410 
2411 	vu_req = get_nvmf_vfio_user_req(vu_qpair);
2412 	if (vu_req == NULL) {
2413 		return -1;
2414 	}
2415 
2416 	req = &vu_req->req;
2417 	req->cmd->connect_cmd.opcode = SPDK_NVME_OPC_FABRIC;
2418 	req->cmd->connect_cmd.cid = 0;
2419 	req->cmd->connect_cmd.fctype = SPDK_NVMF_FABRIC_COMMAND_CONNECT;
2420 	req->cmd->connect_cmd.recfmt = 0;
2421 	req->cmd->connect_cmd.sqsize = vu_qpair->qsize - 1;
2422 	req->cmd->connect_cmd.qid = admin ? 0 : qpair->qid;
2423 
2424 	req->length = sizeof(struct spdk_nvmf_fabric_connect_data);
2425 	req->data = calloc(1, req->length);
2426 	if (req->data == NULL) {
2427 		nvmf_vfio_user_req_free(req);
2428 		return -ENOMEM;
2429 	}
2430 
2431 	data = (struct spdk_nvmf_fabric_connect_data *)req->data;
2432 	data->cntlid = admin ? 0xFFFF : ctrlr->cntlid;
2433 	snprintf(data->subnqn, sizeof(data->subnqn), "%s",
2434 		 spdk_nvmf_subsystem_get_nqn(ctrlr->endpoint->subsystem));
2435 
2436 	vu_req->cb_fn = handle_queue_connect_rsp;
2437 	vu_req->cb_arg = vu_qpair;
2438 
2439 	SPDK_DEBUGLOG(nvmf_vfio,
2440 		      "%s: sending connect fabrics command for QID=%#x cntlid=%#x\n",
2441 		      ctrlr_id(ctrlr), qpair->qid, data->cntlid);
2442 
2443 	spdk_nvmf_request_exec_fabrics(req);
2444 	return 0;
2445 }
2446 
2447 static int
2448 nvmf_vfio_user_poll_group_remove(struct spdk_nvmf_transport_poll_group *group,
2449 				 struct spdk_nvmf_qpair *qpair)
2450 {
2451 	struct nvmf_vfio_user_qpair *vu_qpair;
2452 	struct nvmf_vfio_user_ctrlr *vu_ctrlr;
2453 	struct nvmf_vfio_user_endpoint *endpoint;
2454 	struct nvmf_vfio_user_poll_group *vu_group;
2455 
2456 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2457 	vu_ctrlr = vu_qpair->ctrlr;
2458 	endpoint = vu_ctrlr->endpoint;
2459 
2460 	SPDK_DEBUGLOG(nvmf_vfio,
2461 		      "%s: remove NVMf QP%d=%p from NVMf poll_group=%p\n",
2462 		      ctrlr_id(vu_qpair->ctrlr), qpair->qid, qpair, group);
2463 
2464 
2465 	vu_group = SPDK_CONTAINEROF(group, struct nvmf_vfio_user_poll_group, group);
2466 	TAILQ_REMOVE(&vu_group->qps, vu_qpair, link);
2467 
2468 	pthread_mutex_lock(&endpoint->lock);
2469 	TAILQ_REMOVE(&vu_ctrlr->connected_qps, vu_qpair, tailq);
2470 	pthread_mutex_unlock(&endpoint->lock);
2471 
2472 	return 0;
2473 }
2474 
2475 static void
2476 _nvmf_vfio_user_req_free(struct nvmf_vfio_user_qpair *vu_qpair, struct nvmf_vfio_user_req *vu_req)
2477 {
2478 	memset(&vu_req->cmd, 0, sizeof(vu_req->cmd));
2479 	memset(&vu_req->rsp, 0, sizeof(vu_req->rsp));
2480 	vu_req->iovcnt = 0;
2481 	vu_req->state = VFIO_USER_REQUEST_STATE_FREE;
2482 
2483 	TAILQ_INSERT_TAIL(&vu_qpair->reqs, vu_req, link);
2484 }
2485 
2486 static int
2487 nvmf_vfio_user_req_free(struct spdk_nvmf_request *req)
2488 {
2489 	struct nvmf_vfio_user_qpair *vu_qpair;
2490 	struct nvmf_vfio_user_req *vu_req;
2491 
2492 	assert(req != NULL);
2493 
2494 	vu_req = SPDK_CONTAINEROF(req, struct nvmf_vfio_user_req, req);
2495 	vu_qpair = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2496 
2497 	_nvmf_vfio_user_req_free(vu_qpair, vu_req);
2498 
2499 	return 0;
2500 }
2501 
2502 static int
2503 nvmf_vfio_user_req_complete(struct spdk_nvmf_request *req)
2504 {
2505 	struct nvmf_vfio_user_qpair *vu_qpair;
2506 	struct nvmf_vfio_user_req *vu_req;
2507 
2508 	assert(req != NULL);
2509 
2510 	vu_req = SPDK_CONTAINEROF(req, struct nvmf_vfio_user_req, req);
2511 	vu_qpair = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2512 
2513 	if (vu_req->cb_fn != NULL) {
2514 		if (vu_req->cb_fn(vu_req, vu_req->cb_arg) != 0) {
2515 			fail_ctrlr(vu_qpair->ctrlr);
2516 		}
2517 	}
2518 
2519 	_nvmf_vfio_user_req_free(vu_qpair, vu_req);
2520 
2521 	return 0;
2522 }
2523 
2524 static void
2525 nvmf_vfio_user_close_qpair(struct spdk_nvmf_qpair *qpair,
2526 			   spdk_nvmf_transport_qpair_fini_cb cb_fn, void *cb_arg)
2527 {
2528 	struct nvmf_vfio_user_qpair *vu_qpair;
2529 
2530 	assert(qpair != NULL);
2531 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2532 	free_qp(vu_qpair->ctrlr, qpair->qid);
2533 
2534 	if (cb_fn) {
2535 		cb_fn(cb_arg);
2536 	}
2537 }
2538 
2539 /**
2540  * Returns a preallocated spdk_nvmf_request or NULL if there isn't one available.
2541  */
2542 static struct nvmf_vfio_user_req *
2543 get_nvmf_vfio_user_req(struct nvmf_vfio_user_qpair *qpair)
2544 {
2545 	struct nvmf_vfio_user_req *req;
2546 
2547 	assert(qpair != NULL);
2548 
2549 	if (TAILQ_EMPTY(&qpair->reqs)) {
2550 		return NULL;
2551 	}
2552 
2553 	req = TAILQ_FIRST(&qpair->reqs);
2554 	TAILQ_REMOVE(&qpair->reqs, req, link);
2555 
2556 	return req;
2557 }
2558 
2559 static struct spdk_nvmf_request *
2560 get_nvmf_req(struct nvmf_vfio_user_qpair *qpair)
2561 {
2562 	struct nvmf_vfio_user_req *req = get_nvmf_vfio_user_req(qpair);
2563 
2564 	if (req == NULL) {
2565 		return NULL;
2566 	}
2567 	return &req->req;
2568 }
2569 
2570 static int
2571 get_nvmf_io_req_length(struct spdk_nvmf_request *req)
2572 {
2573 	uint16_t nlb, nr;
2574 	uint32_t nsid;
2575 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2576 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2577 	struct spdk_nvmf_ns *ns;
2578 
2579 	nsid = cmd->nsid;
2580 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
2581 	if (ns == NULL || ns->bdev == NULL) {
2582 		SPDK_ERRLOG("unsuccessful query for nsid %u\n", cmd->nsid);
2583 		return -EINVAL;
2584 	}
2585 
2586 	if (cmd->opc == SPDK_NVME_OPC_DATASET_MANAGEMENT) {
2587 		nr = cmd->cdw10_bits.dsm.nr + 1;
2588 		return nr * sizeof(struct spdk_nvme_dsm_range);
2589 	}
2590 
2591 	nlb = (cmd->cdw12 & 0x0000ffffu) + 1;
2592 	return nlb * spdk_bdev_get_block_size(ns->bdev);
2593 }
2594 
2595 static int
2596 map_admin_cmd_req(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvmf_request *req)
2597 {
2598 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2599 	uint32_t len = 0;
2600 	int iovcnt;
2601 
2602 	req->xfer = spdk_nvme_opc_get_data_transfer(cmd->opc);
2603 	req->length = 0;
2604 	req->data = NULL;
2605 
2606 	if (req->xfer == SPDK_NVME_DATA_NONE) {
2607 		return 0;
2608 	}
2609 
2610 	switch (cmd->opc) {
2611 	case SPDK_NVME_OPC_IDENTIFY:
2612 		len = 4096;
2613 		break;
2614 	case SPDK_NVME_OPC_GET_LOG_PAGE:
2615 		len = (((cmd->cdw11_bits.get_log_page.numdu << 16) | cmd->cdw10_bits.get_log_page.numdl) + 1) * 4;
2616 		break;
2617 	default:
2618 		/*
2619 		 * CREATE IO SQ/CQ are processed separately in handle_create_io_q().
2620 		 * GET/SET FEATURES: no need to support Host Identifier for vfio-user transport.
2621 		 * Let the NVMf library to decide other commands.
2622 		 */
2623 		return 0;
2624 	}
2625 
2626 	/* ADMIN command will not use SGL */
2627 	if (req->cmd->nvme_cmd.psdt != 0) {
2628 		return -EINVAL;
2629 	}
2630 
2631 	iovcnt = vfio_user_map_cmd(ctrlr, req, req->iov, len);
2632 	if (iovcnt < 0) {
2633 		SPDK_ERRLOG("%s: map Admin Opc %x failed\n",
2634 			    ctrlr_id(ctrlr), cmd->opc);
2635 		return -1;
2636 	}
2637 	req->length = len;
2638 	req->data = req->iov[0].iov_base;
2639 	req->iovcnt = iovcnt;
2640 
2641 	return 0;
2642 }
2643 
2644 /*
2645  * Map an I/O command's buffers.
2646  *
2647  * Returns 0 on success and -errno on failure.
2648  */
2649 static int
2650 map_io_cmd_req(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvmf_request *req)
2651 {
2652 	int len, iovcnt;
2653 	struct spdk_nvme_cmd *cmd;
2654 
2655 	assert(ctrlr != NULL);
2656 	assert(req != NULL);
2657 
2658 	cmd = &req->cmd->nvme_cmd;
2659 	req->xfer = spdk_nvme_opc_get_data_transfer(cmd->opc);
2660 	req->length = 0;
2661 	req->data = NULL;
2662 
2663 	if (spdk_unlikely(req->xfer == SPDK_NVME_DATA_NONE)) {
2664 		return 0;
2665 	}
2666 
2667 	len = get_nvmf_io_req_length(req);
2668 	if (len < 0) {
2669 		return -EINVAL;
2670 	}
2671 	req->length = len;
2672 
2673 	iovcnt = vfio_user_map_cmd(ctrlr, req, req->iov, req->length);
2674 	if (iovcnt < 0) {
2675 		SPDK_ERRLOG("%s: failed to map IO OPC %u\n", ctrlr_id(ctrlr), cmd->opc);
2676 		return -EFAULT;
2677 	}
2678 	req->data = req->iov[0].iov_base;
2679 	req->iovcnt = iovcnt;
2680 
2681 	return 0;
2682 }
2683 
2684 static int
2685 handle_cmd_req(struct nvmf_vfio_user_ctrlr *ctrlr, struct spdk_nvme_cmd *cmd,
2686 	       struct spdk_nvmf_request *req)
2687 {
2688 	int err;
2689 	struct nvmf_vfio_user_req *vu_req;
2690 
2691 	assert(ctrlr != NULL);
2692 	assert(cmd != NULL);
2693 
2694 	/*
2695 	 * TODO: this means that there are no free requests available,
2696 	 * returning -1 will fail the controller. Theoretically this error can
2697 	 * be avoided completely by ensuring we have as many requests as slots
2698 	 * in the SQ, plus one for the the property request.
2699 	 */
2700 	if (spdk_unlikely(req == NULL)) {
2701 		return -1;
2702 	}
2703 
2704 	assert(req->qpair != NULL);
2705 	SPDK_DEBUGLOG(nvmf_vfio, "%s: handle qid%u, req opc=%#x cid=%d\n",
2706 		      ctrlr_id(ctrlr), req->qpair->qid, cmd->opc, cmd->cid);
2707 
2708 	vu_req = SPDK_CONTAINEROF(req, struct nvmf_vfio_user_req, req);
2709 	vu_req->cb_fn = handle_cmd_rsp;
2710 	vu_req->cb_arg = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2711 	req->cmd->nvme_cmd = *cmd;
2712 
2713 	if (nvmf_qpair_is_admin_queue(req->qpair)) {
2714 		err = map_admin_cmd_req(ctrlr, req);
2715 	} else {
2716 		switch (cmd->opc) {
2717 		case SPDK_NVME_OPC_RESERVATION_REGISTER:
2718 		case SPDK_NVME_OPC_RESERVATION_REPORT:
2719 		case SPDK_NVME_OPC_RESERVATION_ACQUIRE:
2720 		case SPDK_NVME_OPC_RESERVATION_RELEASE:
2721 			err = -ENOTSUP;
2722 			break;
2723 		default:
2724 			err = map_io_cmd_req(ctrlr, req);
2725 			break;
2726 		}
2727 	}
2728 
2729 	if (spdk_unlikely(err < 0)) {
2730 		struct nvmf_vfio_user_qpair *vu_qpair;
2731 
2732 		SPDK_ERRLOG("%s: process NVMe command opc 0x%x failed\n",
2733 			    ctrlr_id(ctrlr), cmd->opc);
2734 		req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
2735 		req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
2736 		err = handle_cmd_rsp(vu_req, vu_req->cb_arg);
2737 		vu_qpair = SPDK_CONTAINEROF(req->qpair, struct nvmf_vfio_user_qpair, qpair);
2738 		_nvmf_vfio_user_req_free(vu_qpair, vu_req);
2739 		return err;
2740 	}
2741 
2742 	vu_req->state = VFIO_USER_REQUEST_STATE_EXECUTING;
2743 	spdk_nvmf_request_exec(req);
2744 
2745 	return 0;
2746 }
2747 
2748 /* Returns the number of commands processed, or a negative value on error. */
2749 static int
2750 nvmf_vfio_user_qpair_poll(struct nvmf_vfio_user_qpair *qpair)
2751 {
2752 	struct nvmf_vfio_user_ctrlr *ctrlr;
2753 	uint32_t new_tail;
2754 	int count = 0;
2755 
2756 	assert(qpair != NULL);
2757 
2758 	ctrlr = qpair->ctrlr;
2759 
2760 	/* Load-Acquire. */
2761 	new_tail = *tdbl(ctrlr, &qpair->sq);
2762 
2763 	/*
2764 	 * Ensure that changes to the queue are visible to us.
2765 	 * The host driver should write the queue first, do a wmb(), and then
2766 	 * update the SQ tail doorbell (their Store-Release).
2767 	 */
2768 	spdk_rmb();
2769 
2770 	if (sq_head(qpair) == new_tail) {
2771 		return 0;
2772 	}
2773 
2774 	count = handle_sq_tdbl_write(ctrlr, new_tail, qpair);
2775 	if (count < 0) {
2776 		fail_ctrlr(ctrlr);
2777 	}
2778 
2779 	return count;
2780 }
2781 
2782 /*
2783  * vfio-user transport poll handler. Note that the library context is polled in
2784  * a separate poller (->vfu_ctx_poller), so this poller only needs to poll the
2785  * active qpairs.
2786  *
2787  * Returns the number of commands processed, or a negative value on error.
2788  */
2789 static int
2790 nvmf_vfio_user_poll_group_poll(struct spdk_nvmf_transport_poll_group *group)
2791 {
2792 	struct nvmf_vfio_user_poll_group *vu_group;
2793 	struct nvmf_vfio_user_qpair *vu_qpair, *tmp;
2794 	int count = 0;
2795 
2796 	assert(group != NULL);
2797 
2798 	spdk_rmb();
2799 
2800 	vu_group = SPDK_CONTAINEROF(group, struct nvmf_vfio_user_poll_group, group);
2801 
2802 	TAILQ_FOREACH_SAFE(vu_qpair, &vu_group->qps, link, tmp) {
2803 		int ret;
2804 
2805 		if (spdk_unlikely(vu_qpair->state != VFIO_USER_QPAIR_ACTIVE || !vu_qpair->sq.size)) {
2806 			continue;
2807 		}
2808 
2809 		ret = nvmf_vfio_user_qpair_poll(vu_qpair);
2810 
2811 		if (ret < 0) {
2812 			return ret;
2813 		}
2814 
2815 		count += ret;
2816 	}
2817 
2818 	return count;
2819 }
2820 
2821 static int
2822 nvmf_vfio_user_qpair_get_local_trid(struct spdk_nvmf_qpair *qpair,
2823 				    struct spdk_nvme_transport_id *trid)
2824 {
2825 	struct nvmf_vfio_user_qpair *vu_qpair;
2826 	struct nvmf_vfio_user_ctrlr *ctrlr;
2827 
2828 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2829 	ctrlr = vu_qpair->ctrlr;
2830 
2831 	memcpy(trid, &ctrlr->endpoint->trid, sizeof(*trid));
2832 	return 0;
2833 }
2834 
2835 static int
2836 nvmf_vfio_user_qpair_get_peer_trid(struct spdk_nvmf_qpair *qpair,
2837 				   struct spdk_nvme_transport_id *trid)
2838 {
2839 	return 0;
2840 }
2841 
2842 static int
2843 nvmf_vfio_user_qpair_get_listen_trid(struct spdk_nvmf_qpair *qpair,
2844 				     struct spdk_nvme_transport_id *trid)
2845 {
2846 	struct nvmf_vfio_user_qpair *vu_qpair;
2847 	struct nvmf_vfio_user_ctrlr *ctrlr;
2848 
2849 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2850 	ctrlr = vu_qpair->ctrlr;
2851 
2852 	memcpy(trid, &ctrlr->endpoint->trid, sizeof(*trid));
2853 	return 0;
2854 }
2855 
2856 static void
2857 nvmf_vfio_user_qpair_abort_request(struct spdk_nvmf_qpair *qpair,
2858 				   struct spdk_nvmf_request *req)
2859 {
2860 	struct nvmf_vfio_user_qpair *vu_qpair;
2861 	struct nvmf_vfio_user_req *vu_req, *vu_req_to_abort = NULL;
2862 	uint16_t i, cid;
2863 
2864 	vu_qpair = SPDK_CONTAINEROF(qpair, struct nvmf_vfio_user_qpair, qpair);
2865 
2866 	cid = req->cmd->nvme_cmd.cdw10_bits.abort.cid;
2867 	for (i = 0; i < vu_qpair->qsize; i++) {
2868 		vu_req = &vu_qpair->reqs_internal[i];
2869 		if (vu_req->state == VFIO_USER_REQUEST_STATE_EXECUTING && vu_req->cmd.cid == cid) {
2870 			vu_req_to_abort = vu_req;
2871 			break;
2872 		}
2873 	}
2874 
2875 	if (vu_req_to_abort == NULL) {
2876 		spdk_nvmf_request_complete(req);
2877 		return;
2878 	}
2879 
2880 	req->req_to_abort = &vu_req_to_abort->req;
2881 	nvmf_ctrlr_abort_request(req);
2882 }
2883 
2884 static void
2885 nvmf_vfio_user_opts_init(struct spdk_nvmf_transport_opts *opts)
2886 {
2887 	opts->max_queue_depth =		NVMF_VFIO_USER_DEFAULT_MAX_QUEUE_DEPTH;
2888 	opts->max_qpairs_per_ctrlr =	NVMF_VFIO_USER_DEFAULT_MAX_QPAIRS_PER_CTRLR;
2889 	opts->in_capsule_data_size =	0;
2890 	opts->max_io_size =		NVMF_VFIO_USER_DEFAULT_MAX_IO_SIZE;
2891 	opts->io_unit_size =		NVMF_VFIO_USER_DEFAULT_IO_UNIT_SIZE;
2892 	opts->max_aq_depth =		NVMF_VFIO_USER_DEFAULT_AQ_DEPTH;
2893 	opts->num_shared_buffers =	0;
2894 	opts->buf_cache_size =		0;
2895 	opts->association_timeout =	0;
2896 	opts->transport_specific =      NULL;
2897 }
2898 
2899 const struct spdk_nvmf_transport_ops spdk_nvmf_transport_vfio_user = {
2900 	.name = "VFIOUSER",
2901 	.type = SPDK_NVME_TRANSPORT_VFIOUSER,
2902 	.opts_init = nvmf_vfio_user_opts_init,
2903 	.create = nvmf_vfio_user_create,
2904 	.destroy = nvmf_vfio_user_destroy,
2905 
2906 	.listen = nvmf_vfio_user_listen,
2907 	.stop_listen = nvmf_vfio_user_stop_listen,
2908 	.accept = nvmf_vfio_user_accept,
2909 	.cdata_init = nvmf_vfio_user_cdata_init,
2910 	.listen_associate = nvmf_vfio_user_listen_associate,
2911 
2912 	.listener_discover = nvmf_vfio_user_discover,
2913 
2914 	.poll_group_create = nvmf_vfio_user_poll_group_create,
2915 	.poll_group_destroy = nvmf_vfio_user_poll_group_destroy,
2916 	.poll_group_add = nvmf_vfio_user_poll_group_add,
2917 	.poll_group_remove = nvmf_vfio_user_poll_group_remove,
2918 	.poll_group_poll = nvmf_vfio_user_poll_group_poll,
2919 
2920 	.req_free = nvmf_vfio_user_req_free,
2921 	.req_complete = nvmf_vfio_user_req_complete,
2922 
2923 	.qpair_fini = nvmf_vfio_user_close_qpair,
2924 	.qpair_get_local_trid = nvmf_vfio_user_qpair_get_local_trid,
2925 	.qpair_get_peer_trid = nvmf_vfio_user_qpair_get_peer_trid,
2926 	.qpair_get_listen_trid = nvmf_vfio_user_qpair_get_listen_trid,
2927 	.qpair_abort_request = nvmf_vfio_user_qpair_abort_request,
2928 };
2929 
2930 SPDK_NVMF_TRANSPORT_REGISTER(muser, &spdk_nvmf_transport_vfio_user);
2931 SPDK_LOG_REGISTER_COMPONENT(nvmf_vfio)
2932