xref: /spdk/lib/nvme/nvme_pcie_common.c (revision 16b33d51e806dbc8365202ba80673b7afb64666a)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (C) 2021 Intel Corporation. All rights reserved.
3  *   Copyright (c) 2021 Mellanox Technologies LTD. All rights reserved.
4  *   Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
5  */
6 
7 /*
8  * NVMe over PCIe common library
9  */
10 
11 #include "spdk/stdinc.h"
12 #include "spdk/likely.h"
13 #include "spdk/string.h"
14 #include "nvme_internal.h"
15 #include "nvme_pcie_internal.h"
16 #include "spdk/trace.h"
17 
18 #include "spdk_internal/trace_defs.h"
19 
20 __thread struct nvme_pcie_ctrlr *g_thread_mmio_ctrlr = NULL;
21 
22 static struct spdk_nvme_pcie_stat g_dummy_stat = {};
23 
24 static void nvme_pcie_fail_request_bad_vtophys(struct spdk_nvme_qpair *qpair,
25 		struct nvme_tracker *tr);
26 
27 static inline uint64_t
28 nvme_pcie_vtophys(struct spdk_nvme_ctrlr *ctrlr, const void *buf, uint64_t *size)
29 {
30 	if (spdk_likely(ctrlr->trid.trtype == SPDK_NVME_TRANSPORT_PCIE)) {
31 		return spdk_vtophys(buf, size);
32 	} else {
33 		/* vfio-user address translation with IOVA=VA mode */
34 		return (uint64_t)(uintptr_t)buf;
35 	}
36 }
37 
38 int
39 nvme_pcie_qpair_reset(struct spdk_nvme_qpair *qpair)
40 {
41 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
42 	uint32_t i;
43 
44 	/* all head/tail vals are set to 0 */
45 	pqpair->last_sq_tail = pqpair->sq_tail = pqpair->sq_head = pqpair->cq_head = 0;
46 
47 	/*
48 	 * First time through the completion queue, HW will set phase
49 	 *  bit on completions to 1.  So set this to 1 here, indicating
50 	 *  we're looking for a 1 to know which entries have completed.
51 	 *  we'll toggle the bit each time when the completion queue
52 	 *  rolls over.
53 	 */
54 	pqpair->flags.phase = 1;
55 	for (i = 0; i < pqpair->num_entries; i++) {
56 		pqpair->cpl[i].status.p = 0;
57 	}
58 
59 	return 0;
60 }
61 
62 static void
63 nvme_qpair_construct_tracker(struct nvme_tracker *tr, uint16_t cid, uint64_t phys_addr)
64 {
65 	tr->prp_sgl_bus_addr = phys_addr + offsetof(struct nvme_tracker, u.prp);
66 	tr->cid = cid;
67 	tr->req = NULL;
68 }
69 
70 static void *
71 nvme_pcie_ctrlr_alloc_cmb(struct spdk_nvme_ctrlr *ctrlr, uint64_t size, uint64_t alignment,
72 			  uint64_t *phys_addr)
73 {
74 	struct nvme_pcie_ctrlr *pctrlr = nvme_pcie_ctrlr(ctrlr);
75 	uintptr_t addr;
76 
77 	if (pctrlr->cmb.mem_register_addr != NULL) {
78 		/* BAR is mapped for data */
79 		return NULL;
80 	}
81 
82 	addr = (uintptr_t)pctrlr->cmb.bar_va + pctrlr->cmb.current_offset;
83 	addr = (addr + (alignment - 1)) & ~(alignment - 1);
84 
85 	/* CMB may only consume part of the BAR, calculate accordingly */
86 	if (addr + size > ((uintptr_t)pctrlr->cmb.bar_va + pctrlr->cmb.size)) {
87 		SPDK_ERRLOG("Tried to allocate past valid CMB range!\n");
88 		return NULL;
89 	}
90 	*phys_addr = pctrlr->cmb.bar_pa + addr - (uintptr_t)pctrlr->cmb.bar_va;
91 
92 	pctrlr->cmb.current_offset = (addr + size) - (uintptr_t)pctrlr->cmb.bar_va;
93 
94 	return (void *)addr;
95 }
96 
97 int
98 nvme_pcie_qpair_construct(struct spdk_nvme_qpair *qpair,
99 			  const struct spdk_nvme_io_qpair_opts *opts)
100 {
101 	struct spdk_nvme_ctrlr	*ctrlr = qpair->ctrlr;
102 	struct nvme_pcie_ctrlr	*pctrlr = nvme_pcie_ctrlr(ctrlr);
103 	struct nvme_pcie_qpair	*pqpair = nvme_pcie_qpair(qpair);
104 	struct nvme_tracker	*tr;
105 	uint16_t		i;
106 	uint16_t		num_trackers;
107 	size_t			page_align = sysconf(_SC_PAGESIZE);
108 	size_t			queue_align, queue_len;
109 	uint32_t                flags = SPDK_MALLOC_DMA;
110 	uint64_t		sq_paddr = 0;
111 	uint64_t		cq_paddr = 0;
112 
113 	if (opts) {
114 		pqpair->sq_vaddr = opts->sq.vaddr;
115 		pqpair->cq_vaddr = opts->cq.vaddr;
116 		sq_paddr = opts->sq.paddr;
117 		cq_paddr = opts->cq.paddr;
118 	}
119 
120 	pqpair->retry_count = ctrlr->opts.transport_retry_count;
121 
122 	/*
123 	 * Limit the maximum number of completions to return per call to prevent wraparound,
124 	 * and calculate how many trackers can be submitted at once without overflowing the
125 	 * completion queue.
126 	 */
127 	pqpair->max_completions_cap = pqpair->num_entries / 4;
128 	pqpair->max_completions_cap = spdk_max(pqpair->max_completions_cap, NVME_MIN_COMPLETIONS);
129 	pqpair->max_completions_cap = spdk_min(pqpair->max_completions_cap, NVME_MAX_COMPLETIONS);
130 	num_trackers = pqpair->num_entries - pqpair->max_completions_cap;
131 
132 	SPDK_INFOLOG(nvme, "max_completions_cap = %" PRIu16 " num_trackers = %" PRIu16 "\n",
133 		     pqpair->max_completions_cap, num_trackers);
134 
135 	assert(num_trackers != 0);
136 
137 	pqpair->sq_in_cmb = false;
138 
139 	if (nvme_qpair_is_admin_queue(&pqpair->qpair)) {
140 		flags |= SPDK_MALLOC_SHARE;
141 	}
142 
143 	/* cmd and cpl rings must be aligned on page size boundaries. */
144 	if (ctrlr->opts.use_cmb_sqs) {
145 		pqpair->cmd = nvme_pcie_ctrlr_alloc_cmb(ctrlr, pqpair->num_entries * sizeof(struct spdk_nvme_cmd),
146 							page_align, &pqpair->cmd_bus_addr);
147 		if (pqpair->cmd != NULL) {
148 			pqpair->sq_in_cmb = true;
149 		}
150 	}
151 
152 	if (pqpair->sq_in_cmb == false) {
153 		if (pqpair->sq_vaddr) {
154 			pqpair->cmd = pqpair->sq_vaddr;
155 		} else {
156 			/* To ensure physical address contiguity we make each ring occupy
157 			 * a single hugepage only. See MAX_IO_QUEUE_ENTRIES.
158 			 */
159 			queue_len = pqpair->num_entries * sizeof(struct spdk_nvme_cmd);
160 			queue_align = spdk_max(spdk_align32pow2(queue_len), page_align);
161 			pqpair->cmd = spdk_zmalloc(queue_len, queue_align, NULL, SPDK_ENV_SOCKET_ID_ANY, flags);
162 			if (pqpair->cmd == NULL) {
163 				SPDK_ERRLOG("alloc qpair_cmd failed\n");
164 				return -ENOMEM;
165 			}
166 		}
167 		if (sq_paddr) {
168 			assert(pqpair->sq_vaddr != NULL);
169 			pqpair->cmd_bus_addr = sq_paddr;
170 		} else {
171 			pqpair->cmd_bus_addr = nvme_pcie_vtophys(ctrlr, pqpair->cmd, NULL);
172 			if (pqpair->cmd_bus_addr == SPDK_VTOPHYS_ERROR) {
173 				SPDK_ERRLOG("spdk_vtophys(pqpair->cmd) failed\n");
174 				return -EFAULT;
175 			}
176 		}
177 	}
178 
179 	if (pqpair->cq_vaddr) {
180 		pqpair->cpl = pqpair->cq_vaddr;
181 	} else {
182 		queue_len = pqpair->num_entries * sizeof(struct spdk_nvme_cpl);
183 		queue_align = spdk_max(spdk_align32pow2(queue_len), page_align);
184 		pqpair->cpl = spdk_zmalloc(queue_len, queue_align, NULL, SPDK_ENV_SOCKET_ID_ANY, flags);
185 		if (pqpair->cpl == NULL) {
186 			SPDK_ERRLOG("alloc qpair_cpl failed\n");
187 			return -ENOMEM;
188 		}
189 	}
190 	if (cq_paddr) {
191 		assert(pqpair->cq_vaddr != NULL);
192 		pqpair->cpl_bus_addr = cq_paddr;
193 	} else {
194 		pqpair->cpl_bus_addr =  nvme_pcie_vtophys(ctrlr, pqpair->cpl, NULL);
195 		if (pqpair->cpl_bus_addr == SPDK_VTOPHYS_ERROR) {
196 			SPDK_ERRLOG("spdk_vtophys(pqpair->cpl) failed\n");
197 			return -EFAULT;
198 		}
199 	}
200 
201 	pqpair->sq_tdbl = pctrlr->doorbell_base + (2 * qpair->id + 0) * pctrlr->doorbell_stride_u32;
202 	pqpair->cq_hdbl = pctrlr->doorbell_base + (2 * qpair->id + 1) * pctrlr->doorbell_stride_u32;
203 
204 	/*
205 	 * Reserve space for all of the trackers in a single allocation.
206 	 *   struct nvme_tracker must be padded so that its size is already a power of 2.
207 	 *   This ensures the PRP list embedded in the nvme_tracker object will not span a
208 	 *   4KB boundary, while allowing access to trackers in tr[] via normal array indexing.
209 	 */
210 	pqpair->tr = spdk_zmalloc(num_trackers * sizeof(*tr), sizeof(*tr), NULL,
211 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_SHARE);
212 	if (pqpair->tr == NULL) {
213 		SPDK_ERRLOG("nvme_tr failed\n");
214 		return -ENOMEM;
215 	}
216 
217 	TAILQ_INIT(&pqpair->free_tr);
218 	TAILQ_INIT(&pqpair->outstanding_tr);
219 	pqpair->qpair.queue_depth = 0;
220 
221 	for (i = 0; i < num_trackers; i++) {
222 		tr = &pqpair->tr[i];
223 		nvme_qpair_construct_tracker(tr, i, nvme_pcie_vtophys(ctrlr, tr, NULL));
224 		TAILQ_INSERT_HEAD(&pqpair->free_tr, tr, tq_list);
225 	}
226 
227 	nvme_pcie_qpair_reset(qpair);
228 
229 	return 0;
230 }
231 
232 int
233 nvme_pcie_ctrlr_construct_admin_qpair(struct spdk_nvme_ctrlr *ctrlr, uint16_t num_entries)
234 {
235 	struct nvme_pcie_qpair *pqpair;
236 	int rc;
237 
238 	pqpair = spdk_zmalloc(sizeof(*pqpair), 64, NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_SHARE);
239 	if (pqpair == NULL) {
240 		return -ENOMEM;
241 	}
242 
243 	pqpair->num_entries = num_entries;
244 	pqpair->flags.delay_cmd_submit = 0;
245 	pqpair->pcie_state = NVME_PCIE_QPAIR_READY;
246 
247 	ctrlr->adminq = &pqpair->qpair;
248 
249 	rc = nvme_qpair_init(ctrlr->adminq,
250 			     0, /* qpair ID */
251 			     ctrlr,
252 			     SPDK_NVME_QPRIO_URGENT,
253 			     num_entries,
254 			     false);
255 	if (rc != 0) {
256 		return rc;
257 	}
258 
259 	pqpair->stat = spdk_zmalloc(sizeof(*pqpair->stat), 64, NULL, SPDK_ENV_SOCKET_ID_ANY,
260 				    SPDK_MALLOC_SHARE);
261 	if (!pqpair->stat) {
262 		SPDK_ERRLOG("Failed to allocate admin qpair statistics\n");
263 		return -ENOMEM;
264 	}
265 
266 	return nvme_pcie_qpair_construct(ctrlr->adminq, NULL);
267 }
268 
269 /**
270  * Note: the ctrlr_lock must be held when calling this function.
271  */
272 void
273 nvme_pcie_qpair_insert_pending_admin_request(struct spdk_nvme_qpair *qpair,
274 		struct nvme_request *req, struct spdk_nvme_cpl *cpl)
275 {
276 	struct spdk_nvme_ctrlr		*ctrlr = qpair->ctrlr;
277 	struct nvme_request		*active_req = req;
278 	struct spdk_nvme_ctrlr_process	*active_proc;
279 
280 	/*
281 	 * The admin request is from another process. Move to the per
282 	 *  process list for that process to handle it later.
283 	 */
284 	assert(nvme_qpair_is_admin_queue(qpair));
285 	assert(active_req->pid != getpid());
286 
287 	active_proc = nvme_ctrlr_get_process(ctrlr, active_req->pid);
288 	if (active_proc) {
289 		/* Save the original completion information */
290 		memcpy(&active_req->cpl, cpl, sizeof(*cpl));
291 		STAILQ_INSERT_TAIL(&active_proc->active_reqs, active_req, stailq);
292 	} else {
293 		SPDK_ERRLOG("The owning process (pid %d) is not found. Dropping the request.\n",
294 			    active_req->pid);
295 		nvme_cleanup_user_req(active_req);
296 		nvme_free_request(active_req);
297 	}
298 }
299 
300 /**
301  * Note: the ctrlr_lock must be held when calling this function.
302  */
303 void
304 nvme_pcie_qpair_complete_pending_admin_request(struct spdk_nvme_qpair *qpair)
305 {
306 	struct spdk_nvme_ctrlr		*ctrlr = qpair->ctrlr;
307 	struct nvme_request		*req, *tmp_req;
308 	pid_t				pid = getpid();
309 	struct spdk_nvme_ctrlr_process	*proc;
310 
311 	/*
312 	 * Check whether there is any pending admin request from
313 	 * other active processes.
314 	 */
315 	assert(nvme_qpair_is_admin_queue(qpair));
316 
317 	proc = nvme_ctrlr_get_current_process(ctrlr);
318 	if (!proc) {
319 		SPDK_ERRLOG("the active process (pid %d) is not found for this controller.\n", pid);
320 		assert(proc);
321 		return;
322 	}
323 
324 	STAILQ_FOREACH_SAFE(req, &proc->active_reqs, stailq, tmp_req) {
325 		STAILQ_REMOVE(&proc->active_reqs, req, nvme_request, stailq);
326 
327 		assert(req->pid == pid);
328 
329 		nvme_complete_request(req->cb_fn, req->cb_arg, qpair, req, &req->cpl);
330 	}
331 }
332 
333 int
334 nvme_pcie_ctrlr_cmd_create_io_cq(struct spdk_nvme_ctrlr *ctrlr,
335 				 struct spdk_nvme_qpair *io_que, spdk_nvme_cmd_cb cb_fn,
336 				 void *cb_arg)
337 {
338 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(io_que);
339 	struct nvme_request *req;
340 	struct spdk_nvme_cmd *cmd;
341 
342 	req = nvme_allocate_request_null(ctrlr->adminq, cb_fn, cb_arg);
343 	if (req == NULL) {
344 		return -ENOMEM;
345 	}
346 
347 	cmd = &req->cmd;
348 	cmd->opc = SPDK_NVME_OPC_CREATE_IO_CQ;
349 
350 	cmd->cdw10_bits.create_io_q.qid = io_que->id;
351 	cmd->cdw10_bits.create_io_q.qsize = pqpair->num_entries - 1;
352 
353 	cmd->cdw11_bits.create_io_cq.pc = 1;
354 	cmd->dptr.prp.prp1 = pqpair->cpl_bus_addr;
355 
356 	return nvme_ctrlr_submit_admin_request(ctrlr, req);
357 }
358 
359 int
360 nvme_pcie_ctrlr_cmd_create_io_sq(struct spdk_nvme_ctrlr *ctrlr,
361 				 struct spdk_nvme_qpair *io_que, spdk_nvme_cmd_cb cb_fn, void *cb_arg)
362 {
363 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(io_que);
364 	struct nvme_request *req;
365 	struct spdk_nvme_cmd *cmd;
366 
367 	req = nvme_allocate_request_null(ctrlr->adminq, cb_fn, cb_arg);
368 	if (req == NULL) {
369 		return -ENOMEM;
370 	}
371 
372 	cmd = &req->cmd;
373 	cmd->opc = SPDK_NVME_OPC_CREATE_IO_SQ;
374 
375 	cmd->cdw10_bits.create_io_q.qid = io_que->id;
376 	cmd->cdw10_bits.create_io_q.qsize = pqpair->num_entries - 1;
377 	cmd->cdw11_bits.create_io_sq.pc = 1;
378 	cmd->cdw11_bits.create_io_sq.qprio = io_que->qprio;
379 	cmd->cdw11_bits.create_io_sq.cqid = io_que->id;
380 	cmd->dptr.prp.prp1 = pqpair->cmd_bus_addr;
381 
382 	return nvme_ctrlr_submit_admin_request(ctrlr, req);
383 }
384 
385 int
386 nvme_pcie_ctrlr_cmd_delete_io_cq(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_qpair *qpair,
387 				 spdk_nvme_cmd_cb cb_fn, void *cb_arg)
388 {
389 	struct nvme_request *req;
390 	struct spdk_nvme_cmd *cmd;
391 
392 	req = nvme_allocate_request_null(ctrlr->adminq, cb_fn, cb_arg);
393 	if (req == NULL) {
394 		return -ENOMEM;
395 	}
396 
397 	cmd = &req->cmd;
398 	cmd->opc = SPDK_NVME_OPC_DELETE_IO_CQ;
399 	cmd->cdw10_bits.delete_io_q.qid = qpair->id;
400 
401 	return nvme_ctrlr_submit_admin_request(ctrlr, req);
402 }
403 
404 int
405 nvme_pcie_ctrlr_cmd_delete_io_sq(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_qpair *qpair,
406 				 spdk_nvme_cmd_cb cb_fn, void *cb_arg)
407 {
408 	struct nvme_request *req;
409 	struct spdk_nvme_cmd *cmd;
410 
411 	req = nvme_allocate_request_null(ctrlr->adminq, cb_fn, cb_arg);
412 	if (req == NULL) {
413 		return -ENOMEM;
414 	}
415 
416 	cmd = &req->cmd;
417 	cmd->opc = SPDK_NVME_OPC_DELETE_IO_SQ;
418 	cmd->cdw10_bits.delete_io_q.qid = qpair->id;
419 
420 	return nvme_ctrlr_submit_admin_request(ctrlr, req);
421 }
422 
423 static void
424 nvme_completion_sq_error_delete_cq_cb(void *arg, const struct spdk_nvme_cpl *cpl)
425 {
426 	struct spdk_nvme_qpair *qpair = arg;
427 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
428 
429 	if (spdk_nvme_cpl_is_error(cpl)) {
430 		SPDK_ERRLOG("delete_io_cq failed!\n");
431 	}
432 
433 	pqpair->pcie_state = NVME_PCIE_QPAIR_FAILED;
434 }
435 
436 static void
437 nvme_completion_create_sq_cb(void *arg, const struct spdk_nvme_cpl *cpl)
438 {
439 	struct spdk_nvme_qpair *qpair = arg;
440 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
441 	struct spdk_nvme_ctrlr	*ctrlr = qpair->ctrlr;
442 	struct nvme_pcie_ctrlr	*pctrlr = nvme_pcie_ctrlr(ctrlr);
443 	int rc;
444 
445 	if (pqpair->flags.defer_destruction) {
446 		/* This qpair was deleted by the application while the
447 		 * connection was still in progress.  We had to wait
448 		 * to free the qpair resources until this outstanding
449 		 * command was completed.  Now that we have the completion
450 		 * free it now.
451 		 */
452 		nvme_pcie_qpair_destroy(qpair);
453 		return;
454 	}
455 
456 	if (spdk_nvme_cpl_is_error(cpl)) {
457 		SPDK_ERRLOG("nvme_create_io_sq failed, deleting cq!\n");
458 		rc = nvme_pcie_ctrlr_cmd_delete_io_cq(qpair->ctrlr, qpair, nvme_completion_sq_error_delete_cq_cb,
459 						      qpair);
460 		if (rc != 0) {
461 			SPDK_ERRLOG("Failed to send request to delete_io_cq with rc=%d\n", rc);
462 			pqpair->pcie_state = NVME_PCIE_QPAIR_FAILED;
463 		}
464 		return;
465 	}
466 	pqpair->pcie_state = NVME_PCIE_QPAIR_READY;
467 	if (ctrlr->shadow_doorbell) {
468 		pqpair->shadow_doorbell.sq_tdbl = ctrlr->shadow_doorbell + (2 * qpair->id + 0) *
469 						  pctrlr->doorbell_stride_u32;
470 		pqpair->shadow_doorbell.cq_hdbl = ctrlr->shadow_doorbell + (2 * qpair->id + 1) *
471 						  pctrlr->doorbell_stride_u32;
472 		pqpair->shadow_doorbell.sq_eventidx = ctrlr->eventidx + (2 * qpair->id + 0) *
473 						      pctrlr->doorbell_stride_u32;
474 		pqpair->shadow_doorbell.cq_eventidx = ctrlr->eventidx + (2 * qpair->id + 1) *
475 						      pctrlr->doorbell_stride_u32;
476 		pqpair->flags.has_shadow_doorbell = 1;
477 	} else {
478 		pqpair->flags.has_shadow_doorbell = 0;
479 	}
480 	nvme_pcie_qpair_reset(qpair);
481 
482 }
483 
484 static void
485 nvme_completion_create_cq_cb(void *arg, const struct spdk_nvme_cpl *cpl)
486 {
487 	struct spdk_nvme_qpair *qpair = arg;
488 	struct nvme_pcie_qpair	*pqpair = nvme_pcie_qpair(qpair);
489 	int rc;
490 
491 	if (pqpair->flags.defer_destruction) {
492 		/* This qpair was deleted by the application while the
493 		 * connection was still in progress.  We had to wait
494 		 * to free the qpair resources until this outstanding
495 		 * command was completed.  Now that we have the completion
496 		 * free it now.
497 		 */
498 		nvme_pcie_qpair_destroy(qpair);
499 		return;
500 	}
501 
502 	if (spdk_nvme_cpl_is_error(cpl)) {
503 		pqpair->pcie_state = NVME_PCIE_QPAIR_FAILED;
504 		SPDK_ERRLOG("nvme_create_io_cq failed!\n");
505 		return;
506 	}
507 
508 	rc = nvme_pcie_ctrlr_cmd_create_io_sq(qpair->ctrlr, qpair, nvme_completion_create_sq_cb, qpair);
509 
510 	if (rc != 0) {
511 		SPDK_ERRLOG("Failed to send request to create_io_sq, deleting cq!\n");
512 		rc = nvme_pcie_ctrlr_cmd_delete_io_cq(qpair->ctrlr, qpair, nvme_completion_sq_error_delete_cq_cb,
513 						      qpair);
514 		if (rc != 0) {
515 			SPDK_ERRLOG("Failed to send request to delete_io_cq with rc=%d\n", rc);
516 			pqpair->pcie_state = NVME_PCIE_QPAIR_FAILED;
517 		}
518 		return;
519 	}
520 	pqpair->pcie_state = NVME_PCIE_QPAIR_WAIT_FOR_SQ;
521 }
522 
523 static int
524 _nvme_pcie_ctrlr_create_io_qpair(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_qpair *qpair,
525 				 uint16_t qid)
526 {
527 	struct nvme_pcie_qpair	*pqpair = nvme_pcie_qpair(qpair);
528 	int	rc;
529 
530 	/* Statistics may already be allocated in the case of controller reset */
531 	if (qpair->poll_group) {
532 		struct nvme_pcie_poll_group *group = SPDK_CONTAINEROF(qpair->poll_group,
533 						     struct nvme_pcie_poll_group, group);
534 
535 		pqpair->stat = &group->stats;
536 		pqpair->shared_stats = true;
537 	} else {
538 		if (pqpair->stat == NULL) {
539 			pqpair->stat = calloc(1, sizeof(*pqpair->stat));
540 			if (!pqpair->stat) {
541 				SPDK_ERRLOG("Failed to allocate qpair statistics\n");
542 				nvme_qpair_set_state(qpair, NVME_QPAIR_DISCONNECTED);
543 				return -ENOMEM;
544 			}
545 		}
546 	}
547 
548 	rc = nvme_pcie_ctrlr_cmd_create_io_cq(ctrlr, qpair, nvme_completion_create_cq_cb, qpair);
549 
550 	if (rc != 0) {
551 		SPDK_ERRLOG("Failed to send request to create_io_cq\n");
552 		nvme_qpair_set_state(qpair, NVME_QPAIR_DISCONNECTED);
553 		return rc;
554 	}
555 	pqpair->pcie_state = NVME_PCIE_QPAIR_WAIT_FOR_CQ;
556 	return 0;
557 }
558 
559 int
560 nvme_pcie_ctrlr_connect_qpair(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_qpair *qpair)
561 {
562 	int rc = 0;
563 
564 	if (!nvme_qpair_is_admin_queue(qpair)) {
565 		rc = _nvme_pcie_ctrlr_create_io_qpair(ctrlr, qpair, qpair->id);
566 	} else {
567 		nvme_qpair_set_state(qpair, NVME_QPAIR_CONNECTED);
568 	}
569 
570 	return rc;
571 }
572 
573 void
574 nvme_pcie_ctrlr_disconnect_qpair(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_qpair *qpair)
575 {
576 	if (!nvme_qpair_is_admin_queue(qpair) || !ctrlr->is_disconnecting) {
577 		nvme_transport_ctrlr_disconnect_qpair_done(qpair);
578 	} else {
579 		/* If this function is called for the admin qpair via spdk_nvme_ctrlr_reset()
580 		 * or spdk_nvme_ctrlr_disconnect(), initiate a Controller Level Reset.
581 		 * Then we can abort trackers safely because the Controller Level Reset deletes
582 		 * all I/O SQ/CQs.
583 		 */
584 		nvme_ctrlr_disable(ctrlr);
585 	}
586 }
587 
588 /* Used when dst points to MMIO (i.e. CMB) in a virtual machine - in these cases we must
589  * not use wide instructions because QEMU will not emulate such instructions to MMIO space.
590  * So this function ensures we only copy 8 bytes at a time.
591  */
592 static inline void
593 nvme_pcie_copy_command_mmio(struct spdk_nvme_cmd *dst, const struct spdk_nvme_cmd *src)
594 {
595 	uint64_t *dst64 = (uint64_t *)dst;
596 	const uint64_t *src64 = (const uint64_t *)src;
597 	uint32_t i;
598 
599 	for (i = 0; i < sizeof(*dst) / 8; i++) {
600 		dst64[i] = src64[i];
601 	}
602 }
603 
604 static inline void
605 nvme_pcie_copy_command(struct spdk_nvme_cmd *dst, const struct spdk_nvme_cmd *src)
606 {
607 	/* dst and src are known to be non-overlapping and 64-byte aligned. */
608 #if defined(__SSE2__)
609 	__m128i *d128 = (__m128i *)dst;
610 	const __m128i *s128 = (const __m128i *)src;
611 
612 	_mm_stream_si128(&d128[0], _mm_load_si128(&s128[0]));
613 	_mm_stream_si128(&d128[1], _mm_load_si128(&s128[1]));
614 	_mm_stream_si128(&d128[2], _mm_load_si128(&s128[2]));
615 	_mm_stream_si128(&d128[3], _mm_load_si128(&s128[3]));
616 #else
617 	*dst = *src;
618 #endif
619 }
620 
621 void
622 nvme_pcie_qpair_submit_tracker(struct spdk_nvme_qpair *qpair, struct nvme_tracker *tr)
623 {
624 	struct nvme_request	*req;
625 	struct nvme_pcie_qpair	*pqpair = nvme_pcie_qpair(qpair);
626 	struct spdk_nvme_ctrlr	*ctrlr = qpair->ctrlr;
627 
628 	req = tr->req;
629 	assert(req != NULL);
630 
631 	spdk_trace_record(TRACE_NVME_PCIE_SUBMIT, qpair->id, 0, (uintptr_t)req, req->cb_arg,
632 			  (uint32_t)req->cmd.cid, (uint32_t)req->cmd.opc,
633 			  req->cmd.cdw10, req->cmd.cdw11, req->cmd.cdw12,
634 			  pqpair->qpair.queue_depth);
635 
636 	if (req->cmd.fuse) {
637 		/*
638 		 * Keep track of the fuse operation sequence so that we ring the doorbell only
639 		 * after the second fuse is submitted.
640 		 */
641 		qpair->last_fuse = req->cmd.fuse;
642 	}
643 
644 	/* Don't use wide instructions to copy NVMe command, this is limited by QEMU
645 	 * virtual NVMe controller, the maximum access width is 8 Bytes for one time.
646 	 */
647 	if (spdk_unlikely((ctrlr->quirks & NVME_QUIRK_MAXIMUM_PCI_ACCESS_WIDTH) && pqpair->sq_in_cmb)) {
648 		nvme_pcie_copy_command_mmio(&pqpair->cmd[pqpair->sq_tail], &req->cmd);
649 	} else {
650 		/* Copy the command from the tracker to the submission queue. */
651 		nvme_pcie_copy_command(&pqpair->cmd[pqpair->sq_tail], &req->cmd);
652 	}
653 
654 	if (spdk_unlikely(++pqpair->sq_tail == pqpair->num_entries)) {
655 		pqpair->sq_tail = 0;
656 	}
657 
658 	if (spdk_unlikely(pqpair->sq_tail == pqpair->sq_head)) {
659 		SPDK_ERRLOG("sq_tail is passing sq_head!\n");
660 	}
661 
662 	if (!pqpair->flags.delay_cmd_submit) {
663 		nvme_pcie_qpair_ring_sq_doorbell(qpair);
664 	}
665 }
666 
667 void
668 nvme_pcie_qpair_complete_tracker(struct spdk_nvme_qpair *qpair, struct nvme_tracker *tr,
669 				 struct spdk_nvme_cpl *cpl, bool print_on_error)
670 {
671 	struct nvme_pcie_qpair		*pqpair = nvme_pcie_qpair(qpair);
672 	struct nvme_request		*req;
673 	bool				retry, error;
674 	bool				print_error;
675 
676 	req = tr->req;
677 
678 	spdk_trace_record(TRACE_NVME_PCIE_COMPLETE, qpair->id, 0, (uintptr_t)req, req->cb_arg,
679 			  (uint32_t)req->cmd.cid, (uint32_t)cpl->status_raw, pqpair->qpair.queue_depth);
680 
681 	assert(req != NULL);
682 
683 	error = spdk_nvme_cpl_is_error(cpl);
684 	retry = error && nvme_completion_is_retry(cpl) &&
685 		req->retries < pqpair->retry_count;
686 	print_error = error && print_on_error && !qpair->ctrlr->opts.disable_error_logging;
687 
688 	if (print_error) {
689 		spdk_nvme_qpair_print_command(qpair, &req->cmd);
690 	}
691 
692 	if (print_error || SPDK_DEBUGLOG_FLAG_ENABLED("nvme")) {
693 		spdk_nvme_qpair_print_completion(qpair, cpl);
694 	}
695 
696 	assert(cpl->cid == req->cmd.cid);
697 
698 	if (retry) {
699 		req->retries++;
700 		nvme_pcie_qpair_submit_tracker(qpair, tr);
701 	} else {
702 		TAILQ_REMOVE(&pqpair->outstanding_tr, tr, tq_list);
703 		pqpair->qpair.queue_depth--;
704 
705 		/* Only check admin requests from different processes. */
706 		if (nvme_qpair_is_admin_queue(qpair) && req->pid != getpid()) {
707 			nvme_pcie_qpair_insert_pending_admin_request(qpair, req, cpl);
708 		} else {
709 			nvme_complete_request(tr->cb_fn, tr->cb_arg, qpair, req, cpl);
710 		}
711 
712 		tr->req = NULL;
713 
714 		TAILQ_INSERT_HEAD(&pqpair->free_tr, tr, tq_list);
715 	}
716 }
717 
718 void
719 nvme_pcie_qpair_manual_complete_tracker(struct spdk_nvme_qpair *qpair,
720 					struct nvme_tracker *tr, uint32_t sct, uint32_t sc, uint32_t dnr,
721 					bool print_on_error)
722 {
723 	struct spdk_nvme_cpl	cpl;
724 
725 	memset(&cpl, 0, sizeof(cpl));
726 	cpl.sqid = qpair->id;
727 	cpl.cid = tr->cid;
728 	cpl.status.sct = sct;
729 	cpl.status.sc = sc;
730 	cpl.status.dnr = dnr;
731 	nvme_pcie_qpair_complete_tracker(qpair, tr, &cpl, print_on_error);
732 }
733 
734 void
735 nvme_pcie_qpair_abort_trackers(struct spdk_nvme_qpair *qpair, uint32_t dnr)
736 {
737 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
738 	struct nvme_tracker *tr, *temp, *last;
739 
740 	last = TAILQ_LAST(&pqpair->outstanding_tr, nvme_outstanding_tr_head);
741 
742 	/* Abort previously submitted (outstanding) trs */
743 	TAILQ_FOREACH_SAFE(tr, &pqpair->outstanding_tr, tq_list, temp) {
744 		if (!qpair->ctrlr->opts.disable_error_logging) {
745 			SPDK_ERRLOG("aborting outstanding command\n");
746 		}
747 		nvme_pcie_qpair_manual_complete_tracker(qpair, tr, SPDK_NVME_SCT_GENERIC,
748 							SPDK_NVME_SC_ABORTED_BY_REQUEST, dnr, true);
749 
750 		if (tr == last) {
751 			break;
752 		}
753 	}
754 }
755 
756 void
757 nvme_pcie_admin_qpair_abort_aers(struct spdk_nvme_qpair *qpair)
758 {
759 	struct nvme_pcie_qpair	*pqpair = nvme_pcie_qpair(qpair);
760 	struct nvme_tracker	*tr;
761 
762 	tr = TAILQ_FIRST(&pqpair->outstanding_tr);
763 	while (tr != NULL) {
764 		assert(tr->req != NULL);
765 		if (tr->req->cmd.opc == SPDK_NVME_OPC_ASYNC_EVENT_REQUEST) {
766 			nvme_pcie_qpair_manual_complete_tracker(qpair, tr,
767 								SPDK_NVME_SCT_GENERIC, SPDK_NVME_SC_ABORTED_SQ_DELETION, 0,
768 								false);
769 			tr = TAILQ_FIRST(&pqpair->outstanding_tr);
770 		} else {
771 			tr = TAILQ_NEXT(tr, tq_list);
772 		}
773 	}
774 }
775 
776 void
777 nvme_pcie_admin_qpair_destroy(struct spdk_nvme_qpair *qpair)
778 {
779 	nvme_pcie_admin_qpair_abort_aers(qpair);
780 }
781 
782 void
783 nvme_pcie_qpair_abort_reqs(struct spdk_nvme_qpair *qpair, uint32_t dnr)
784 {
785 	nvme_pcie_qpair_abort_trackers(qpair, dnr);
786 }
787 
788 static void
789 nvme_pcie_qpair_check_timeout(struct spdk_nvme_qpair *qpair)
790 {
791 	uint64_t t02;
792 	struct nvme_tracker *tr, *tmp;
793 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
794 	struct spdk_nvme_ctrlr *ctrlr = qpair->ctrlr;
795 	struct spdk_nvme_ctrlr_process *active_proc;
796 
797 	/* Don't check timeouts during controller initialization. */
798 	if (ctrlr->state != NVME_CTRLR_STATE_READY) {
799 		return;
800 	}
801 
802 	if (nvme_qpair_is_admin_queue(qpair)) {
803 		active_proc = nvme_ctrlr_get_current_process(ctrlr);
804 	} else {
805 		active_proc = qpair->active_proc;
806 	}
807 
808 	/* Only check timeouts if the current process has a timeout callback. */
809 	if (active_proc == NULL || active_proc->timeout_cb_fn == NULL) {
810 		return;
811 	}
812 
813 	t02 = spdk_get_ticks();
814 	TAILQ_FOREACH_SAFE(tr, &pqpair->outstanding_tr, tq_list, tmp) {
815 		assert(tr->req != NULL);
816 
817 		if (nvme_request_check_timeout(tr->req, tr->cid, active_proc, t02)) {
818 			/*
819 			 * The requests are in order, so as soon as one has not timed out,
820 			 * stop iterating.
821 			 */
822 			break;
823 		}
824 	}
825 }
826 
827 int32_t
828 nvme_pcie_qpair_process_completions(struct spdk_nvme_qpair *qpair, uint32_t max_completions)
829 {
830 	struct nvme_pcie_qpair	*pqpair = nvme_pcie_qpair(qpair);
831 	struct nvme_tracker	*tr;
832 	struct spdk_nvme_cpl	*cpl, *next_cpl;
833 	uint32_t		 num_completions = 0;
834 	struct spdk_nvme_ctrlr	*ctrlr = qpair->ctrlr;
835 	uint16_t		 next_cq_head;
836 	uint8_t			 next_phase;
837 	bool			 next_is_valid = false;
838 	int			 rc;
839 
840 	if (spdk_unlikely(pqpair->pcie_state == NVME_PCIE_QPAIR_FAILED)) {
841 		return -ENXIO;
842 	}
843 
844 	if (spdk_unlikely(nvme_qpair_get_state(qpair) == NVME_QPAIR_CONNECTING)) {
845 		if (pqpair->pcie_state == NVME_PCIE_QPAIR_READY) {
846 			/* It is possible that another thread set the pcie_state to
847 			 * QPAIR_READY, if it polled the adminq and processed the SQ
848 			 * completion for this qpair.  So check for that condition
849 			 * here and then update the qpair's state to CONNECTED, since
850 			 * we can only set the qpair state from the qpair's thread.
851 			 * (Note: this fixed issue #2157.)
852 			 */
853 			nvme_qpair_set_state(qpair, NVME_QPAIR_CONNECTED);
854 		} else if (pqpair->pcie_state == NVME_PCIE_QPAIR_FAILED) {
855 			nvme_qpair_set_state(qpair, NVME_QPAIR_DISCONNECTED);
856 			return -ENXIO;
857 		} else {
858 			rc = spdk_nvme_qpair_process_completions(ctrlr->adminq, 0);
859 			if (rc < 0) {
860 				return rc;
861 			} else if (pqpair->pcie_state == NVME_PCIE_QPAIR_FAILED) {
862 				nvme_qpair_set_state(qpair, NVME_QPAIR_DISCONNECTED);
863 				return -ENXIO;
864 			}
865 		}
866 		return 0;
867 	}
868 
869 	if (spdk_unlikely(nvme_qpair_is_admin_queue(qpair))) {
870 		nvme_ctrlr_lock(ctrlr);
871 	}
872 
873 	if (max_completions == 0 || max_completions > pqpair->max_completions_cap) {
874 		/*
875 		 * max_completions == 0 means unlimited, but complete at most
876 		 * max_completions_cap batch of I/O at a time so that the completion
877 		 * queue doorbells don't wrap around.
878 		 */
879 		max_completions = pqpair->max_completions_cap;
880 	}
881 
882 	pqpair->stat->polls++;
883 
884 	while (1) {
885 		cpl = &pqpair->cpl[pqpair->cq_head];
886 
887 		if (!next_is_valid && cpl->status.p != pqpair->flags.phase) {
888 			break;
889 		}
890 
891 		if (spdk_likely(pqpair->cq_head + 1 != pqpair->num_entries)) {
892 			next_cq_head = pqpair->cq_head + 1;
893 			next_phase = pqpair->flags.phase;
894 		} else {
895 			next_cq_head = 0;
896 			next_phase = !pqpair->flags.phase;
897 		}
898 		next_cpl = &pqpair->cpl[next_cq_head];
899 		next_is_valid = (next_cpl->status.p == next_phase);
900 		if (next_is_valid) {
901 			__builtin_prefetch(&pqpair->tr[next_cpl->cid]);
902 		}
903 
904 #if defined(__PPC64__) || defined(__riscv) || defined(__loongarch__)
905 		/*
906 		 * This memory barrier prevents reordering of:
907 		 * - load after store from/to tr
908 		 * - load after load cpl phase and cpl cid
909 		 */
910 		spdk_mb();
911 #elif defined(__aarch64__)
912 		__asm volatile("dmb oshld" ::: "memory");
913 #endif
914 
915 		if (spdk_unlikely(++pqpair->cq_head == pqpair->num_entries)) {
916 			pqpair->cq_head = 0;
917 			pqpair->flags.phase = !pqpair->flags.phase;
918 		}
919 
920 		tr = &pqpair->tr[cpl->cid];
921 		pqpair->sq_head = cpl->sqhd;
922 
923 		if (tr->req) {
924 			/* Prefetch the req's STAILQ_ENTRY since we'll need to access it
925 			 * as part of putting the req back on the qpair's free list.
926 			 */
927 			__builtin_prefetch(&tr->req->stailq);
928 			nvme_pcie_qpair_complete_tracker(qpair, tr, cpl, true);
929 		} else {
930 			SPDK_ERRLOG("cpl does not map to outstanding cmd\n");
931 			spdk_nvme_qpair_print_completion(qpair, cpl);
932 			assert(0);
933 		}
934 
935 		if (++num_completions == max_completions) {
936 			break;
937 		}
938 	}
939 
940 	if (num_completions > 0) {
941 		pqpair->stat->completions += num_completions;
942 		nvme_pcie_qpair_ring_cq_doorbell(qpair);
943 	} else {
944 		pqpair->stat->idle_polls++;
945 	}
946 
947 	if (pqpair->flags.delay_cmd_submit) {
948 		if (pqpair->last_sq_tail != pqpair->sq_tail) {
949 			nvme_pcie_qpair_ring_sq_doorbell(qpair);
950 			pqpair->last_sq_tail = pqpair->sq_tail;
951 		}
952 	}
953 
954 	if (spdk_unlikely(ctrlr->timeout_enabled)) {
955 		/*
956 		 * User registered for timeout callback
957 		 */
958 		nvme_pcie_qpair_check_timeout(qpair);
959 	}
960 
961 	/* Before returning, complete any pending admin request or
962 	 * process the admin qpair disconnection.
963 	 */
964 	if (spdk_unlikely(nvme_qpair_is_admin_queue(qpair))) {
965 		nvme_pcie_qpair_complete_pending_admin_request(qpair);
966 
967 		if (nvme_qpair_get_state(qpair) == NVME_QPAIR_DISCONNECTING) {
968 			rc = nvme_ctrlr_disable_poll(qpair->ctrlr);
969 			if (rc != -EAGAIN) {
970 				nvme_transport_ctrlr_disconnect_qpair_done(qpair);
971 			}
972 		}
973 
974 		nvme_ctrlr_unlock(ctrlr);
975 	}
976 
977 	if (spdk_unlikely(pqpair->flags.has_pending_vtophys_failures)) {
978 		struct nvme_tracker *tr, *tmp;
979 
980 		TAILQ_FOREACH_SAFE(tr, &pqpair->outstanding_tr, tq_list, tmp) {
981 			if (tr->bad_vtophys) {
982 				tr->bad_vtophys = 0;
983 				nvme_pcie_fail_request_bad_vtophys(qpair, tr);
984 			}
985 		}
986 		pqpair->flags.has_pending_vtophys_failures = 0;
987 	}
988 
989 	return num_completions;
990 }
991 
992 int
993 nvme_pcie_qpair_destroy(struct spdk_nvme_qpair *qpair)
994 {
995 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
996 
997 	if (nvme_qpair_is_admin_queue(qpair)) {
998 		nvme_pcie_admin_qpair_destroy(qpair);
999 	}
1000 	/*
1001 	 * We check sq_vaddr and cq_vaddr to see if the user specified the memory
1002 	 * buffers when creating the I/O queue.
1003 	 * If the user specified them, we cannot free that memory.
1004 	 * Nor do we free it if it's in the CMB.
1005 	 */
1006 	if (!pqpair->sq_vaddr && pqpair->cmd && !pqpair->sq_in_cmb) {
1007 		spdk_free(pqpair->cmd);
1008 	}
1009 	if (!pqpair->cq_vaddr && pqpair->cpl) {
1010 		spdk_free(pqpair->cpl);
1011 	}
1012 	if (pqpair->tr) {
1013 		spdk_free(pqpair->tr);
1014 	}
1015 
1016 	nvme_qpair_deinit(qpair);
1017 
1018 	if (!pqpair->shared_stats && (!qpair->active_proc ||
1019 				      qpair->active_proc == nvme_ctrlr_get_current_process(qpair->ctrlr))) {
1020 		if (qpair->id) {
1021 			free(pqpair->stat);
1022 		} else {
1023 			/* statistics of admin qpair are allocates from huge pages because
1024 			 * admin qpair is shared for multi-process */
1025 			spdk_free(pqpair->stat);
1026 		}
1027 
1028 	}
1029 
1030 	spdk_free(pqpair);
1031 
1032 	return 0;
1033 }
1034 
1035 struct spdk_nvme_qpair *
1036 nvme_pcie_ctrlr_create_io_qpair(struct spdk_nvme_ctrlr *ctrlr, uint16_t qid,
1037 				const struct spdk_nvme_io_qpair_opts *opts)
1038 {
1039 	struct nvme_pcie_qpair *pqpair;
1040 	struct spdk_nvme_qpair *qpair;
1041 	int rc;
1042 
1043 	assert(ctrlr != NULL);
1044 
1045 	pqpair = spdk_zmalloc(sizeof(*pqpair), 64, NULL,
1046 			      SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_SHARE);
1047 	if (pqpair == NULL) {
1048 		return NULL;
1049 	}
1050 
1051 	pqpair->num_entries = opts->io_queue_size;
1052 	pqpair->flags.delay_cmd_submit = opts->delay_cmd_submit;
1053 
1054 	qpair = &pqpair->qpair;
1055 
1056 	rc = nvme_qpair_init(qpair, qid, ctrlr, opts->qprio, opts->io_queue_requests, opts->async_mode);
1057 	if (rc != 0) {
1058 		nvme_pcie_qpair_destroy(qpair);
1059 		return NULL;
1060 	}
1061 
1062 	rc = nvme_pcie_qpair_construct(qpair, opts);
1063 
1064 	if (rc != 0) {
1065 		nvme_pcie_qpair_destroy(qpair);
1066 		return NULL;
1067 	}
1068 
1069 	return qpair;
1070 }
1071 
1072 int
1073 nvme_pcie_ctrlr_delete_io_qpair(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_qpair *qpair)
1074 {
1075 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
1076 	struct nvme_completion_poll_status *status;
1077 	int rc;
1078 
1079 	assert(ctrlr != NULL);
1080 
1081 	if (ctrlr->is_removed) {
1082 		goto free;
1083 	}
1084 
1085 	if (ctrlr->prepare_for_reset) {
1086 		if (nvme_qpair_get_state(qpair) == NVME_QPAIR_CONNECTING) {
1087 			pqpair->flags.defer_destruction = true;
1088 		}
1089 		goto clear_shadow_doorbells;
1090 	}
1091 
1092 	/* If attempting to delete a qpair that's still being connected, we have to wait until it's
1093 	 * finished, so that we don't free it while it's waiting for the create cq/sq callbacks.
1094 	 */
1095 	while (pqpair->pcie_state == NVME_PCIE_QPAIR_WAIT_FOR_CQ ||
1096 	       pqpair->pcie_state == NVME_PCIE_QPAIR_WAIT_FOR_SQ) {
1097 		rc = spdk_nvme_qpair_process_completions(ctrlr->adminq, 0);
1098 		if (rc < 0) {
1099 			break;
1100 		}
1101 	}
1102 
1103 	status = calloc(1, sizeof(*status));
1104 	if (!status) {
1105 		SPDK_ERRLOG("Failed to allocate status tracker\n");
1106 		goto free;
1107 	}
1108 
1109 	/* Delete the I/O submission queue */
1110 	rc = nvme_pcie_ctrlr_cmd_delete_io_sq(ctrlr, qpair, nvme_completion_poll_cb, status);
1111 	if (rc != 0) {
1112 		SPDK_ERRLOG("Failed to send request to delete_io_sq with rc=%d\n", rc);
1113 		free(status);
1114 		goto free;
1115 	}
1116 	if (nvme_wait_for_completion(ctrlr->adminq, status)) {
1117 		if (!status->timed_out) {
1118 			free(status);
1119 		}
1120 		goto free;
1121 	}
1122 
1123 	/* Now that the submission queue is deleted, the device is supposed to have
1124 	 * completed any outstanding I/O. Try to complete them. If they don't complete,
1125 	 * they'll be marked as aborted and completed below. */
1126 	if (qpair->active_proc == nvme_ctrlr_get_current_process(ctrlr)) {
1127 		nvme_pcie_qpair_process_completions(qpair, 0);
1128 	}
1129 
1130 	memset(status, 0, sizeof(*status));
1131 	/* Delete the completion queue */
1132 	rc = nvme_pcie_ctrlr_cmd_delete_io_cq(ctrlr, qpair, nvme_completion_poll_cb, status);
1133 	if (rc != 0) {
1134 		SPDK_ERRLOG("Failed to send request to delete_io_cq with rc=%d\n", rc);
1135 		free(status);
1136 		goto free;
1137 	}
1138 	if (nvme_wait_for_completion(ctrlr->adminq, status)) {
1139 		if (!status->timed_out) {
1140 			free(status);
1141 		}
1142 		goto free;
1143 	}
1144 	free(status);
1145 
1146 clear_shadow_doorbells:
1147 	if (pqpair->flags.has_shadow_doorbell && ctrlr->shadow_doorbell) {
1148 		*pqpair->shadow_doorbell.sq_tdbl = 0;
1149 		*pqpair->shadow_doorbell.cq_hdbl = 0;
1150 		*pqpair->shadow_doorbell.sq_eventidx = 0;
1151 		*pqpair->shadow_doorbell.cq_eventidx = 0;
1152 	}
1153 free:
1154 	if (qpair->no_deletion_notification_needed == 0) {
1155 		/* Abort the rest of the I/O */
1156 		nvme_pcie_qpair_abort_trackers(qpair, 1);
1157 	}
1158 
1159 	if (!pqpair->flags.defer_destruction) {
1160 		nvme_pcie_qpair_destroy(qpair);
1161 	}
1162 	return 0;
1163 }
1164 
1165 static void
1166 nvme_pcie_fail_request_bad_vtophys(struct spdk_nvme_qpair *qpair, struct nvme_tracker *tr)
1167 {
1168 	if (!qpair->in_completion_context) {
1169 		struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
1170 
1171 		tr->bad_vtophys = 1;
1172 		pqpair->flags.has_pending_vtophys_failures = 1;
1173 		return;
1174 	}
1175 
1176 	/*
1177 	 * Bad vtophys translation, so abort this request and return
1178 	 *  immediately.
1179 	 */
1180 	SPDK_ERRLOG("vtophys or other payload buffer related error\n");
1181 	nvme_pcie_qpair_manual_complete_tracker(qpair, tr, SPDK_NVME_SCT_GENERIC,
1182 						SPDK_NVME_SC_INVALID_FIELD,
1183 						1 /* do not retry */, true);
1184 }
1185 
1186 /*
1187  * Append PRP list entries to describe a virtually contiguous buffer starting at virt_addr of len bytes.
1188  *
1189  * *prp_index will be updated to account for the number of PRP entries used.
1190  */
1191 static inline int
1192 nvme_pcie_prp_list_append(struct spdk_nvme_ctrlr *ctrlr, struct nvme_tracker *tr,
1193 			  uint32_t *prp_index, void *virt_addr, size_t len,
1194 			  uint32_t page_size)
1195 {
1196 	struct spdk_nvme_cmd *cmd = &tr->req->cmd;
1197 	uintptr_t page_mask = page_size - 1;
1198 	uint64_t phys_addr;
1199 	uint32_t i;
1200 
1201 	SPDK_DEBUGLOG(nvme, "prp_index:%u virt_addr:%p len:%u\n",
1202 		      *prp_index, virt_addr, (uint32_t)len);
1203 
1204 	if (spdk_unlikely(((uintptr_t)virt_addr & 3) != 0)) {
1205 		SPDK_ERRLOG("virt_addr %p not dword aligned\n", virt_addr);
1206 		return -EFAULT;
1207 	}
1208 
1209 	i = *prp_index;
1210 	while (len) {
1211 		uint32_t seg_len;
1212 
1213 		/*
1214 		 * prp_index 0 is stored in prp1, and the rest are stored in the prp[] array,
1215 		 * so prp_index == count is valid.
1216 		 */
1217 		if (spdk_unlikely(i > SPDK_COUNTOF(tr->u.prp))) {
1218 			SPDK_ERRLOG("out of PRP entries\n");
1219 			return -EFAULT;
1220 		}
1221 
1222 		phys_addr = nvme_pcie_vtophys(ctrlr, virt_addr, NULL);
1223 		if (spdk_unlikely(phys_addr == SPDK_VTOPHYS_ERROR)) {
1224 			SPDK_ERRLOG("vtophys(%p) failed\n", virt_addr);
1225 			return -EFAULT;
1226 		}
1227 
1228 		if (i == 0) {
1229 			SPDK_DEBUGLOG(nvme, "prp1 = %p\n", (void *)phys_addr);
1230 			cmd->dptr.prp.prp1 = phys_addr;
1231 			seg_len = page_size - ((uintptr_t)virt_addr & page_mask);
1232 		} else {
1233 			if ((phys_addr & page_mask) != 0) {
1234 				SPDK_ERRLOG("PRP %u not page aligned (%p)\n", i, virt_addr);
1235 				return -EFAULT;
1236 			}
1237 
1238 			SPDK_DEBUGLOG(nvme, "prp[%u] = %p\n", i - 1, (void *)phys_addr);
1239 			tr->u.prp[i - 1] = phys_addr;
1240 			seg_len = page_size;
1241 		}
1242 
1243 		seg_len = spdk_min(seg_len, len);
1244 		virt_addr = (uint8_t *)virt_addr + seg_len;
1245 		len -= seg_len;
1246 		i++;
1247 	}
1248 
1249 	cmd->psdt = SPDK_NVME_PSDT_PRP;
1250 	if (i <= 1) {
1251 		cmd->dptr.prp.prp2 = 0;
1252 	} else if (i == 2) {
1253 		cmd->dptr.prp.prp2 = tr->u.prp[0];
1254 		SPDK_DEBUGLOG(nvme, "prp2 = %p\n", (void *)cmd->dptr.prp.prp2);
1255 	} else {
1256 		cmd->dptr.prp.prp2 = tr->prp_sgl_bus_addr;
1257 		SPDK_DEBUGLOG(nvme, "prp2 = %p (PRP list)\n", (void *)cmd->dptr.prp.prp2);
1258 	}
1259 
1260 	*prp_index = i;
1261 	return 0;
1262 }
1263 
1264 static int
1265 nvme_pcie_qpair_build_request_invalid(struct spdk_nvme_qpair *qpair,
1266 				      struct nvme_request *req, struct nvme_tracker *tr, bool dword_aligned)
1267 {
1268 	assert(0);
1269 	nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1270 	return -EINVAL;
1271 }
1272 
1273 /**
1274  * Build PRP list describing physically contiguous payload buffer.
1275  */
1276 static int
1277 nvme_pcie_qpair_build_contig_request(struct spdk_nvme_qpair *qpair, struct nvme_request *req,
1278 				     struct nvme_tracker *tr, bool dword_aligned)
1279 {
1280 	uint32_t prp_index = 0;
1281 	int rc;
1282 
1283 	rc = nvme_pcie_prp_list_append(qpair->ctrlr, tr, &prp_index,
1284 				       (uint8_t *)req->payload.contig_or_cb_arg + req->payload_offset,
1285 				       req->payload_size, qpair->ctrlr->page_size);
1286 	if (rc) {
1287 		nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1288 	}
1289 
1290 	return rc;
1291 }
1292 
1293 /**
1294  * Build an SGL describing a physically contiguous payload buffer.
1295  *
1296  * This is more efficient than using PRP because large buffers can be
1297  * described this way.
1298  */
1299 static int
1300 nvme_pcie_qpair_build_contig_hw_sgl_request(struct spdk_nvme_qpair *qpair, struct nvme_request *req,
1301 		struct nvme_tracker *tr, bool dword_aligned)
1302 {
1303 	uint8_t *virt_addr;
1304 	uint64_t phys_addr, mapping_length;
1305 	uint32_t length;
1306 	struct spdk_nvme_sgl_descriptor *sgl;
1307 	uint32_t nseg = 0;
1308 
1309 	assert(req->payload_size != 0);
1310 	assert(nvme_payload_type(&req->payload) == NVME_PAYLOAD_TYPE_CONTIG);
1311 
1312 	sgl = tr->u.sgl;
1313 	req->cmd.psdt = SPDK_NVME_PSDT_SGL_MPTR_CONTIG;
1314 	req->cmd.dptr.sgl1.unkeyed.subtype = 0;
1315 
1316 	length = req->payload_size;
1317 	/* ubsan complains about applying zero offset to null pointer if contig_or_cb_arg is NULL,
1318 	 * so just double cast it to make it go away */
1319 	virt_addr = (uint8_t *)((uintptr_t)req->payload.contig_or_cb_arg + req->payload_offset);
1320 
1321 	while (length > 0) {
1322 		if (nseg >= NVME_MAX_SGL_DESCRIPTORS) {
1323 			nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1324 			return -EFAULT;
1325 		}
1326 
1327 		if (dword_aligned && ((uintptr_t)virt_addr & 3)) {
1328 			SPDK_ERRLOG("virt_addr %p not dword aligned\n", virt_addr);
1329 			nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1330 			return -EFAULT;
1331 		}
1332 
1333 		mapping_length = length;
1334 		phys_addr = nvme_pcie_vtophys(qpair->ctrlr, virt_addr, &mapping_length);
1335 		if (phys_addr == SPDK_VTOPHYS_ERROR) {
1336 			nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1337 			return -EFAULT;
1338 		}
1339 
1340 		mapping_length = spdk_min(length, mapping_length);
1341 
1342 		length -= mapping_length;
1343 		virt_addr += mapping_length;
1344 
1345 		sgl->unkeyed.type = SPDK_NVME_SGL_TYPE_DATA_BLOCK;
1346 		sgl->unkeyed.length = mapping_length;
1347 		sgl->address = phys_addr;
1348 		sgl->unkeyed.subtype = 0;
1349 
1350 		sgl++;
1351 		nseg++;
1352 	}
1353 
1354 	if (nseg == 1) {
1355 		/*
1356 		 * The whole transfer can be described by a single SGL descriptor.
1357 		 *  Use the special case described by the spec where SGL1's type is Data Block.
1358 		 *  This means the SGL in the tracker is not used at all, so copy the first (and only)
1359 		 *  SGL element into SGL1.
1360 		 */
1361 		req->cmd.dptr.sgl1.unkeyed.type = SPDK_NVME_SGL_TYPE_DATA_BLOCK;
1362 		req->cmd.dptr.sgl1.address = tr->u.sgl[0].address;
1363 		req->cmd.dptr.sgl1.unkeyed.length = tr->u.sgl[0].unkeyed.length;
1364 	} else {
1365 		/* SPDK NVMe driver supports only 1 SGL segment for now, it is enough because
1366 		 *  NVME_MAX_SGL_DESCRIPTORS * 16 is less than one page.
1367 		 */
1368 		req->cmd.dptr.sgl1.unkeyed.type = SPDK_NVME_SGL_TYPE_LAST_SEGMENT;
1369 		req->cmd.dptr.sgl1.address = tr->prp_sgl_bus_addr;
1370 		req->cmd.dptr.sgl1.unkeyed.length = nseg * sizeof(struct spdk_nvme_sgl_descriptor);
1371 	}
1372 
1373 	return 0;
1374 }
1375 
1376 /**
1377  * Build SGL list describing scattered payload buffer.
1378  */
1379 static int
1380 nvme_pcie_qpair_build_hw_sgl_request(struct spdk_nvme_qpair *qpair, struct nvme_request *req,
1381 				     struct nvme_tracker *tr, bool dword_aligned)
1382 {
1383 	int rc;
1384 	void *virt_addr;
1385 	uint64_t phys_addr, mapping_length;
1386 	uint32_t remaining_transfer_len, remaining_user_sge_len, length;
1387 	struct spdk_nvme_sgl_descriptor *sgl;
1388 	uint32_t nseg = 0;
1389 
1390 	/*
1391 	 * Build scattered payloads.
1392 	 */
1393 	assert(req->payload_size != 0);
1394 	assert(nvme_payload_type(&req->payload) == NVME_PAYLOAD_TYPE_SGL);
1395 	assert(req->payload.reset_sgl_fn != NULL);
1396 	assert(req->payload.next_sge_fn != NULL);
1397 	req->payload.reset_sgl_fn(req->payload.contig_or_cb_arg, req->payload_offset);
1398 
1399 	sgl = tr->u.sgl;
1400 	req->cmd.psdt = SPDK_NVME_PSDT_SGL_MPTR_CONTIG;
1401 	req->cmd.dptr.sgl1.unkeyed.subtype = 0;
1402 
1403 	remaining_transfer_len = req->payload_size;
1404 
1405 	while (remaining_transfer_len > 0) {
1406 		rc = req->payload.next_sge_fn(req->payload.contig_or_cb_arg,
1407 					      &virt_addr, &remaining_user_sge_len);
1408 		if (rc) {
1409 			nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1410 			return -EFAULT;
1411 		}
1412 
1413 		/* Bit Bucket SGL descriptor */
1414 		if ((uint64_t)virt_addr == UINT64_MAX) {
1415 			/* TODO: enable WRITE and COMPARE when necessary */
1416 			if (req->cmd.opc != SPDK_NVME_OPC_READ) {
1417 				SPDK_ERRLOG("Only READ command can be supported\n");
1418 				goto exit;
1419 			}
1420 			if (nseg >= NVME_MAX_SGL_DESCRIPTORS) {
1421 				SPDK_ERRLOG("Too many SGL entries\n");
1422 				goto exit;
1423 			}
1424 
1425 			sgl->unkeyed.type = SPDK_NVME_SGL_TYPE_BIT_BUCKET;
1426 			/* If the SGL describes a destination data buffer, the length of data
1427 			 * buffer shall be discarded by controller, and the length is included
1428 			 * in Number of Logical Blocks (NLB) parameter. Otherwise, the length
1429 			 * is not included in the NLB parameter.
1430 			 */
1431 			remaining_user_sge_len = spdk_min(remaining_user_sge_len, remaining_transfer_len);
1432 			remaining_transfer_len -= remaining_user_sge_len;
1433 
1434 			sgl->unkeyed.length = remaining_user_sge_len;
1435 			sgl->address = 0;
1436 			sgl->unkeyed.subtype = 0;
1437 
1438 			sgl++;
1439 			nseg++;
1440 
1441 			continue;
1442 		}
1443 
1444 		remaining_user_sge_len = spdk_min(remaining_user_sge_len, remaining_transfer_len);
1445 		remaining_transfer_len -= remaining_user_sge_len;
1446 		while (remaining_user_sge_len > 0) {
1447 			if (nseg >= NVME_MAX_SGL_DESCRIPTORS) {
1448 				SPDK_ERRLOG("Too many SGL entries\n");
1449 				goto exit;
1450 			}
1451 
1452 			if (dword_aligned && ((uintptr_t)virt_addr & 3)) {
1453 				SPDK_ERRLOG("virt_addr %p not dword aligned\n", virt_addr);
1454 				goto exit;
1455 			}
1456 
1457 			mapping_length = remaining_user_sge_len;
1458 			phys_addr = nvme_pcie_vtophys(qpair->ctrlr, virt_addr, &mapping_length);
1459 			if (phys_addr == SPDK_VTOPHYS_ERROR) {
1460 				goto exit;
1461 			}
1462 
1463 			length = spdk_min(remaining_user_sge_len, mapping_length);
1464 			remaining_user_sge_len -= length;
1465 			virt_addr = (uint8_t *)virt_addr + length;
1466 
1467 			if (nseg > 0 && phys_addr ==
1468 			    (*(sgl - 1)).address + (*(sgl - 1)).unkeyed.length) {
1469 				/* extend previous entry */
1470 				(*(sgl - 1)).unkeyed.length += length;
1471 				continue;
1472 			}
1473 
1474 			sgl->unkeyed.type = SPDK_NVME_SGL_TYPE_DATA_BLOCK;
1475 			sgl->unkeyed.length = length;
1476 			sgl->address = phys_addr;
1477 			sgl->unkeyed.subtype = 0;
1478 
1479 			sgl++;
1480 			nseg++;
1481 		}
1482 	}
1483 
1484 	if (nseg == 1) {
1485 		/*
1486 		 * The whole transfer can be described by a single SGL descriptor.
1487 		 *  Use the special case described by the spec where SGL1's type is Data Block.
1488 		 *  This means the SGL in the tracker is not used at all, so copy the first (and only)
1489 		 *  SGL element into SGL1.
1490 		 */
1491 		req->cmd.dptr.sgl1.unkeyed.type = SPDK_NVME_SGL_TYPE_DATA_BLOCK;
1492 		req->cmd.dptr.sgl1.address = tr->u.sgl[0].address;
1493 		req->cmd.dptr.sgl1.unkeyed.length = tr->u.sgl[0].unkeyed.length;
1494 	} else {
1495 		/* SPDK NVMe driver supports only 1 SGL segment for now, it is enough because
1496 		 *  NVME_MAX_SGL_DESCRIPTORS * 16 is less than one page.
1497 		 */
1498 		req->cmd.dptr.sgl1.unkeyed.type = SPDK_NVME_SGL_TYPE_LAST_SEGMENT;
1499 		req->cmd.dptr.sgl1.address = tr->prp_sgl_bus_addr;
1500 		req->cmd.dptr.sgl1.unkeyed.length = nseg * sizeof(struct spdk_nvme_sgl_descriptor);
1501 	}
1502 
1503 	return 0;
1504 
1505 exit:
1506 	nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1507 	return -EFAULT;
1508 }
1509 
1510 /**
1511  * Build PRP list describing scattered payload buffer.
1512  */
1513 static int
1514 nvme_pcie_qpair_build_prps_sgl_request(struct spdk_nvme_qpair *qpair, struct nvme_request *req,
1515 				       struct nvme_tracker *tr, bool dword_aligned)
1516 {
1517 	int rc;
1518 	void *virt_addr;
1519 	uint32_t remaining_transfer_len, length;
1520 	uint32_t prp_index = 0;
1521 	uint32_t page_size = qpair->ctrlr->page_size;
1522 
1523 	/*
1524 	 * Build scattered payloads.
1525 	 */
1526 	assert(nvme_payload_type(&req->payload) == NVME_PAYLOAD_TYPE_SGL);
1527 	assert(req->payload.reset_sgl_fn != NULL);
1528 	req->payload.reset_sgl_fn(req->payload.contig_or_cb_arg, req->payload_offset);
1529 
1530 	remaining_transfer_len = req->payload_size;
1531 	while (remaining_transfer_len > 0) {
1532 		assert(req->payload.next_sge_fn != NULL);
1533 		rc = req->payload.next_sge_fn(req->payload.contig_or_cb_arg, &virt_addr, &length);
1534 		if (rc) {
1535 			nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1536 			return -EFAULT;
1537 		}
1538 
1539 		length = spdk_min(remaining_transfer_len, length);
1540 
1541 		/*
1542 		 * Any incompatible sges should have been handled up in the splitting routine,
1543 		 *  but assert here as an additional check.
1544 		 *
1545 		 * All SGEs except last must end on a page boundary.
1546 		 */
1547 		assert((length == remaining_transfer_len) ||
1548 		       _is_page_aligned((uintptr_t)virt_addr + length, page_size));
1549 
1550 		rc = nvme_pcie_prp_list_append(qpair->ctrlr, tr, &prp_index, virt_addr, length, page_size);
1551 		if (rc) {
1552 			nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1553 			return rc;
1554 		}
1555 
1556 		remaining_transfer_len -= length;
1557 	}
1558 
1559 	return 0;
1560 }
1561 
1562 typedef int(*build_req_fn)(struct spdk_nvme_qpair *, struct nvme_request *, struct nvme_tracker *,
1563 			   bool);
1564 
1565 static build_req_fn const g_nvme_pcie_build_req_table[][2] = {
1566 	[NVME_PAYLOAD_TYPE_INVALID] = {
1567 		nvme_pcie_qpair_build_request_invalid,			/* PRP */
1568 		nvme_pcie_qpair_build_request_invalid			/* SGL */
1569 	},
1570 	[NVME_PAYLOAD_TYPE_CONTIG] = {
1571 		nvme_pcie_qpair_build_contig_request,			/* PRP */
1572 		nvme_pcie_qpair_build_contig_hw_sgl_request		/* SGL */
1573 	},
1574 	[NVME_PAYLOAD_TYPE_SGL] = {
1575 		nvme_pcie_qpair_build_prps_sgl_request,			/* PRP */
1576 		nvme_pcie_qpair_build_hw_sgl_request			/* SGL */
1577 	}
1578 };
1579 
1580 static int
1581 nvme_pcie_qpair_build_metadata(struct spdk_nvme_qpair *qpair, struct nvme_tracker *tr,
1582 			       bool sgl_supported, bool mptr_sgl_supported, bool dword_aligned)
1583 {
1584 	void *md_payload;
1585 	struct nvme_request *req = tr->req;
1586 	uint64_t mapping_length;
1587 
1588 	if (req->payload.md) {
1589 		md_payload = (uint8_t *)req->payload.md + req->md_offset;
1590 		if (dword_aligned && ((uintptr_t)md_payload & 3)) {
1591 			SPDK_ERRLOG("virt_addr %p not dword aligned\n", md_payload);
1592 			goto exit;
1593 		}
1594 
1595 		mapping_length = req->md_size;
1596 		if (sgl_supported && mptr_sgl_supported && dword_aligned) {
1597 			assert(req->cmd.psdt == SPDK_NVME_PSDT_SGL_MPTR_CONTIG);
1598 			req->cmd.psdt = SPDK_NVME_PSDT_SGL_MPTR_SGL;
1599 
1600 			tr->meta_sgl.address = nvme_pcie_vtophys(qpair->ctrlr, md_payload, &mapping_length);
1601 			if (tr->meta_sgl.address == SPDK_VTOPHYS_ERROR || mapping_length != req->md_size) {
1602 				goto exit;
1603 			}
1604 			tr->meta_sgl.unkeyed.type = SPDK_NVME_SGL_TYPE_DATA_BLOCK;
1605 			tr->meta_sgl.unkeyed.length = req->md_size;
1606 			tr->meta_sgl.unkeyed.subtype = 0;
1607 			req->cmd.mptr = tr->prp_sgl_bus_addr - sizeof(struct spdk_nvme_sgl_descriptor);
1608 		} else {
1609 			req->cmd.mptr = nvme_pcie_vtophys(qpair->ctrlr, md_payload, &mapping_length);
1610 			if (req->cmd.mptr == SPDK_VTOPHYS_ERROR || mapping_length != req->md_size) {
1611 				goto exit;
1612 			}
1613 		}
1614 	}
1615 
1616 	return 0;
1617 
1618 exit:
1619 	nvme_pcie_fail_request_bad_vtophys(qpair, tr);
1620 	return -EINVAL;
1621 }
1622 
1623 int
1624 nvme_pcie_qpair_submit_request(struct spdk_nvme_qpair *qpair, struct nvme_request *req)
1625 {
1626 	struct nvme_tracker	*tr;
1627 	int			rc = 0;
1628 	struct spdk_nvme_ctrlr	*ctrlr = qpair->ctrlr;
1629 	struct nvme_pcie_qpair	*pqpair = nvme_pcie_qpair(qpair);
1630 	enum nvme_payload_type	payload_type;
1631 	bool			sgl_supported;
1632 	bool			mptr_sgl_supported;
1633 	bool			dword_aligned = true;
1634 
1635 	if (spdk_unlikely(nvme_qpair_is_admin_queue(qpair))) {
1636 		nvme_ctrlr_lock(ctrlr);
1637 	}
1638 
1639 	tr = TAILQ_FIRST(&pqpair->free_tr);
1640 
1641 	if (tr == NULL) {
1642 		pqpair->stat->queued_requests++;
1643 		/* Inform the upper layer to try again later. */
1644 		rc = -EAGAIN;
1645 		goto exit;
1646 	}
1647 
1648 	pqpair->stat->submitted_requests++;
1649 	TAILQ_REMOVE(&pqpair->free_tr, tr, tq_list); /* remove tr from free_tr */
1650 	TAILQ_INSERT_TAIL(&pqpair->outstanding_tr, tr, tq_list);
1651 	pqpair->qpair.queue_depth++;
1652 	tr->req = req;
1653 	tr->cb_fn = req->cb_fn;
1654 	tr->cb_arg = req->cb_arg;
1655 	req->cmd.cid = tr->cid;
1656 	/* Use PRP by default. This bit will be overridden below if needed. */
1657 	req->cmd.psdt = SPDK_NVME_PSDT_PRP;
1658 
1659 	if (req->payload_size != 0) {
1660 		payload_type = nvme_payload_type(&req->payload);
1661 		/* According to the specification, PRPs shall be used for all
1662 		 *  Admin commands for NVMe over PCIe implementations.
1663 		 */
1664 		sgl_supported = (ctrlr->flags & SPDK_NVME_CTRLR_SGL_SUPPORTED) != 0 &&
1665 				!nvme_qpair_is_admin_queue(qpair);
1666 		mptr_sgl_supported = (ctrlr->flags & SPDK_NVME_CTRLR_MPTR_SGL_SUPPORTED) != 0 &&
1667 				     !nvme_qpair_is_admin_queue(qpair);
1668 
1669 		if (sgl_supported) {
1670 			/* Don't use SGL for DSM command */
1671 			if (spdk_unlikely((ctrlr->quirks & NVME_QUIRK_NO_SGL_FOR_DSM) &&
1672 					  (req->cmd.opc == SPDK_NVME_OPC_DATASET_MANAGEMENT))) {
1673 				sgl_supported = false;
1674 			}
1675 		}
1676 
1677 		if (sgl_supported && !(ctrlr->flags & SPDK_NVME_CTRLR_SGL_REQUIRES_DWORD_ALIGNMENT)) {
1678 			dword_aligned = false;
1679 		}
1680 
1681 		/* If we fail to build the request or the metadata, do not return the -EFAULT back up
1682 		 * the stack.  This ensures that we always fail these types of requests via a
1683 		 * completion callback, and never in the context of the submission.
1684 		 */
1685 		rc = g_nvme_pcie_build_req_table[payload_type][sgl_supported](qpair, req, tr, dword_aligned);
1686 		if (rc < 0) {
1687 			assert(rc == -EFAULT);
1688 			rc = 0;
1689 			goto exit;
1690 		}
1691 
1692 		rc = nvme_pcie_qpair_build_metadata(qpair, tr, sgl_supported, mptr_sgl_supported, dword_aligned);
1693 		if (rc < 0) {
1694 			assert(rc == -EFAULT);
1695 			rc = 0;
1696 			goto exit;
1697 		}
1698 	}
1699 
1700 	nvme_pcie_qpair_submit_tracker(qpair, tr);
1701 
1702 exit:
1703 	if (spdk_unlikely(nvme_qpair_is_admin_queue(qpair))) {
1704 		nvme_ctrlr_unlock(ctrlr);
1705 	}
1706 
1707 	return rc;
1708 }
1709 
1710 struct spdk_nvme_transport_poll_group *
1711 nvme_pcie_poll_group_create(void)
1712 {
1713 	struct nvme_pcie_poll_group *group = calloc(1, sizeof(*group));
1714 
1715 	if (group == NULL) {
1716 		SPDK_ERRLOG("Unable to allocate poll group.\n");
1717 		return NULL;
1718 	}
1719 
1720 	return &group->group;
1721 }
1722 
1723 int
1724 nvme_pcie_poll_group_connect_qpair(struct spdk_nvme_qpair *qpair)
1725 {
1726 	return 0;
1727 }
1728 
1729 int
1730 nvme_pcie_poll_group_disconnect_qpair(struct spdk_nvme_qpair *qpair)
1731 {
1732 	return 0;
1733 }
1734 
1735 int
1736 nvme_pcie_poll_group_add(struct spdk_nvme_transport_poll_group *tgroup,
1737 			 struct spdk_nvme_qpair *qpair)
1738 {
1739 	return 0;
1740 }
1741 
1742 int
1743 nvme_pcie_poll_group_remove(struct spdk_nvme_transport_poll_group *tgroup,
1744 			    struct spdk_nvme_qpair *qpair)
1745 {
1746 	struct nvme_pcie_qpair *pqpair = nvme_pcie_qpair(qpair);
1747 
1748 	pqpair->stat = &g_dummy_stat;
1749 	return 0;
1750 }
1751 
1752 int64_t
1753 nvme_pcie_poll_group_process_completions(struct spdk_nvme_transport_poll_group *tgroup,
1754 		uint32_t completions_per_qpair, spdk_nvme_disconnected_qpair_cb disconnected_qpair_cb)
1755 {
1756 	struct spdk_nvme_qpair *qpair, *tmp_qpair;
1757 	int32_t local_completions = 0;
1758 	int64_t total_completions = 0;
1759 
1760 	STAILQ_FOREACH_SAFE(qpair, &tgroup->disconnected_qpairs, poll_group_stailq, tmp_qpair) {
1761 		disconnected_qpair_cb(qpair, tgroup->group->ctx);
1762 	}
1763 
1764 	STAILQ_FOREACH_SAFE(qpair, &tgroup->connected_qpairs, poll_group_stailq, tmp_qpair) {
1765 		local_completions = spdk_nvme_qpair_process_completions(qpair, completions_per_qpair);
1766 		if (spdk_unlikely(local_completions < 0)) {
1767 			disconnected_qpair_cb(qpair, tgroup->group->ctx);
1768 			total_completions = -ENXIO;
1769 		} else if (spdk_likely(total_completions >= 0)) {
1770 			total_completions += local_completions;
1771 		}
1772 	}
1773 
1774 	return total_completions;
1775 }
1776 
1777 int
1778 nvme_pcie_poll_group_destroy(struct spdk_nvme_transport_poll_group *tgroup)
1779 {
1780 	if (!STAILQ_EMPTY(&tgroup->connected_qpairs) || !STAILQ_EMPTY(&tgroup->disconnected_qpairs)) {
1781 		return -EBUSY;
1782 	}
1783 
1784 	free(tgroup);
1785 
1786 	return 0;
1787 }
1788 
1789 int
1790 nvme_pcie_poll_group_get_stats(struct spdk_nvme_transport_poll_group *tgroup,
1791 			       struct spdk_nvme_transport_poll_group_stat **_stats)
1792 {
1793 	struct nvme_pcie_poll_group *group;
1794 	struct spdk_nvme_transport_poll_group_stat *stats;
1795 
1796 	if (tgroup == NULL || _stats == NULL) {
1797 		SPDK_ERRLOG("Invalid stats or group pointer\n");
1798 		return -EINVAL;
1799 	}
1800 
1801 	stats = calloc(1, sizeof(*stats));
1802 	if (!stats) {
1803 		SPDK_ERRLOG("Can't allocate memory for stats\n");
1804 		return -ENOMEM;
1805 	}
1806 	stats->trtype = SPDK_NVME_TRANSPORT_PCIE;
1807 	group = SPDK_CONTAINEROF(tgroup, struct nvme_pcie_poll_group, group);
1808 	memcpy(&stats->pcie, &group->stats, sizeof(group->stats));
1809 
1810 	*_stats = stats;
1811 
1812 	return 0;
1813 }
1814 
1815 void
1816 nvme_pcie_poll_group_free_stats(struct spdk_nvme_transport_poll_group *tgroup,
1817 				struct spdk_nvme_transport_poll_group_stat *stats)
1818 {
1819 	free(stats);
1820 }
1821 
1822 SPDK_TRACE_REGISTER_FN(nvme_pcie, "nvme_pcie", TRACE_GROUP_NVME_PCIE)
1823 {
1824 	struct spdk_trace_tpoint_opts opts[] = {
1825 		{
1826 			"NVME_PCIE_SUBMIT", TRACE_NVME_PCIE_SUBMIT,
1827 			OWNER_TYPE_NVME_PCIE_QP, OBJECT_NVME_PCIE_REQ, 1,
1828 			{	{ "ctx", SPDK_TRACE_ARG_TYPE_PTR, 8 },
1829 				{ "cid", SPDK_TRACE_ARG_TYPE_INT, 4 },
1830 				{ "opc", SPDK_TRACE_ARG_TYPE_INT, 4 },
1831 				{ "dw10", SPDK_TRACE_ARG_TYPE_PTR, 4 },
1832 				{ "dw11", SPDK_TRACE_ARG_TYPE_PTR, 4 },
1833 				{ "dw12", SPDK_TRACE_ARG_TYPE_PTR, 4 },
1834 				{ "qd", SPDK_TRACE_ARG_TYPE_INT, 4 }
1835 			}
1836 		},
1837 		{
1838 			"NVME_PCIE_COMPLETE", TRACE_NVME_PCIE_COMPLETE,
1839 			OWNER_TYPE_NVME_PCIE_QP, OBJECT_NVME_PCIE_REQ, 0,
1840 			{	{ "ctx", SPDK_TRACE_ARG_TYPE_PTR, 8 },
1841 				{ "cid", SPDK_TRACE_ARG_TYPE_INT, 4 },
1842 				{ "cpl", SPDK_TRACE_ARG_TYPE_PTR, 4 },
1843 				{ "qd", SPDK_TRACE_ARG_TYPE_INT, 4 }
1844 			}
1845 		},
1846 	};
1847 
1848 	spdk_trace_register_object(OBJECT_NVME_PCIE_REQ, 'p');
1849 	spdk_trace_register_owner_type(OWNER_TYPE_NVME_PCIE_QP, 'q');
1850 	spdk_trace_register_description_ext(opts, SPDK_COUNTOF(opts));
1851 }
1852