xref: /freebsd/sys/dev/nvme/nvme_qpair.c (revision 95cd10f13971ef2f035f07c9bda14fb094edc0b3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2012-2014 Intel Corporation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/bus.h>
34 #include <sys/conf.h>
35 #include <sys/domainset.h>
36 #include <sys/proc.h>
37 
38 #include <dev/pci/pcivar.h>
39 
40 #include "nvme_private.h"
41 
42 typedef enum error_print { ERROR_PRINT_NONE, ERROR_PRINT_NO_RETRY, ERROR_PRINT_ALL } error_print_t;
43 #define DO_NOT_RETRY	1
44 
45 static void	_nvme_qpair_submit_request(struct nvme_qpair *qpair,
46 					   struct nvme_request *req);
47 static void	nvme_qpair_destroy(struct nvme_qpair *qpair);
48 
49 struct nvme_opcode_string {
50 	uint16_t	opc;
51 	const char *	str;
52 };
53 
54 static struct nvme_opcode_string admin_opcode[] = {
55 	{ NVME_OPC_DELETE_IO_SQ, "DELETE IO SQ" },
56 	{ NVME_OPC_CREATE_IO_SQ, "CREATE IO SQ" },
57 	{ NVME_OPC_GET_LOG_PAGE, "GET LOG PAGE" },
58 	{ NVME_OPC_DELETE_IO_CQ, "DELETE IO CQ" },
59 	{ NVME_OPC_CREATE_IO_CQ, "CREATE IO CQ" },
60 	{ NVME_OPC_IDENTIFY, "IDENTIFY" },
61 	{ NVME_OPC_ABORT, "ABORT" },
62 	{ NVME_OPC_SET_FEATURES, "SET FEATURES" },
63 	{ NVME_OPC_GET_FEATURES, "GET FEATURES" },
64 	{ NVME_OPC_ASYNC_EVENT_REQUEST, "ASYNC EVENT REQUEST" },
65 	{ NVME_OPC_NAMESPACE_MANAGEMENT, "NAMESPACE MANAGEMENT" },
66 	{ NVME_OPC_FIRMWARE_ACTIVATE, "FIRMWARE ACTIVATE" },
67 	{ NVME_OPC_FIRMWARE_IMAGE_DOWNLOAD, "FIRMWARE IMAGE DOWNLOAD" },
68 	{ NVME_OPC_DEVICE_SELF_TEST, "DEVICE SELF-TEST" },
69 	{ NVME_OPC_NAMESPACE_ATTACHMENT, "NAMESPACE ATTACHMENT" },
70 	{ NVME_OPC_KEEP_ALIVE, "KEEP ALIVE" },
71 	{ NVME_OPC_DIRECTIVE_SEND, "DIRECTIVE SEND" },
72 	{ NVME_OPC_DIRECTIVE_RECEIVE, "DIRECTIVE RECEIVE" },
73 	{ NVME_OPC_VIRTUALIZATION_MANAGEMENT, "VIRTUALIZATION MANAGEMENT" },
74 	{ NVME_OPC_NVME_MI_SEND, "NVME-MI SEND" },
75 	{ NVME_OPC_NVME_MI_RECEIVE, "NVME-MI RECEIVE" },
76 	{ NVME_OPC_CAPACITY_MANAGEMENT, "CAPACITY MANAGEMENT" },
77 	{ NVME_OPC_LOCKDOWN, "LOCKDOWN" },
78 	{ NVME_OPC_DOORBELL_BUFFER_CONFIG, "DOORBELL BUFFER CONFIG" },
79 	{ NVME_OPC_FABRICS_COMMANDS, "FABRICS COMMANDS" },
80 	{ NVME_OPC_FORMAT_NVM, "FORMAT NVM" },
81 	{ NVME_OPC_SECURITY_SEND, "SECURITY SEND" },
82 	{ NVME_OPC_SECURITY_RECEIVE, "SECURITY RECEIVE" },
83 	{ NVME_OPC_SANITIZE, "SANITIZE" },
84 	{ NVME_OPC_GET_LBA_STATUS, "GET LBA STATUS" },
85 	{ 0xFFFF, "ADMIN COMMAND" }
86 };
87 
88 static struct nvme_opcode_string io_opcode[] = {
89 	{ NVME_OPC_FLUSH, "FLUSH" },
90 	{ NVME_OPC_WRITE, "WRITE" },
91 	{ NVME_OPC_READ, "READ" },
92 	{ NVME_OPC_WRITE_UNCORRECTABLE, "WRITE UNCORRECTABLE" },
93 	{ NVME_OPC_COMPARE, "COMPARE" },
94 	{ NVME_OPC_WRITE_ZEROES, "WRITE ZEROES" },
95 	{ NVME_OPC_DATASET_MANAGEMENT, "DATASET MANAGEMENT" },
96 	{ NVME_OPC_VERIFY, "VERIFY" },
97 	{ NVME_OPC_RESERVATION_REGISTER, "RESERVATION REGISTER" },
98 	{ NVME_OPC_RESERVATION_REPORT, "RESERVATION REPORT" },
99 	{ NVME_OPC_RESERVATION_ACQUIRE, "RESERVATION ACQUIRE" },
100 	{ NVME_OPC_RESERVATION_RELEASE, "RESERVATION RELEASE" },
101 	{ NVME_OPC_COPY, "COPY" },
102 	{ 0xFFFF, "IO COMMAND" }
103 };
104 
105 static const char *
106 get_opcode_string(struct nvme_opcode_string *entry, uint16_t opc)
107 {
108 	while (entry->opc != 0xFFFF) {
109 		if (entry->opc == opc)
110 			return (entry->str);
111 		entry++;
112 	}
113 	return (entry->str);
114 }
115 
116 static const char *
117 get_admin_opcode_string(uint16_t opc)
118 {
119 	return (get_opcode_string(admin_opcode, opc));
120 }
121 
122 static const char *
123 get_io_opcode_string(uint16_t opc)
124 {
125 	return (get_opcode_string(io_opcode, opc));
126 }
127 
128 static void
129 nvme_admin_qpair_print_command(struct nvme_qpair *qpair,
130     struct nvme_command *cmd)
131 {
132 
133 	nvme_printf(qpair->ctrlr, "%s (%02x) sqid:%d cid:%d nsid:%x "
134 	    "cdw10:%08x cdw11:%08x\n",
135 	    get_admin_opcode_string(cmd->opc), cmd->opc, qpair->id, cmd->cid,
136 	    le32toh(cmd->nsid), le32toh(cmd->cdw10), le32toh(cmd->cdw11));
137 }
138 
139 static void
140 nvme_io_qpair_print_command(struct nvme_qpair *qpair,
141     struct nvme_command *cmd)
142 {
143 
144 	switch (cmd->opc) {
145 	case NVME_OPC_WRITE:
146 	case NVME_OPC_READ:
147 	case NVME_OPC_WRITE_UNCORRECTABLE:
148 	case NVME_OPC_COMPARE:
149 	case NVME_OPC_WRITE_ZEROES:
150 	case NVME_OPC_VERIFY:
151 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d "
152 		    "lba:%llu len:%d\n",
153 		    get_io_opcode_string(cmd->opc), qpair->id, cmd->cid, le32toh(cmd->nsid),
154 		    ((unsigned long long)le32toh(cmd->cdw11) << 32) + le32toh(cmd->cdw10),
155 		    (le32toh(cmd->cdw12) & 0xFFFF) + 1);
156 		break;
157 	case NVME_OPC_FLUSH:
158 	case NVME_OPC_DATASET_MANAGEMENT:
159 	case NVME_OPC_RESERVATION_REGISTER:
160 	case NVME_OPC_RESERVATION_REPORT:
161 	case NVME_OPC_RESERVATION_ACQUIRE:
162 	case NVME_OPC_RESERVATION_RELEASE:
163 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d\n",
164 		    get_io_opcode_string(cmd->opc), qpair->id, cmd->cid, le32toh(cmd->nsid));
165 		break;
166 	default:
167 		nvme_printf(qpair->ctrlr, "%s (%02x) sqid:%d cid:%d nsid:%d\n",
168 		    get_io_opcode_string(cmd->opc), cmd->opc, qpair->id,
169 		    cmd->cid, le32toh(cmd->nsid));
170 		break;
171 	}
172 }
173 
174 void
175 nvme_qpair_print_command(struct nvme_qpair *qpair, struct nvme_command *cmd)
176 {
177 	if (qpair->id == 0)
178 		nvme_admin_qpair_print_command(qpair, cmd);
179 	else
180 		nvme_io_qpair_print_command(qpair, cmd);
181 	if (nvme_verbose_cmd_dump) {
182 		nvme_printf(qpair->ctrlr,
183 		    "nsid:%#x rsvd2:%#x rsvd3:%#x mptr:%#jx prp1:%#jx prp2:%#jx\n",
184 		    cmd->nsid, cmd->rsvd2, cmd->rsvd3, (uintmax_t)cmd->mptr,
185 		    (uintmax_t)cmd->prp1, (uintmax_t)cmd->prp2);
186 		nvme_printf(qpair->ctrlr,
187 		    "cdw10: %#x cdw11:%#x cdw12:%#x cdw13:%#x cdw14:%#x cdw15:%#x\n",
188 		    cmd->cdw10, cmd->cdw11, cmd->cdw12, cmd->cdw13, cmd->cdw14,
189 		    cmd->cdw15);
190 	}
191 }
192 
193 struct nvme_status_string {
194 	uint16_t	sc;
195 	const char *	str;
196 };
197 
198 static struct nvme_status_string generic_status[] = {
199 	{ NVME_SC_SUCCESS, "SUCCESS" },
200 	{ NVME_SC_INVALID_OPCODE, "INVALID OPCODE" },
201 	{ NVME_SC_INVALID_FIELD, "INVALID_FIELD" },
202 	{ NVME_SC_COMMAND_ID_CONFLICT, "COMMAND ID CONFLICT" },
203 	{ NVME_SC_DATA_TRANSFER_ERROR, "DATA TRANSFER ERROR" },
204 	{ NVME_SC_ABORTED_POWER_LOSS, "ABORTED - POWER LOSS" },
205 	{ NVME_SC_INTERNAL_DEVICE_ERROR, "INTERNAL DEVICE ERROR" },
206 	{ NVME_SC_ABORTED_BY_REQUEST, "ABORTED - BY REQUEST" },
207 	{ NVME_SC_ABORTED_SQ_DELETION, "ABORTED - SQ DELETION" },
208 	{ NVME_SC_ABORTED_FAILED_FUSED, "ABORTED - FAILED FUSED" },
209 	{ NVME_SC_ABORTED_MISSING_FUSED, "ABORTED - MISSING FUSED" },
210 	{ NVME_SC_INVALID_NAMESPACE_OR_FORMAT, "INVALID NAMESPACE OR FORMAT" },
211 	{ NVME_SC_COMMAND_SEQUENCE_ERROR, "COMMAND SEQUENCE ERROR" },
212 	{ NVME_SC_INVALID_SGL_SEGMENT_DESCR, "INVALID SGL SEGMENT DESCRIPTOR" },
213 	{ NVME_SC_INVALID_NUMBER_OF_SGL_DESCR, "INVALID NUMBER OF SGL DESCRIPTORS" },
214 	{ NVME_SC_DATA_SGL_LENGTH_INVALID, "DATA SGL LENGTH INVALID" },
215 	{ NVME_SC_METADATA_SGL_LENGTH_INVALID, "METADATA SGL LENGTH INVALID" },
216 	{ NVME_SC_SGL_DESCRIPTOR_TYPE_INVALID, "SGL DESCRIPTOR TYPE INVALID" },
217 	{ NVME_SC_INVALID_USE_OF_CMB, "INVALID USE OF CONTROLLER MEMORY BUFFER" },
218 	{ NVME_SC_PRP_OFFET_INVALID, "PRP OFFET INVALID" },
219 	{ NVME_SC_ATOMIC_WRITE_UNIT_EXCEEDED, "ATOMIC WRITE UNIT EXCEEDED" },
220 	{ NVME_SC_OPERATION_DENIED, "OPERATION DENIED" },
221 	{ NVME_SC_SGL_OFFSET_INVALID, "SGL OFFSET INVALID" },
222 	{ NVME_SC_HOST_ID_INCONSISTENT_FORMAT, "HOST IDENTIFIER INCONSISTENT FORMAT" },
223 	{ NVME_SC_KEEP_ALIVE_TIMEOUT_EXPIRED, "KEEP ALIVE TIMEOUT EXPIRED" },
224 	{ NVME_SC_KEEP_ALIVE_TIMEOUT_INVALID, "KEEP ALIVE TIMEOUT INVALID" },
225 	{ NVME_SC_ABORTED_DUE_TO_PREEMPT, "COMMAND ABORTED DUE TO PREEMPT AND ABORT" },
226 	{ NVME_SC_SANITIZE_FAILED, "SANITIZE FAILED" },
227 	{ NVME_SC_SANITIZE_IN_PROGRESS, "SANITIZE IN PROGRESS" },
228 	{ NVME_SC_SGL_DATA_BLOCK_GRAN_INVALID, "SGL_DATA_BLOCK_GRANULARITY_INVALID" },
229 	{ NVME_SC_NOT_SUPPORTED_IN_CMB, "COMMAND NOT SUPPORTED FOR QUEUE IN CMB" },
230 	{ NVME_SC_NAMESPACE_IS_WRITE_PROTECTED, "NAMESPACE IS WRITE PROTECTED" },
231 	{ NVME_SC_COMMAND_INTERRUPTED, "COMMAND INTERRUPTED" },
232 	{ NVME_SC_TRANSIENT_TRANSPORT_ERROR, "TRANSIENT TRANSPORT ERROR" },
233 
234 	{ NVME_SC_LBA_OUT_OF_RANGE, "LBA OUT OF RANGE" },
235 	{ NVME_SC_CAPACITY_EXCEEDED, "CAPACITY EXCEEDED" },
236 	{ NVME_SC_NAMESPACE_NOT_READY, "NAMESPACE NOT READY" },
237 	{ NVME_SC_RESERVATION_CONFLICT, "RESERVATION CONFLICT" },
238 	{ NVME_SC_FORMAT_IN_PROGRESS, "FORMAT IN PROGRESS" },
239 	{ 0xFFFF, "GENERIC" }
240 };
241 
242 static struct nvme_status_string command_specific_status[] = {
243 	{ NVME_SC_COMPLETION_QUEUE_INVALID, "INVALID COMPLETION QUEUE" },
244 	{ NVME_SC_INVALID_QUEUE_IDENTIFIER, "INVALID QUEUE IDENTIFIER" },
245 	{ NVME_SC_MAXIMUM_QUEUE_SIZE_EXCEEDED, "MAX QUEUE SIZE EXCEEDED" },
246 	{ NVME_SC_ABORT_COMMAND_LIMIT_EXCEEDED, "ABORT CMD LIMIT EXCEEDED" },
247 	{ NVME_SC_ASYNC_EVENT_REQUEST_LIMIT_EXCEEDED, "ASYNC LIMIT EXCEEDED" },
248 	{ NVME_SC_INVALID_FIRMWARE_SLOT, "INVALID FIRMWARE SLOT" },
249 	{ NVME_SC_INVALID_FIRMWARE_IMAGE, "INVALID FIRMWARE IMAGE" },
250 	{ NVME_SC_INVALID_INTERRUPT_VECTOR, "INVALID INTERRUPT VECTOR" },
251 	{ NVME_SC_INVALID_LOG_PAGE, "INVALID LOG PAGE" },
252 	{ NVME_SC_INVALID_FORMAT, "INVALID FORMAT" },
253 	{ NVME_SC_FIRMWARE_REQUIRES_RESET, "FIRMWARE REQUIRES RESET" },
254 	{ NVME_SC_INVALID_QUEUE_DELETION, "INVALID QUEUE DELETION" },
255 	{ NVME_SC_FEATURE_NOT_SAVEABLE, "FEATURE IDENTIFIER NOT SAVEABLE" },
256 	{ NVME_SC_FEATURE_NOT_CHANGEABLE, "FEATURE NOT CHANGEABLE" },
257 	{ NVME_SC_FEATURE_NOT_NS_SPECIFIC, "FEATURE NOT NAMESPACE SPECIFIC" },
258 	{ NVME_SC_FW_ACT_REQUIRES_NVMS_RESET, "FIRMWARE ACTIVATION REQUIRES NVM SUBSYSTEM RESET" },
259 	{ NVME_SC_FW_ACT_REQUIRES_RESET, "FIRMWARE ACTIVATION REQUIRES RESET" },
260 	{ NVME_SC_FW_ACT_REQUIRES_TIME, "FIRMWARE ACTIVATION REQUIRES MAXIMUM TIME VIOLATION" },
261 	{ NVME_SC_FW_ACT_PROHIBITED, "FIRMWARE ACTIVATION PROHIBITED" },
262 	{ NVME_SC_OVERLAPPING_RANGE, "OVERLAPPING RANGE" },
263 	{ NVME_SC_NS_INSUFFICIENT_CAPACITY, "NAMESPACE INSUFFICIENT CAPACITY" },
264 	{ NVME_SC_NS_ID_UNAVAILABLE, "NAMESPACE IDENTIFIER UNAVAILABLE" },
265 	{ NVME_SC_NS_ALREADY_ATTACHED, "NAMESPACE ALREADY ATTACHED" },
266 	{ NVME_SC_NS_IS_PRIVATE, "NAMESPACE IS PRIVATE" },
267 	{ NVME_SC_NS_NOT_ATTACHED, "NS NOT ATTACHED" },
268 	{ NVME_SC_THIN_PROV_NOT_SUPPORTED, "THIN PROVISIONING NOT SUPPORTED" },
269 	{ NVME_SC_CTRLR_LIST_INVALID, "CONTROLLER LIST INVALID" },
270 	{ NVME_SC_SELF_TEST_IN_PROGRESS, "DEVICE SELF-TEST IN PROGRESS" },
271 	{ NVME_SC_BOOT_PART_WRITE_PROHIB, "BOOT PARTITION WRITE PROHIBITED" },
272 	{ NVME_SC_INVALID_CTRLR_ID, "INVALID CONTROLLER IDENTIFIER" },
273 	{ NVME_SC_INVALID_SEC_CTRLR_STATE, "INVALID SECONDARY CONTROLLER STATE" },
274 	{ NVME_SC_INVALID_NUM_OF_CTRLR_RESRC, "INVALID NUMBER OF CONTROLLER RESOURCES" },
275 	{ NVME_SC_INVALID_RESOURCE_ID, "INVALID RESOURCE IDENTIFIER" },
276 	{ NVME_SC_SANITIZE_PROHIBITED_WPMRE, "SANITIZE PROHIBITED WRITE PERSISTENT MEMORY REGION ENABLED" },
277 	{ NVME_SC_ANA_GROUP_ID_INVALID, "ANA GROUP IDENTIFIED INVALID" },
278 	{ NVME_SC_ANA_ATTACH_FAILED, "ANA ATTACH FAILED" },
279 
280 	{ NVME_SC_CONFLICTING_ATTRIBUTES, "CONFLICTING ATTRIBUTES" },
281 	{ NVME_SC_INVALID_PROTECTION_INFO, "INVALID PROTECTION INFO" },
282 	{ NVME_SC_ATTEMPTED_WRITE_TO_RO_PAGE, "WRITE TO RO PAGE" },
283 	{ 0xFFFF, "COMMAND SPECIFIC" }
284 };
285 
286 static struct nvme_status_string media_error_status[] = {
287 	{ NVME_SC_WRITE_FAULTS, "WRITE FAULTS" },
288 	{ NVME_SC_UNRECOVERED_READ_ERROR, "UNRECOVERED READ ERROR" },
289 	{ NVME_SC_GUARD_CHECK_ERROR, "GUARD CHECK ERROR" },
290 	{ NVME_SC_APPLICATION_TAG_CHECK_ERROR, "APPLICATION TAG CHECK ERROR" },
291 	{ NVME_SC_REFERENCE_TAG_CHECK_ERROR, "REFERENCE TAG CHECK ERROR" },
292 	{ NVME_SC_COMPARE_FAILURE, "COMPARE FAILURE" },
293 	{ NVME_SC_ACCESS_DENIED, "ACCESS DENIED" },
294 	{ NVME_SC_DEALLOCATED_OR_UNWRITTEN, "DEALLOCATED OR UNWRITTEN LOGICAL BLOCK" },
295 	{ 0xFFFF, "MEDIA ERROR" }
296 };
297 
298 static struct nvme_status_string path_related_status[] = {
299 	{ NVME_SC_INTERNAL_PATH_ERROR, "INTERNAL PATH ERROR" },
300 	{ NVME_SC_ASYMMETRIC_ACCESS_PERSISTENT_LOSS, "ASYMMETRIC ACCESS PERSISTENT LOSS" },
301 	{ NVME_SC_ASYMMETRIC_ACCESS_INACCESSIBLE, "ASYMMETRIC ACCESS INACCESSIBLE" },
302 	{ NVME_SC_ASYMMETRIC_ACCESS_TRANSITION, "ASYMMETRIC ACCESS TRANSITION" },
303 	{ NVME_SC_CONTROLLER_PATHING_ERROR, "CONTROLLER PATHING ERROR" },
304 	{ NVME_SC_HOST_PATHING_ERROR, "HOST PATHING ERROR" },
305 	{ NVME_SC_COMMAND_ABORTED_BY_HOST, "COMMAND ABORTED BY HOST" },
306 	{ 0xFFFF, "PATH RELATED" },
307 };
308 
309 static const char *
310 get_status_string(uint16_t sct, uint16_t sc)
311 {
312 	struct nvme_status_string *entry;
313 
314 	switch (sct) {
315 	case NVME_SCT_GENERIC:
316 		entry = generic_status;
317 		break;
318 	case NVME_SCT_COMMAND_SPECIFIC:
319 		entry = command_specific_status;
320 		break;
321 	case NVME_SCT_MEDIA_ERROR:
322 		entry = media_error_status;
323 		break;
324 	case NVME_SCT_PATH_RELATED:
325 		entry = path_related_status;
326 		break;
327 	case NVME_SCT_VENDOR_SPECIFIC:
328 		return ("VENDOR SPECIFIC");
329 	default:
330 		return ("RESERVED");
331 	}
332 
333 	while (entry->sc != 0xFFFF) {
334 		if (entry->sc == sc)
335 			return (entry->str);
336 		entry++;
337 	}
338 	return (entry->str);
339 }
340 
341 void
342 nvme_qpair_print_completion(struct nvme_qpair *qpair,
343     struct nvme_completion *cpl)
344 {
345 	uint8_t sct, sc, crd, m, dnr, p;
346 
347 	sct = NVME_STATUS_GET_SCT(cpl->status);
348 	sc = NVME_STATUS_GET_SC(cpl->status);
349 	crd = NVME_STATUS_GET_CRD(cpl->status);
350 	m = NVME_STATUS_GET_M(cpl->status);
351 	dnr = NVME_STATUS_GET_DNR(cpl->status);
352 	p = NVME_STATUS_GET_P(cpl->status);
353 
354 	nvme_printf(qpair->ctrlr, "%s (%02x/%02x) crd:%x m:%x dnr:%x p:%d "
355 	    "sqid:%d cid:%d cdw0:%x\n",
356 	    get_status_string(sct, sc), sct, sc, crd, m, dnr, p,
357 	    cpl->sqid, cpl->cid, cpl->cdw0);
358 }
359 
360 static bool
361 nvme_completion_is_retry(const struct nvme_completion *cpl)
362 {
363 	uint8_t sct, sc, dnr;
364 
365 	sct = NVME_STATUS_GET_SCT(cpl->status);
366 	sc = NVME_STATUS_GET_SC(cpl->status);
367 	dnr = NVME_STATUS_GET_DNR(cpl->status);	/* Do Not Retry Bit */
368 
369 	/*
370 	 * TODO: spec is not clear how commands that are aborted due
371 	 *  to TLER will be marked.  So for now, it seems
372 	 *  NAMESPACE_NOT_READY is the only case where we should
373 	 *  look at the DNR bit. Requests failed with ABORTED_BY_REQUEST
374 	 *  set the DNR bit correctly since the driver controls that.
375 	 */
376 	switch (sct) {
377 	case NVME_SCT_GENERIC:
378 		switch (sc) {
379 		case NVME_SC_ABORTED_BY_REQUEST:
380 		case NVME_SC_NAMESPACE_NOT_READY:
381 			if (dnr)
382 				return (0);
383 			else
384 				return (1);
385 		case NVME_SC_INVALID_OPCODE:
386 		case NVME_SC_INVALID_FIELD:
387 		case NVME_SC_COMMAND_ID_CONFLICT:
388 		case NVME_SC_DATA_TRANSFER_ERROR:
389 		case NVME_SC_ABORTED_POWER_LOSS:
390 		case NVME_SC_INTERNAL_DEVICE_ERROR:
391 		case NVME_SC_ABORTED_SQ_DELETION:
392 		case NVME_SC_ABORTED_FAILED_FUSED:
393 		case NVME_SC_ABORTED_MISSING_FUSED:
394 		case NVME_SC_INVALID_NAMESPACE_OR_FORMAT:
395 		case NVME_SC_COMMAND_SEQUENCE_ERROR:
396 		case NVME_SC_LBA_OUT_OF_RANGE:
397 		case NVME_SC_CAPACITY_EXCEEDED:
398 		default:
399 			return (0);
400 		}
401 	case NVME_SCT_COMMAND_SPECIFIC:
402 	case NVME_SCT_MEDIA_ERROR:
403 		return (0);
404 	case NVME_SCT_PATH_RELATED:
405 		switch (sc) {
406 		case NVME_SC_INTERNAL_PATH_ERROR:
407 			if (dnr)
408 				return (0);
409 			else
410 				return (1);
411 		default:
412 			return (0);
413 		}
414 	case NVME_SCT_VENDOR_SPECIFIC:
415 	default:
416 		return (0);
417 	}
418 }
419 
420 static void
421 nvme_qpair_complete_tracker(struct nvme_tracker *tr,
422     struct nvme_completion *cpl, error_print_t print_on_error)
423 {
424 	struct nvme_qpair * qpair = tr->qpair;
425 	struct nvme_request	*req;
426 	bool			retry, error, retriable;
427 
428 	req = tr->req;
429 	error = nvme_completion_is_error(cpl);
430 	retriable = nvme_completion_is_retry(cpl);
431 	retry = error && retriable && req->retries < nvme_retry_count;
432 	if (retry)
433 		qpair->num_retries++;
434 	if (error && req->retries >= nvme_retry_count && retriable)
435 		qpair->num_failures++;
436 
437 	if (error && (print_on_error == ERROR_PRINT_ALL ||
438 		(!retry && print_on_error == ERROR_PRINT_NO_RETRY))) {
439 		nvme_qpair_print_command(qpair, &req->cmd);
440 		nvme_qpair_print_completion(qpair, cpl);
441 	}
442 
443 	qpair->act_tr[cpl->cid] = NULL;
444 
445 	KASSERT(cpl->cid == req->cmd.cid, ("cpl cid does not match cmd cid\n"));
446 
447 	if (!retry) {
448 		if (req->payload_valid) {
449 			bus_dmamap_sync(qpair->dma_tag_payload,
450 			    tr->payload_dma_map,
451 			    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
452 		}
453 		if (req->cb_fn)
454 			req->cb_fn(req->cb_arg, cpl);
455 	}
456 
457 	mtx_lock(&qpair->lock);
458 
459 	if (retry) {
460 		req->retries++;
461 		nvme_qpair_submit_tracker(qpair, tr);
462 	} else {
463 		if (req->payload_valid) {
464 			bus_dmamap_unload(qpair->dma_tag_payload,
465 			    tr->payload_dma_map);
466 		}
467 
468 		nvme_free_request(req);
469 		tr->req = NULL;
470 
471 		TAILQ_REMOVE(&qpair->outstanding_tr, tr, tailq);
472 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
473 
474 		/*
475 		 * If the controller is in the middle of resetting, don't
476 		 *  try to submit queued requests here - let the reset logic
477 		 *  handle that instead.
478 		 */
479 		if (!STAILQ_EMPTY(&qpair->queued_req) &&
480 		    !qpair->ctrlr->is_resetting) {
481 			req = STAILQ_FIRST(&qpair->queued_req);
482 			STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
483 			_nvme_qpair_submit_request(qpair, req);
484 		}
485 	}
486 
487 	mtx_unlock(&qpair->lock);
488 }
489 
490 static void
491 nvme_qpair_manual_complete_tracker(
492     struct nvme_tracker *tr, uint32_t sct, uint32_t sc, uint32_t dnr,
493     error_print_t print_on_error)
494 {
495 	struct nvme_completion	cpl;
496 
497 	memset(&cpl, 0, sizeof(cpl));
498 
499 	struct nvme_qpair * qpair = tr->qpair;
500 
501 	cpl.sqid = qpair->id;
502 	cpl.cid = tr->cid;
503 	cpl.status |= (sct & NVME_STATUS_SCT_MASK) << NVME_STATUS_SCT_SHIFT;
504 	cpl.status |= (sc & NVME_STATUS_SC_MASK) << NVME_STATUS_SC_SHIFT;
505 	cpl.status |= (dnr & NVME_STATUS_DNR_MASK) << NVME_STATUS_DNR_SHIFT;
506 	/* M=0 : this is artificial so no data in error log page */
507 	/* CRD=0 : this is artificial and no delayed retry support anyway */
508 	/* P=0 : phase not checked */
509 	nvme_qpair_complete_tracker(tr, &cpl, print_on_error);
510 }
511 
512 void
513 nvme_qpair_manual_complete_request(struct nvme_qpair *qpair,
514     struct nvme_request *req, uint32_t sct, uint32_t sc)
515 {
516 	struct nvme_completion	cpl;
517 	bool			error;
518 
519 	memset(&cpl, 0, sizeof(cpl));
520 	cpl.sqid = qpair->id;
521 	cpl.status |= (sct & NVME_STATUS_SCT_MASK) << NVME_STATUS_SCT_SHIFT;
522 	cpl.status |= (sc & NVME_STATUS_SC_MASK) << NVME_STATUS_SC_SHIFT;
523 
524 	error = nvme_completion_is_error(&cpl);
525 
526 	if (error) {
527 		nvme_qpair_print_command(qpair, &req->cmd);
528 		nvme_qpair_print_completion(qpair, &cpl);
529 	}
530 
531 	if (req->cb_fn)
532 		req->cb_fn(req->cb_arg, &cpl);
533 
534 	nvme_free_request(req);
535 }
536 
537 bool
538 nvme_qpair_process_completions(struct nvme_qpair *qpair)
539 {
540 	struct nvme_tracker	*tr;
541 	struct nvme_completion	cpl;
542 	int done = 0;
543 	bool in_panic = dumping || SCHEDULER_STOPPED();
544 
545 	/*
546 	 * qpair is not enabled, likely because a controller reset is in
547 	 * progress.  Ignore the interrupt - any I/O that was associated with
548 	 * this interrupt will get retried when the reset is complete. Any
549 	 * pending completions for when we're in startup will be completed
550 	 * as soon as initialization is complete and we start sending commands
551 	 * to the device.
552 	 */
553 	if (qpair->recovery_state != RECOVERY_NONE) {
554 		qpair->num_ignored++;
555 		return (false);
556 	}
557 
558 	/*
559 	 * Sanity check initialization. After we reset the hardware, the phase
560 	 * is defined to be 1. So if we get here with zero prior calls and the
561 	 * phase is 0, it means that we've lost a race between the
562 	 * initialization and the ISR running. With the phase wrong, we'll
563 	 * process a bunch of completions that aren't really completions leading
564 	 * to a KASSERT below.
565 	 */
566 	KASSERT(!(qpair->num_intr_handler_calls == 0 && qpair->phase == 0),
567 	    ("%s: Phase wrong for first interrupt call.",
568 		device_get_nameunit(qpair->ctrlr->dev)));
569 
570 	qpair->num_intr_handler_calls++;
571 
572 	bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
573 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
574 	/*
575 	 * A panic can stop the CPU this routine is running on at any point.  If
576 	 * we're called during a panic, complete the sq_head wrap protocol for
577 	 * the case where we are interrupted just after the increment at 1
578 	 * below, but before we can reset cq_head to zero at 2. Also cope with
579 	 * the case where we do the zero at 2, but may or may not have done the
580 	 * phase adjustment at step 3. The panic machinery flushes all pending
581 	 * memory writes, so we can make these strong ordering assumptions
582 	 * that would otherwise be unwise if we were racing in real time.
583 	 */
584 	if (__predict_false(in_panic)) {
585 		if (qpair->cq_head == qpair->num_entries) {
586 			/*
587 			 * Here we know that we need to zero cq_head and then negate
588 			 * the phase, which hasn't been assigned if cq_head isn't
589 			 * zero due to the atomic_store_rel.
590 			 */
591 			qpair->cq_head = 0;
592 			qpair->phase = !qpair->phase;
593 		} else if (qpair->cq_head == 0) {
594 			/*
595 			 * In this case, we know that the assignment at 2
596 			 * happened below, but we don't know if it 3 happened or
597 			 * not. To do this, we look at the last completion
598 			 * entry and set the phase to the opposite phase
599 			 * that it has. This gets us back in sync
600 			 */
601 			cpl = qpair->cpl[qpair->num_entries - 1];
602 			nvme_completion_swapbytes(&cpl);
603 			qpair->phase = !NVME_STATUS_GET_P(cpl.status);
604 		}
605 	}
606 
607 	while (1) {
608 		uint16_t status;
609 
610 		/*
611 		 * We need to do this dance to avoid a race between the host and
612 		 * the device where the device overtakes the host while the host
613 		 * is reading this record, leaving the status field 'new' and
614 		 * the sqhd and cid fields potentially stale. If the phase
615 		 * doesn't match, that means status hasn't yet been updated and
616 		 * we'll get any pending changes next time. It also means that
617 		 * the phase must be the same the second time. We have to sync
618 		 * before reading to ensure any bouncing completes.
619 		 */
620 		status = le16toh(qpair->cpl[qpair->cq_head].status);
621 		if (NVME_STATUS_GET_P(status) != qpair->phase)
622 			break;
623 
624 		bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
625 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
626 		cpl = qpair->cpl[qpair->cq_head];
627 		nvme_completion_swapbytes(&cpl);
628 
629 		KASSERT(
630 		    NVME_STATUS_GET_P(status) == NVME_STATUS_GET_P(cpl.status),
631 		    ("Phase unexpectedly inconsistent"));
632 
633 		if (cpl.cid < qpair->num_trackers)
634 			tr = qpair->act_tr[cpl.cid];
635 		else
636 			tr = NULL;
637 
638 		done++;
639 		if (tr != NULL) {
640 			nvme_qpair_complete_tracker(tr, &cpl, ERROR_PRINT_ALL);
641 			qpair->sq_head = cpl.sqhd;
642 		} else if (!in_panic) {
643 			/*
644 			 * A missing tracker is normally an error.  However, a
645 			 * panic can stop the CPU this routine is running on
646 			 * after completing an I/O but before updating
647 			 * qpair->cq_head at 1 below.  Later, we re-enter this
648 			 * routine to poll I/O associated with the kernel
649 			 * dump. We find that the tr has been set to null before
650 			 * calling the completion routine.  If it hasn't
651 			 * completed (or it triggers a panic), then '1' below
652 			 * won't have updated cq_head. Rather than panic again,
653 			 * ignore this condition because it's not unexpected.
654 			 */
655 			nvme_printf(qpair->ctrlr,
656 			    "cpl (cid = %u) does not map to outstanding cmd\n",
657 				cpl.cid);
658 			nvme_qpair_print_completion(qpair,
659 			    &qpair->cpl[qpair->cq_head]);
660 			KASSERT(0, ("received completion for unknown cmd"));
661 		}
662 
663 		/*
664 		 * There's a number of races with the following (see above) when
665 		 * the system panics. We compensate for each one of them by
666 		 * using the atomic store to force strong ordering (at least when
667 		 * viewed in the aftermath of a panic).
668 		 */
669 		if (++qpair->cq_head == qpair->num_entries) {		/* 1 */
670 			atomic_store_rel_int(&qpair->cq_head, 0);	/* 2 */
671 			qpair->phase = !qpair->phase;			/* 3 */
672 		}
673 	}
674 
675 	if (done != 0) {
676 		bus_space_write_4(qpair->ctrlr->bus_tag, qpair->ctrlr->bus_handle,
677 		    qpair->cq_hdbl_off, qpair->cq_head);
678 	}
679 
680 	return (done != 0);
681 }
682 
683 static void
684 nvme_qpair_msi_handler(void *arg)
685 {
686 	struct nvme_qpair *qpair = arg;
687 
688 	nvme_qpair_process_completions(qpair);
689 }
690 
691 int
692 nvme_qpair_construct(struct nvme_qpair *qpair,
693     uint32_t num_entries, uint32_t num_trackers,
694     struct nvme_controller *ctrlr)
695 {
696 	struct nvme_tracker	*tr;
697 	size_t			cmdsz, cplsz, prpsz, allocsz, prpmemsz;
698 	uint64_t		queuemem_phys, prpmem_phys, list_phys;
699 	uint8_t			*queuemem, *prpmem, *prp_list;
700 	int			i, err;
701 
702 	qpair->vector = ctrlr->msi_count > 1 ? qpair->id : 0;
703 	qpair->num_entries = num_entries;
704 	qpair->num_trackers = num_trackers;
705 	qpair->ctrlr = ctrlr;
706 
707 	mtx_init(&qpair->lock, "nvme qpair lock", NULL, MTX_DEF);
708 
709 	/* Note: NVMe PRP format is restricted to 4-byte alignment. */
710 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
711 	    4, ctrlr->page_size, BUS_SPACE_MAXADDR,
712 	    BUS_SPACE_MAXADDR, NULL, NULL, ctrlr->max_xfer_size,
713 	    howmany(ctrlr->max_xfer_size, ctrlr->page_size) + 1,
714 	    ctrlr->page_size, 0,
715 	    NULL, NULL, &qpair->dma_tag_payload);
716 	if (err != 0) {
717 		nvme_printf(ctrlr, "payload tag create failed %d\n", err);
718 		goto out;
719 	}
720 
721 	/*
722 	 * Each component must be page aligned, and individual PRP lists
723 	 * cannot cross a page boundary.
724 	 */
725 	cmdsz = qpair->num_entries * sizeof(struct nvme_command);
726 	cmdsz = roundup2(cmdsz, ctrlr->page_size);
727 	cplsz = qpair->num_entries * sizeof(struct nvme_completion);
728 	cplsz = roundup2(cplsz, ctrlr->page_size);
729 	/*
730 	 * For commands requiring more than 2 PRP entries, one PRP will be
731 	 * embedded in the command (prp1), and the rest of the PRP entries
732 	 * will be in a list pointed to by the command (prp2).
733 	 */
734 	prpsz = sizeof(uint64_t) *
735 	    howmany(ctrlr->max_xfer_size, ctrlr->page_size);
736 	prpmemsz = qpair->num_trackers * prpsz;
737 	allocsz = cmdsz + cplsz + prpmemsz;
738 
739 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
740 	    ctrlr->page_size, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
741 	    allocsz, 1, allocsz, 0, NULL, NULL, &qpair->dma_tag);
742 	if (err != 0) {
743 		nvme_printf(ctrlr, "tag create failed %d\n", err);
744 		goto out;
745 	}
746 	bus_dma_tag_set_domain(qpair->dma_tag, qpair->domain);
747 
748 	if (bus_dmamem_alloc(qpair->dma_tag, (void **)&queuemem,
749 	     BUS_DMA_COHERENT | BUS_DMA_NOWAIT, &qpair->queuemem_map)) {
750 		nvme_printf(ctrlr, "failed to alloc qpair memory\n");
751 		goto out;
752 	}
753 
754 	if (bus_dmamap_load(qpair->dma_tag, qpair->queuemem_map,
755 	    queuemem, allocsz, nvme_single_map, &queuemem_phys, 0) != 0) {
756 		nvme_printf(ctrlr, "failed to load qpair memory\n");
757 		bus_dmamem_free(qpair->dma_tag, qpair->cmd,
758 		    qpair->queuemem_map);
759 		goto out;
760 	}
761 
762 	qpair->num_cmds = 0;
763 	qpair->num_intr_handler_calls = 0;
764 	qpair->num_retries = 0;
765 	qpair->num_failures = 0;
766 	qpair->num_ignored = 0;
767 	qpair->cmd = (struct nvme_command *)queuemem;
768 	qpair->cpl = (struct nvme_completion *)(queuemem + cmdsz);
769 	prpmem = (uint8_t *)(queuemem + cmdsz + cplsz);
770 	qpair->cmd_bus_addr = queuemem_phys;
771 	qpair->cpl_bus_addr = queuemem_phys + cmdsz;
772 	prpmem_phys = queuemem_phys + cmdsz + cplsz;
773 
774 	callout_init(&qpair->timer, 1);
775 	qpair->timer_armed = false;
776 	qpair->recovery_state = RECOVERY_WAITING;
777 
778 	/*
779 	 * Calcuate the stride of the doorbell register. Many emulators set this
780 	 * value to correspond to a cache line. However, some hardware has set
781 	 * it to various small values.
782 	 */
783 	qpair->sq_tdbl_off = nvme_mmio_offsetof(doorbell[0]) +
784 	    (qpair->id << (ctrlr->dstrd + 1));
785 	qpair->cq_hdbl_off = nvme_mmio_offsetof(doorbell[0]) +
786 	    (qpair->id << (ctrlr->dstrd + 1)) + (1 << ctrlr->dstrd);
787 
788 	TAILQ_INIT(&qpair->free_tr);
789 	TAILQ_INIT(&qpair->outstanding_tr);
790 	STAILQ_INIT(&qpair->queued_req);
791 
792 	list_phys = prpmem_phys;
793 	prp_list = prpmem;
794 	for (i = 0; i < qpair->num_trackers; i++) {
795 		if (list_phys + prpsz > prpmem_phys + prpmemsz) {
796 			qpair->num_trackers = i;
797 			break;
798 		}
799 
800 		/*
801 		 * Make sure that the PRP list for this tracker doesn't
802 		 * overflow to another nvme page.
803 		 */
804 		if (trunc_page(list_phys) !=
805 		    trunc_page(list_phys + prpsz - 1)) {
806 			list_phys = roundup2(list_phys, ctrlr->page_size);
807 			prp_list =
808 			    (uint8_t *)roundup2((uintptr_t)prp_list, ctrlr->page_size);
809 		}
810 
811 		tr = malloc_domainset(sizeof(*tr), M_NVME,
812 		    DOMAINSET_PREF(qpair->domain), M_ZERO | M_WAITOK);
813 		bus_dmamap_create(qpair->dma_tag_payload, 0,
814 		    &tr->payload_dma_map);
815 		tr->cid = i;
816 		tr->qpair = qpair;
817 		tr->prp = (uint64_t *)prp_list;
818 		tr->prp_bus_addr = list_phys;
819 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
820 		list_phys += prpsz;
821 		prp_list += prpsz;
822 	}
823 
824 	if (qpair->num_trackers == 0) {
825 		nvme_printf(ctrlr, "failed to allocate enough trackers\n");
826 		goto out;
827 	}
828 
829 	qpair->act_tr = malloc_domainset(sizeof(struct nvme_tracker *) *
830 	    qpair->num_entries, M_NVME, DOMAINSET_PREF(qpair->domain),
831 	    M_ZERO | M_WAITOK);
832 
833 	if (ctrlr->msi_count > 1) {
834 		/*
835 		 * MSI-X vector resource IDs start at 1, so we add one to
836 		 *  the queue's vector to get the corresponding rid to use.
837 		 */
838 		qpair->rid = qpair->vector + 1;
839 
840 		qpair->res = bus_alloc_resource_any(ctrlr->dev, SYS_RES_IRQ,
841 		    &qpair->rid, RF_ACTIVE);
842 		if (qpair->res == NULL) {
843 			nvme_printf(ctrlr, "unable to allocate MSI\n");
844 			goto out;
845 		}
846 		if (bus_setup_intr(ctrlr->dev, qpair->res,
847 		    INTR_TYPE_MISC | INTR_MPSAFE, NULL,
848 		    nvme_qpair_msi_handler, qpair, &qpair->tag) != 0) {
849 			nvme_printf(ctrlr, "unable to setup MSI\n");
850 			goto out;
851 		}
852 		if (qpair->id == 0) {
853 			bus_describe_intr(ctrlr->dev, qpair->res, qpair->tag,
854 			    "admin");
855 		} else {
856 			bus_describe_intr(ctrlr->dev, qpair->res, qpair->tag,
857 			    "io%d", qpair->id - 1);
858 		}
859 	}
860 
861 	return (0);
862 
863 out:
864 	nvme_qpair_destroy(qpair);
865 	return (ENOMEM);
866 }
867 
868 static void
869 nvme_qpair_destroy(struct nvme_qpair *qpair)
870 {
871 	struct nvme_tracker	*tr;
872 
873 	callout_drain(&qpair->timer);
874 
875 	if (qpair->tag) {
876 		bus_teardown_intr(qpair->ctrlr->dev, qpair->res, qpair->tag);
877 		qpair->tag = NULL;
878 	}
879 
880 	if (qpair->act_tr) {
881 		free(qpair->act_tr, M_NVME);
882 		qpair->act_tr = NULL;
883 	}
884 
885 	while (!TAILQ_EMPTY(&qpair->free_tr)) {
886 		tr = TAILQ_FIRST(&qpair->free_tr);
887 		TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
888 		bus_dmamap_destroy(qpair->dma_tag_payload,
889 		    tr->payload_dma_map);
890 		free(tr, M_NVME);
891 	}
892 
893 	if (qpair->cmd != NULL) {
894 		bus_dmamap_unload(qpair->dma_tag, qpair->queuemem_map);
895 		bus_dmamem_free(qpair->dma_tag, qpair->cmd,
896 		    qpair->queuemem_map);
897 		qpair->cmd = NULL;
898 	}
899 
900 	if (qpair->dma_tag) {
901 		bus_dma_tag_destroy(qpair->dma_tag);
902 		qpair->dma_tag = NULL;
903 	}
904 
905 	if (qpair->dma_tag_payload) {
906 		bus_dma_tag_destroy(qpair->dma_tag_payload);
907 		qpair->dma_tag_payload = NULL;
908 	}
909 
910 	if (mtx_initialized(&qpair->lock))
911 		mtx_destroy(&qpair->lock);
912 
913 	if (qpair->res) {
914 		bus_release_resource(qpair->ctrlr->dev, SYS_RES_IRQ,
915 		    rman_get_rid(qpair->res), qpair->res);
916 		qpair->res = NULL;
917 	}
918 }
919 
920 static void
921 nvme_admin_qpair_abort_aers(struct nvme_qpair *qpair)
922 {
923 	struct nvme_tracker	*tr;
924 
925 	tr = TAILQ_FIRST(&qpair->outstanding_tr);
926 	while (tr != NULL) {
927 		if (tr->req->cmd.opc == NVME_OPC_ASYNC_EVENT_REQUEST) {
928 			nvme_qpair_manual_complete_tracker(tr,
929 			    NVME_SCT_GENERIC, NVME_SC_ABORTED_SQ_DELETION, 0,
930 			    ERROR_PRINT_NONE);
931 			tr = TAILQ_FIRST(&qpair->outstanding_tr);
932 		} else {
933 			tr = TAILQ_NEXT(tr, tailq);
934 		}
935 	}
936 }
937 
938 void
939 nvme_admin_qpair_destroy(struct nvme_qpair *qpair)
940 {
941 
942 	nvme_admin_qpair_abort_aers(qpair);
943 	nvme_qpair_destroy(qpair);
944 }
945 
946 void
947 nvme_io_qpair_destroy(struct nvme_qpair *qpair)
948 {
949 
950 	nvme_qpair_destroy(qpair);
951 }
952 
953 static void
954 nvme_qpair_timeout(void *arg)
955 {
956 	struct nvme_qpair	*qpair = arg;
957 	struct nvme_controller	*ctrlr = qpair->ctrlr;
958 	struct nvme_tracker	*tr;
959 	sbintime_t		now;
960 	bool			idle;
961 	uint32_t		csts;
962 	uint8_t			cfs;
963 
964 	mtx_lock(&qpair->lock);
965 	idle = TAILQ_EMPTY(&qpair->outstanding_tr);
966 again:
967 	switch (qpair->recovery_state) {
968 	case RECOVERY_NONE:
969 		if (idle)
970 			break;
971 		now = getsbinuptime();
972 		idle = true;
973 		TAILQ_FOREACH(tr, &qpair->outstanding_tr, tailq) {
974 			if (tr->deadline == SBT_MAX)
975 				continue;
976 			idle = false;
977 			if (now > tr->deadline) {
978 				/*
979 				 * We're now passed our earliest deadline. We
980 				 * need to do expensive things to cope, but next
981 				 * time. Flag that and close the door to any
982 				 * further processing.
983 				 */
984 				qpair->recovery_state = RECOVERY_START;
985 				nvme_printf(ctrlr, "RECOVERY_START %jd vs %jd\n",
986 				    (uintmax_t)now, (uintmax_t)tr->deadline);
987 				break;
988 			}
989 		}
990 		break;
991 	case RECOVERY_START:
992 		/*
993 		 * Read csts to get value of cfs - controller fatal status.
994 		 * If no fatal status, try to call the completion routine, and
995 		 * if completes transactions, report a missed interrupt and
996 		 * return (this may need to be rate limited). Otherwise, if
997 		 * aborts are enabled and the controller is not reporting
998 		 * fatal status, abort the command. Otherwise, just reset the
999 		 * controller and hope for the best.
1000 		 */
1001 		csts = nvme_mmio_read_4(ctrlr, csts);
1002 		cfs = (csts >> NVME_CSTS_REG_CFS_SHIFT) & NVME_CSTS_REG_CFS_MASK;
1003 		if (cfs) {
1004 			nvme_printf(ctrlr, "Controller in fatal status, resetting\n");
1005 			qpair->recovery_state = RECOVERY_RESET;
1006 			goto again;
1007 		}
1008 		mtx_unlock(&qpair->lock);
1009 		if (nvme_qpair_process_completions(qpair)) {
1010 			nvme_printf(ctrlr, "Completions present in output without an interrupt\n");
1011 			qpair->recovery_state = RECOVERY_NONE;
1012 		} else {
1013 			nvme_printf(ctrlr, "timeout with nothing complete, resetting\n");
1014 			qpair->recovery_state = RECOVERY_RESET;
1015 			mtx_lock(&qpair->lock);
1016 			goto again;
1017 		}
1018 		mtx_lock(&qpair->lock);
1019 		break;
1020 	case RECOVERY_RESET:
1021 		/*
1022 		 * If we get here due to a possible surprise hot-unplug event,
1023 		 * then we let nvme_ctrlr_reset confirm and fail the
1024 		 * controller.
1025 		 */
1026 		nvme_printf(ctrlr, "Resetting controller due to a timeout%s.\n",
1027 		    (csts == 0xffffffff) ? " and possible hot unplug" :
1028 		    (cfs ? " and fatal error status" : ""));
1029 		nvme_printf(ctrlr, "RECOVERY_WAITING\n");
1030 		qpair->recovery_state = RECOVERY_WAITING;
1031 		nvme_ctrlr_reset(ctrlr);
1032 		break;
1033 	case RECOVERY_WAITING:
1034 		nvme_printf(ctrlr, "waiting\n");
1035 		break;
1036 	}
1037 
1038 	/*
1039 	 * Rearm the timeout.
1040 	 */
1041 	if (!idle) {
1042 		callout_schedule_sbt(&qpair->timer, SBT_1S / 2, SBT_1S / 2, 0);
1043 	} else {
1044 		qpair->timer_armed = false;
1045 	}
1046 	mtx_unlock(&qpair->lock);
1047 }
1048 
1049 /*
1050  * Submit the tracker to the hardware. Must already be in the
1051  * outstanding queue when called.
1052  */
1053 void
1054 nvme_qpair_submit_tracker(struct nvme_qpair *qpair, struct nvme_tracker *tr)
1055 {
1056 	struct nvme_request	*req;
1057 	struct nvme_controller	*ctrlr;
1058 	int timeout;
1059 
1060 	mtx_assert(&qpair->lock, MA_OWNED);
1061 
1062 	req = tr->req;
1063 	req->cmd.cid = tr->cid;
1064 	qpair->act_tr[tr->cid] = tr;
1065 	ctrlr = qpair->ctrlr;
1066 
1067 	if (req->timeout) {
1068 		if (req->cb_fn == nvme_completion_poll_cb)
1069 			timeout = 1;
1070 		else
1071 			timeout = ctrlr->timeout_period;
1072 		tr->deadline = getsbinuptime() + timeout * SBT_1S;
1073 		if (!qpair->timer_armed) {
1074 			qpair->timer_armed = true;
1075 			callout_reset_sbt_on(&qpair->timer, SBT_1S / 2, SBT_1S / 2,
1076 			    nvme_qpair_timeout, qpair, qpair->cpu, 0);
1077 		}
1078 	} else
1079 		tr->deadline = SBT_MAX;
1080 
1081 	/* Copy the command from the tracker to the submission queue. */
1082 	memcpy(&qpair->cmd[qpair->sq_tail], &req->cmd, sizeof(req->cmd));
1083 
1084 	if (++qpair->sq_tail == qpair->num_entries)
1085 		qpair->sq_tail = 0;
1086 
1087 	bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
1088 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1089 	bus_space_write_4(qpair->ctrlr->bus_tag, qpair->ctrlr->bus_handle,
1090 	    qpair->sq_tdbl_off, qpair->sq_tail);
1091 	qpair->num_cmds++;
1092 }
1093 
1094 static void
1095 nvme_payload_map(void *arg, bus_dma_segment_t *seg, int nseg, int error)
1096 {
1097 	struct nvme_tracker 	*tr = arg;
1098 	uint32_t		cur_nseg;
1099 
1100 	/*
1101 	 * If the mapping operation failed, return immediately.  The caller
1102 	 *  is responsible for detecting the error status and failing the
1103 	 *  tracker manually.
1104 	 */
1105 	if (error != 0) {
1106 		nvme_printf(tr->qpair->ctrlr,
1107 		    "nvme_payload_map err %d\n", error);
1108 		return;
1109 	}
1110 
1111 	/*
1112 	 * Note that we specified ctrlr->page_size for alignment and max
1113 	 * segment size when creating the bus dma tags.  So here we can safely
1114 	 * just transfer each segment to its associated PRP entry.
1115 	 */
1116 	tr->req->cmd.prp1 = htole64(seg[0].ds_addr);
1117 
1118 	if (nseg == 2) {
1119 		tr->req->cmd.prp2 = htole64(seg[1].ds_addr);
1120 	} else if (nseg > 2) {
1121 		cur_nseg = 1;
1122 		tr->req->cmd.prp2 = htole64((uint64_t)tr->prp_bus_addr);
1123 		while (cur_nseg < nseg) {
1124 			tr->prp[cur_nseg-1] =
1125 			    htole64((uint64_t)seg[cur_nseg].ds_addr);
1126 			cur_nseg++;
1127 		}
1128 	} else {
1129 		/*
1130 		 * prp2 should not be used by the controller
1131 		 *  since there is only one segment, but set
1132 		 *  to 0 just to be safe.
1133 		 */
1134 		tr->req->cmd.prp2 = 0;
1135 	}
1136 
1137 	bus_dmamap_sync(tr->qpair->dma_tag_payload, tr->payload_dma_map,
1138 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1139 	nvme_qpair_submit_tracker(tr->qpair, tr);
1140 }
1141 
1142 static void
1143 _nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
1144 {
1145 	struct nvme_tracker	*tr;
1146 	int			err = 0;
1147 
1148 	mtx_assert(&qpair->lock, MA_OWNED);
1149 
1150 	tr = TAILQ_FIRST(&qpair->free_tr);
1151 	req->qpair = qpair;
1152 
1153 	if (tr == NULL || qpair->recovery_state != RECOVERY_NONE) {
1154 		/*
1155 		 * No tracker is available, or the qpair is disabled due to
1156 		 *  an in-progress controller-level reset or controller
1157 		 *  failure.
1158 		 */
1159 
1160 		if (qpair->ctrlr->is_failed) {
1161 			/*
1162 			 * The controller has failed, so fail the request.
1163 			 */
1164 			nvme_qpair_manual_complete_request(qpair, req,
1165 			    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST);
1166 		} else {
1167 			/*
1168 			 * Put the request on the qpair's request queue to be
1169 			 *  processed when a tracker frees up via a command
1170 			 *  completion or when the controller reset is
1171 			 *  completed.
1172 			 */
1173 			STAILQ_INSERT_TAIL(&qpair->queued_req, req, stailq);
1174 		}
1175 		return;
1176 	}
1177 
1178 	TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
1179 	TAILQ_INSERT_TAIL(&qpair->outstanding_tr, tr, tailq);
1180 	tr->deadline = SBT_MAX;
1181 	tr->req = req;
1182 
1183 	if (!req->payload_valid) {
1184 		nvme_qpair_submit_tracker(tr->qpair, tr);
1185 		return;
1186 	}
1187 
1188 	err = bus_dmamap_load_mem(tr->qpair->dma_tag_payload,
1189 	    tr->payload_dma_map, &req->payload, nvme_payload_map, tr, 0);
1190 	if (err != 0) {
1191 		/*
1192 		 * The dmamap operation failed, so we manually fail the
1193 		 *  tracker here with DATA_TRANSFER_ERROR status.
1194 		 *
1195 		 * nvme_qpair_manual_complete_tracker must not be called
1196 		 *  with the qpair lock held.
1197 		 */
1198 		nvme_printf(qpair->ctrlr,
1199 		    "bus_dmamap_load_mem returned 0x%x!\n", err);
1200 		mtx_unlock(&qpair->lock);
1201 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1202 		    NVME_SC_DATA_TRANSFER_ERROR, DO_NOT_RETRY, ERROR_PRINT_ALL);
1203 		mtx_lock(&qpair->lock);
1204 	}
1205 }
1206 
1207 void
1208 nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
1209 {
1210 
1211 	mtx_lock(&qpair->lock);
1212 	_nvme_qpair_submit_request(qpair, req);
1213 	mtx_unlock(&qpair->lock);
1214 }
1215 
1216 static void
1217 nvme_qpair_enable(struct nvme_qpair *qpair)
1218 {
1219 	mtx_assert(&qpair->lock, MA_OWNED);
1220 
1221 	qpair->recovery_state = RECOVERY_NONE;
1222 }
1223 
1224 void
1225 nvme_qpair_reset(struct nvme_qpair *qpair)
1226 {
1227 
1228 	qpair->sq_head = qpair->sq_tail = qpair->cq_head = 0;
1229 
1230 	/*
1231 	 * First time through the completion queue, HW will set phase
1232 	 *  bit on completions to 1.  So set this to 1 here, indicating
1233 	 *  we're looking for a 1 to know which entries have completed.
1234 	 *  we'll toggle the bit each time when the completion queue
1235 	 *  rolls over.
1236 	 */
1237 	qpair->phase = 1;
1238 
1239 	memset(qpair->cmd, 0,
1240 	    qpair->num_entries * sizeof(struct nvme_command));
1241 	memset(qpair->cpl, 0,
1242 	    qpair->num_entries * sizeof(struct nvme_completion));
1243 }
1244 
1245 void
1246 nvme_admin_qpair_enable(struct nvme_qpair *qpair)
1247 {
1248 	struct nvme_tracker		*tr;
1249 	struct nvme_tracker		*tr_temp;
1250 	bool				rpt;
1251 
1252 	/*
1253 	 * Manually abort each outstanding admin command.  Do not retry
1254 	 * admin commands found here, since they will be left over from
1255 	 * a controller reset and its likely the context in which the
1256 	 * command was issued no longer applies.
1257 	 */
1258 	rpt = !TAILQ_EMPTY(&qpair->outstanding_tr);
1259 	if (rpt)
1260 		nvme_printf(qpair->ctrlr,
1261 		    "aborting outstanding admin command\n");
1262 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1263 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1264 		    NVME_SC_ABORTED_BY_REQUEST, DO_NOT_RETRY, ERROR_PRINT_ALL);
1265 	}
1266 	if (rpt)
1267 		nvme_printf(qpair->ctrlr,
1268 		    "done aborting outstanding admin\n");
1269 
1270 	mtx_lock(&qpair->lock);
1271 	nvme_qpair_enable(qpair);
1272 	mtx_unlock(&qpair->lock);
1273 }
1274 
1275 void
1276 nvme_io_qpair_enable(struct nvme_qpair *qpair)
1277 {
1278 	STAILQ_HEAD(, nvme_request)	temp;
1279 	struct nvme_tracker		*tr;
1280 	struct nvme_tracker		*tr_temp;
1281 	struct nvme_request		*req;
1282 	bool				report;
1283 
1284 	/*
1285 	 * Manually abort each outstanding I/O.  This normally results in a
1286 	 * retry, unless the retry count on the associated request has
1287 	 * reached its limit.
1288 	 */
1289 	report = !TAILQ_EMPTY(&qpair->outstanding_tr);
1290 	if (report)
1291 		nvme_printf(qpair->ctrlr, "aborting outstanding i/o\n");
1292 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1293 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1294 		    NVME_SC_ABORTED_BY_REQUEST, 0, ERROR_PRINT_NO_RETRY);
1295 	}
1296 	if (report)
1297 		nvme_printf(qpair->ctrlr, "done aborting outstanding i/o\n");
1298 
1299 	mtx_lock(&qpair->lock);
1300 
1301 	nvme_qpair_enable(qpair);
1302 
1303 	STAILQ_INIT(&temp);
1304 	STAILQ_SWAP(&qpair->queued_req, &temp, nvme_request);
1305 
1306 	report = !STAILQ_EMPTY(&temp);
1307 	if (report)
1308 		nvme_printf(qpair->ctrlr, "resubmitting queued i/o\n");
1309 	while (!STAILQ_EMPTY(&temp)) {
1310 		req = STAILQ_FIRST(&temp);
1311 		STAILQ_REMOVE_HEAD(&temp, stailq);
1312 		nvme_qpair_print_command(qpair, &req->cmd);
1313 		_nvme_qpair_submit_request(qpair, req);
1314 	}
1315 	if (report)
1316 		nvme_printf(qpair->ctrlr, "done resubmitting i/o\n");
1317 
1318 	mtx_unlock(&qpair->lock);
1319 }
1320 
1321 static void
1322 nvme_qpair_disable(struct nvme_qpair *qpair)
1323 {
1324 	struct nvme_tracker	*tr, *tr_temp;
1325 
1326 	mtx_lock(&qpair->lock);
1327 	qpair->recovery_state = RECOVERY_WAITING;
1328 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1329 		tr->deadline = SBT_MAX;
1330 	}
1331 	mtx_unlock(&qpair->lock);
1332 }
1333 
1334 void
1335 nvme_admin_qpair_disable(struct nvme_qpair *qpair)
1336 {
1337 
1338 	nvme_qpair_disable(qpair);
1339 	nvme_admin_qpair_abort_aers(qpair);
1340 }
1341 
1342 void
1343 nvme_io_qpair_disable(struct nvme_qpair *qpair)
1344 {
1345 
1346 	nvme_qpair_disable(qpair);
1347 }
1348 
1349 void
1350 nvme_qpair_fail(struct nvme_qpair *qpair)
1351 {
1352 	struct nvme_tracker		*tr;
1353 	struct nvme_request		*req;
1354 
1355 	if (!mtx_initialized(&qpair->lock))
1356 		return;
1357 
1358 	mtx_lock(&qpair->lock);
1359 
1360 	while (!STAILQ_EMPTY(&qpair->queued_req)) {
1361 		req = STAILQ_FIRST(&qpair->queued_req);
1362 		STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
1363 		nvme_printf(qpair->ctrlr, "failing queued i/o\n");
1364 		mtx_unlock(&qpair->lock);
1365 		nvme_qpair_manual_complete_request(qpair, req, NVME_SCT_GENERIC,
1366 		    NVME_SC_ABORTED_BY_REQUEST);
1367 		mtx_lock(&qpair->lock);
1368 	}
1369 
1370 	/* Manually abort each outstanding I/O. */
1371 	while (!TAILQ_EMPTY(&qpair->outstanding_tr)) {
1372 		tr = TAILQ_FIRST(&qpair->outstanding_tr);
1373 		/*
1374 		 * Do not remove the tracker.  The abort_tracker path will
1375 		 *  do that for us.
1376 		 */
1377 		nvme_printf(qpair->ctrlr, "failing outstanding i/o\n");
1378 		mtx_unlock(&qpair->lock);
1379 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1380 		    NVME_SC_ABORTED_BY_REQUEST, DO_NOT_RETRY, ERROR_PRINT_ALL);
1381 		mtx_lock(&qpair->lock);
1382 	}
1383 
1384 	mtx_unlock(&qpair->lock);
1385 }
1386