xref: /freebsd/sys/dev/nvme/nvme_qpair.c (revision 5ab1c5846ff41be24b1f6beb0317bf8258cd4409)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 
51 	uint16_t	opc;
52 	const char *	str;
53 };
54 
55 static struct nvme_opcode_string admin_opcode[] = {
56 	{ NVME_OPC_DELETE_IO_SQ, "DELETE IO SQ" },
57 	{ NVME_OPC_CREATE_IO_SQ, "CREATE IO SQ" },
58 	{ NVME_OPC_GET_LOG_PAGE, "GET LOG PAGE" },
59 	{ NVME_OPC_DELETE_IO_CQ, "DELETE IO CQ" },
60 	{ NVME_OPC_CREATE_IO_CQ, "CREATE IO CQ" },
61 	{ NVME_OPC_IDENTIFY, "IDENTIFY" },
62 	{ NVME_OPC_ABORT, "ABORT" },
63 	{ NVME_OPC_SET_FEATURES, "SET FEATURES" },
64 	{ NVME_OPC_GET_FEATURES, "GET FEATURES" },
65 	{ NVME_OPC_ASYNC_EVENT_REQUEST, "ASYNC EVENT REQUEST" },
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_DOORBELL_BUFFER_CONFIG, "DOORBELL BUFFER CONFIG" },
77 	{ NVME_OPC_FORMAT_NVM, "FORMAT NVM" },
78 	{ NVME_OPC_SECURITY_SEND, "SECURITY SEND" },
79 	{ NVME_OPC_SECURITY_RECEIVE, "SECURITY RECEIVE" },
80 	{ NVME_OPC_SANITIZE, "SANITIZE" },
81 	{ NVME_OPC_GET_LBA_STATUS, "GET LBA STATUS" },
82 	{ 0xFFFF, "ADMIN COMMAND" }
83 };
84 
85 static struct nvme_opcode_string io_opcode[] = {
86 	{ NVME_OPC_FLUSH, "FLUSH" },
87 	{ NVME_OPC_WRITE, "WRITE" },
88 	{ NVME_OPC_READ, "READ" },
89 	{ NVME_OPC_WRITE_UNCORRECTABLE, "WRITE UNCORRECTABLE" },
90 	{ NVME_OPC_COMPARE, "COMPARE" },
91 	{ NVME_OPC_WRITE_ZEROES, "WRITE ZEROES" },
92 	{ NVME_OPC_DATASET_MANAGEMENT, "DATASET MANAGEMENT" },
93 	{ NVME_OPC_VERIFY, "VERIFY" },
94 	{ NVME_OPC_RESERVATION_REGISTER, "RESERVATION REGISTER" },
95 	{ NVME_OPC_RESERVATION_REPORT, "RESERVATION REPORT" },
96 	{ NVME_OPC_RESERVATION_ACQUIRE, "RESERVATION ACQUIRE" },
97 	{ NVME_OPC_RESERVATION_RELEASE, "RESERVATION RELEASE" },
98 	{ 0xFFFF, "IO COMMAND" }
99 };
100 
101 static const char *
102 get_admin_opcode_string(uint16_t opc)
103 {
104 	struct nvme_opcode_string *entry;
105 
106 	entry = admin_opcode;
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_io_opcode_string(uint16_t opc)
118 {
119 	struct nvme_opcode_string *entry;
120 
121 	entry = io_opcode;
122 
123 	while (entry->opc != 0xFFFF) {
124 		if (entry->opc == opc)
125 			return (entry->str);
126 		entry++;
127 	}
128 	return (entry->str);
129 }
130 
131 
132 static void
133 nvme_admin_qpair_print_command(struct nvme_qpair *qpair,
134     struct nvme_command *cmd)
135 {
136 
137 	nvme_printf(qpair->ctrlr, "%s (%02x) sqid:%d cid:%d nsid:%x "
138 	    "cdw10:%08x cdw11:%08x\n",
139 	    get_admin_opcode_string(cmd->opc), cmd->opc, qpair->id, cmd->cid,
140 	    le32toh(cmd->nsid), le32toh(cmd->cdw10), le32toh(cmd->cdw11));
141 }
142 
143 static void
144 nvme_io_qpair_print_command(struct nvme_qpair *qpair,
145     struct nvme_command *cmd)
146 {
147 
148 	switch (cmd->opc) {
149 	case NVME_OPC_WRITE:
150 	case NVME_OPC_READ:
151 	case NVME_OPC_WRITE_UNCORRECTABLE:
152 	case NVME_OPC_COMPARE:
153 	case NVME_OPC_WRITE_ZEROES:
154 	case NVME_OPC_VERIFY:
155 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d "
156 		    "lba:%llu len:%d\n",
157 		    get_io_opcode_string(cmd->opc), qpair->id, cmd->cid, le32toh(cmd->nsid),
158 		    ((unsigned long long)le32toh(cmd->cdw11) << 32) + le32toh(cmd->cdw10),
159 		    (le32toh(cmd->cdw12) & 0xFFFF) + 1);
160 		break;
161 	case NVME_OPC_FLUSH:
162 	case NVME_OPC_DATASET_MANAGEMENT:
163 	case NVME_OPC_RESERVATION_REGISTER:
164 	case NVME_OPC_RESERVATION_REPORT:
165 	case NVME_OPC_RESERVATION_ACQUIRE:
166 	case NVME_OPC_RESERVATION_RELEASE:
167 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d\n",
168 		    get_io_opcode_string(cmd->opc), qpair->id, cmd->cid, le32toh(cmd->nsid));
169 		break;
170 	default:
171 		nvme_printf(qpair->ctrlr, "%s (%02x) sqid:%d cid:%d nsid:%d\n",
172 		    get_io_opcode_string(cmd->opc), cmd->opc, qpair->id,
173 		    cmd->cid, le32toh(cmd->nsid));
174 		break;
175 	}
176 }
177 
178 static void
179 nvme_qpair_print_command(struct nvme_qpair *qpair, struct nvme_command *cmd)
180 {
181 	if (qpair->id == 0)
182 		nvme_admin_qpair_print_command(qpair, cmd);
183 	else
184 		nvme_io_qpair_print_command(qpair, cmd);
185 	if (nvme_verbose_cmd_dump) {
186 		nvme_printf(qpair->ctrlr,
187 		    "nsid:%#x rsvd2:%#x rsvd3:%#x mptr:%#jx prp1:%#jx prp2:%#jx\n",
188 		    cmd->nsid, cmd->rsvd2, cmd->rsvd3, (uintmax_t)cmd->mptr,
189 		    (uintmax_t)cmd->prp1, (uintmax_t)cmd->prp2);
190 		nvme_printf(qpair->ctrlr,
191 		    "cdw10: %#x cdw11:%#x cdw12:%#x cdw13:%#x cdw14:%#x cdw15:%#x\n",
192 		    cmd->cdw10, cmd->cdw11, cmd->cdw12, cmd->cdw13, cmd->cdw14,
193 		    cmd->cdw15);
194 	}
195 }
196 
197 struct nvme_status_string {
198 
199 	uint16_t	sc;
200 	const char *	str;
201 };
202 
203 static struct nvme_status_string generic_status[] = {
204 	{ NVME_SC_SUCCESS, "SUCCESS" },
205 	{ NVME_SC_INVALID_OPCODE, "INVALID OPCODE" },
206 	{ NVME_SC_INVALID_FIELD, "INVALID_FIELD" },
207 	{ NVME_SC_COMMAND_ID_CONFLICT, "COMMAND ID CONFLICT" },
208 	{ NVME_SC_DATA_TRANSFER_ERROR, "DATA TRANSFER ERROR" },
209 	{ NVME_SC_ABORTED_POWER_LOSS, "ABORTED - POWER LOSS" },
210 	{ NVME_SC_INTERNAL_DEVICE_ERROR, "INTERNAL DEVICE ERROR" },
211 	{ NVME_SC_ABORTED_BY_REQUEST, "ABORTED - BY REQUEST" },
212 	{ NVME_SC_ABORTED_SQ_DELETION, "ABORTED - SQ DELETION" },
213 	{ NVME_SC_ABORTED_FAILED_FUSED, "ABORTED - FAILED FUSED" },
214 	{ NVME_SC_ABORTED_MISSING_FUSED, "ABORTED - MISSING FUSED" },
215 	{ NVME_SC_INVALID_NAMESPACE_OR_FORMAT, "INVALID NAMESPACE OR FORMAT" },
216 	{ NVME_SC_COMMAND_SEQUENCE_ERROR, "COMMAND SEQUENCE ERROR" },
217 	{ NVME_SC_INVALID_SGL_SEGMENT_DESCR, "INVALID SGL SEGMENT DESCRIPTOR" },
218 	{ NVME_SC_INVALID_NUMBER_OF_SGL_DESCR, "INVALID NUMBER OF SGL DESCRIPTORS" },
219 	{ NVME_SC_DATA_SGL_LENGTH_INVALID, "DATA SGL LENGTH INVALID" },
220 	{ NVME_SC_METADATA_SGL_LENGTH_INVALID, "METADATA SGL LENGTH INVALID" },
221 	{ NVME_SC_SGL_DESCRIPTOR_TYPE_INVALID, "SGL DESCRIPTOR TYPE INVALID" },
222 	{ NVME_SC_INVALID_USE_OF_CMB, "INVALID USE OF CONTROLLER MEMORY BUFFER" },
223 	{ NVME_SC_PRP_OFFET_INVALID, "PRP OFFET INVALID" },
224 	{ NVME_SC_ATOMIC_WRITE_UNIT_EXCEEDED, "ATOMIC WRITE UNIT EXCEEDED" },
225 	{ NVME_SC_OPERATION_DENIED, "OPERATION DENIED" },
226 	{ NVME_SC_SGL_OFFSET_INVALID, "SGL OFFSET INVALID" },
227 	{ NVME_SC_HOST_ID_INCONSISTENT_FORMAT, "HOST IDENTIFIER INCONSISTENT FORMAT" },
228 	{ NVME_SC_KEEP_ALIVE_TIMEOUT_EXPIRED, "KEEP ALIVE TIMEOUT EXPIRED" },
229 	{ NVME_SC_KEEP_ALIVE_TIMEOUT_INVALID, "KEEP ALIVE TIMEOUT INVALID" },
230 	{ NVME_SC_ABORTED_DUE_TO_PREEMPT, "COMMAND ABORTED DUE TO PREEMPT AND ABORT" },
231 	{ NVME_SC_SANITIZE_FAILED, "SANITIZE FAILED" },
232 	{ NVME_SC_SANITIZE_IN_PROGRESS, "SANITIZE IN PROGRESS" },
233 	{ NVME_SC_SGL_DATA_BLOCK_GRAN_INVALID, "SGL_DATA_BLOCK_GRANULARITY_INVALID" },
234 	{ NVME_SC_NOT_SUPPORTED_IN_CMB, "COMMAND NOT SUPPORTED FOR QUEUE IN CMB" },
235 	{ NVME_SC_NAMESPACE_IS_WRITE_PROTECTED, "NAMESPACE IS WRITE PROTECTED" },
236 	{ NVME_SC_COMMAND_INTERRUPTED, "COMMAND INTERRUPTED" },
237 	{ NVME_SC_TRANSIENT_TRANSPORT_ERROR, "TRANSIENT TRANSPORT ERROR" },
238 
239 	{ NVME_SC_LBA_OUT_OF_RANGE, "LBA OUT OF RANGE" },
240 	{ NVME_SC_CAPACITY_EXCEEDED, "CAPACITY EXCEEDED" },
241 	{ NVME_SC_NAMESPACE_NOT_READY, "NAMESPACE NOT READY" },
242 	{ NVME_SC_RESERVATION_CONFLICT, "RESERVATION CONFLICT" },
243 	{ NVME_SC_FORMAT_IN_PROGRESS, "FORMAT IN PROGRESS" },
244 	{ 0xFFFF, "GENERIC" }
245 };
246 
247 static struct nvme_status_string command_specific_status[] = {
248 	{ NVME_SC_COMPLETION_QUEUE_INVALID, "INVALID COMPLETION QUEUE" },
249 	{ NVME_SC_INVALID_QUEUE_IDENTIFIER, "INVALID QUEUE IDENTIFIER" },
250 	{ NVME_SC_MAXIMUM_QUEUE_SIZE_EXCEEDED, "MAX QUEUE SIZE EXCEEDED" },
251 	{ NVME_SC_ABORT_COMMAND_LIMIT_EXCEEDED, "ABORT CMD LIMIT EXCEEDED" },
252 	{ NVME_SC_ASYNC_EVENT_REQUEST_LIMIT_EXCEEDED, "ASYNC LIMIT EXCEEDED" },
253 	{ NVME_SC_INVALID_FIRMWARE_SLOT, "INVALID FIRMWARE SLOT" },
254 	{ NVME_SC_INVALID_FIRMWARE_IMAGE, "INVALID FIRMWARE IMAGE" },
255 	{ NVME_SC_INVALID_INTERRUPT_VECTOR, "INVALID INTERRUPT VECTOR" },
256 	{ NVME_SC_INVALID_LOG_PAGE, "INVALID LOG PAGE" },
257 	{ NVME_SC_INVALID_FORMAT, "INVALID FORMAT" },
258 	{ NVME_SC_FIRMWARE_REQUIRES_RESET, "FIRMWARE REQUIRES RESET" },
259 	{ NVME_SC_INVALID_QUEUE_DELETION, "INVALID QUEUE DELETION" },
260 	{ NVME_SC_FEATURE_NOT_SAVEABLE, "FEATURE IDENTIFIER NOT SAVEABLE" },
261 	{ NVME_SC_FEATURE_NOT_CHANGEABLE, "FEATURE NOT CHANGEABLE" },
262 	{ NVME_SC_FEATURE_NOT_NS_SPECIFIC, "FEATURE NOT NAMESPACE SPECIFIC" },
263 	{ NVME_SC_FW_ACT_REQUIRES_NVMS_RESET, "FIRMWARE ACTIVATION REQUIRES NVM SUBSYSTEM RESET" },
264 	{ NVME_SC_FW_ACT_REQUIRES_RESET, "FIRMWARE ACTIVATION REQUIRES RESET" },
265 	{ NVME_SC_FW_ACT_REQUIRES_TIME, "FIRMWARE ACTIVATION REQUIRES MAXIMUM TIME VIOLATION" },
266 	{ NVME_SC_FW_ACT_PROHIBITED, "FIRMWARE ACTIVATION PROHIBITED" },
267 	{ NVME_SC_OVERLAPPING_RANGE, "OVERLAPPING RANGE" },
268 	{ NVME_SC_NS_INSUFFICIENT_CAPACITY, "NAMESPACE INSUFFICIENT CAPACITY" },
269 	{ NVME_SC_NS_ID_UNAVAILABLE, "NAMESPACE IDENTIFIER UNAVAILABLE" },
270 	{ NVME_SC_NS_ALREADY_ATTACHED, "NAMESPACE ALREADY ATTACHED" },
271 	{ NVME_SC_NS_IS_PRIVATE, "NAMESPACE IS PRIVATE" },
272 	{ NVME_SC_NS_NOT_ATTACHED, "NS NOT ATTACHED" },
273 	{ NVME_SC_THIN_PROV_NOT_SUPPORTED, "THIN PROVISIONING NOT SUPPORTED" },
274 	{ NVME_SC_CTRLR_LIST_INVALID, "CONTROLLER LIST INVALID" },
275 	{ NVME_SC_SELT_TEST_IN_PROGRESS, "DEVICE SELT-TEST IN PROGRESS" },
276 	{ NVME_SC_BOOT_PART_WRITE_PROHIB, "BOOT PARTITION WRITE PROHIBITED" },
277 	{ NVME_SC_INVALID_CTRLR_ID, "INVALID CONTROLLER IDENTIFIER" },
278 	{ NVME_SC_INVALID_SEC_CTRLR_STATE, "INVALID SECONDARY CONTROLLER STATE" },
279 	{ NVME_SC_INVALID_NUM_OF_CTRLR_RESRC, "INVALID NUMBER OF CONTROLLER RESOURCES" },
280 	{ NVME_SC_INVALID_RESOURCE_ID, "INVALID RESOURCE IDENTIFIER" },
281 	{ NVME_SC_SANITIZE_PROHIBITED_WPMRE, "SANITIZE PROHIBITED WRITE PERSISTENT MEMORY REGION ENABLED" },
282 	{ NVME_SC_ANA_GROUP_ID_INVALID, "ANA GROUP IDENTIFIED INVALID" },
283 	{ NVME_SC_ANA_ATTACH_FAILED, "ANA ATTACH FAILED" },
284 
285 	{ NVME_SC_CONFLICTING_ATTRIBUTES, "CONFLICTING ATTRIBUTES" },
286 	{ NVME_SC_INVALID_PROTECTION_INFO, "INVALID PROTECTION INFO" },
287 	{ NVME_SC_ATTEMPTED_WRITE_TO_RO_PAGE, "WRITE TO RO PAGE" },
288 	{ 0xFFFF, "COMMAND SPECIFIC" }
289 };
290 
291 static struct nvme_status_string media_error_status[] = {
292 	{ NVME_SC_WRITE_FAULTS, "WRITE FAULTS" },
293 	{ NVME_SC_UNRECOVERED_READ_ERROR, "UNRECOVERED READ ERROR" },
294 	{ NVME_SC_GUARD_CHECK_ERROR, "GUARD CHECK ERROR" },
295 	{ NVME_SC_APPLICATION_TAG_CHECK_ERROR, "APPLICATION TAG CHECK ERROR" },
296 	{ NVME_SC_REFERENCE_TAG_CHECK_ERROR, "REFERENCE TAG CHECK ERROR" },
297 	{ NVME_SC_COMPARE_FAILURE, "COMPARE FAILURE" },
298 	{ NVME_SC_ACCESS_DENIED, "ACCESS DENIED" },
299 	{ NVME_SC_DEALLOCATED_OR_UNWRITTEN, "DEALLOCATED OR UNWRITTEN LOGICAL BLOCK" },
300 	{ 0xFFFF, "MEDIA ERROR" }
301 };
302 
303 static struct nvme_status_string path_related_status[] = {
304 	{ NVME_SC_INTERNAL_PATH_ERROR, "INTERNAL PATH ERROR" },
305 	{ NVME_SC_ASYMMETRIC_ACCESS_PERSISTENT_LOSS, "ASYMMETRIC ACCESS PERSISTENT LOSS" },
306 	{ NVME_SC_ASYMMETRIC_ACCESS_INACCESSIBLE, "ASYMMETRIC ACCESS INACCESSIBLE" },
307 	{ NVME_SC_ASYMMETRIC_ACCESS_TRANSITION, "ASYMMETRIC ACCESS TRANSITION" },
308 	{ NVME_SC_CONTROLLER_PATHING_ERROR, "CONTROLLER PATHING ERROR" },
309 	{ NVME_SC_HOST_PATHING_ERROR, "HOST PATHING ERROR" },
310 	{ NVME_SC_COMMAND_ABOTHED_BY_HOST, "COMMAND ABOTHED BY HOST" },
311 	{ 0xFFFF, "PATH RELATED" },
312 };
313 
314 static const char *
315 get_status_string(uint16_t sct, uint16_t sc)
316 {
317 	struct nvme_status_string *entry;
318 
319 	switch (sct) {
320 	case NVME_SCT_GENERIC:
321 		entry = generic_status;
322 		break;
323 	case NVME_SCT_COMMAND_SPECIFIC:
324 		entry = command_specific_status;
325 		break;
326 	case NVME_SCT_MEDIA_ERROR:
327 		entry = media_error_status;
328 		break;
329 	case NVME_SCT_PATH_RELATED:
330 		entry = path_related_status;
331 		break;
332 	case NVME_SCT_VENDOR_SPECIFIC:
333 		return ("VENDOR SPECIFIC");
334 	default:
335 		return ("RESERVED");
336 	}
337 
338 	while (entry->sc != 0xFFFF) {
339 		if (entry->sc == sc)
340 			return (entry->str);
341 		entry++;
342 	}
343 	return (entry->str);
344 }
345 
346 static void
347 nvme_qpair_print_completion(struct nvme_qpair *qpair,
348     struct nvme_completion *cpl)
349 {
350 	uint16_t sct, sc;
351 
352 	sct = NVME_STATUS_GET_SCT(cpl->status);
353 	sc = NVME_STATUS_GET_SC(cpl->status);
354 
355 	nvme_printf(qpair->ctrlr, "%s (%02x/%02x) sqid:%d cid:%d cdw0:%x\n",
356 	    get_status_string(sct, sc), sct, sc, cpl->sqid, cpl->cid,
357 	    cpl->cdw0);
358 }
359 
360 static boolean_t
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 	boolean_t		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 (req->cb_fn && !retry)
448 		req->cb_fn(req->cb_arg, cpl);
449 
450 	mtx_lock(&qpair->lock);
451 	callout_stop(&tr->timer);
452 
453 	if (retry) {
454 		req->retries++;
455 		nvme_qpair_submit_tracker(qpair, tr);
456 	} else {
457 		if (req->type != NVME_REQUEST_NULL) {
458 			bus_dmamap_sync(qpair->dma_tag_payload,
459 			    tr->payload_dma_map,
460 			    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
461 			bus_dmamap_unload(qpair->dma_tag_payload,
462 			    tr->payload_dma_map);
463 		}
464 
465 		nvme_free_request(req);
466 		tr->req = NULL;
467 
468 		TAILQ_REMOVE(&qpair->outstanding_tr, tr, tailq);
469 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
470 
471 		/*
472 		 * If the controller is in the middle of resetting, don't
473 		 *  try to submit queued requests here - let the reset logic
474 		 *  handle that instead.
475 		 */
476 		if (!STAILQ_EMPTY(&qpair->queued_req) &&
477 		    !qpair->ctrlr->is_resetting) {
478 			req = STAILQ_FIRST(&qpair->queued_req);
479 			STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
480 			_nvme_qpair_submit_request(qpair, req);
481 		}
482 	}
483 
484 	mtx_unlock(&qpair->lock);
485 }
486 
487 static void
488 nvme_qpair_manual_complete_tracker(
489     struct nvme_tracker *tr, uint32_t sct, uint32_t sc, uint32_t dnr,
490     error_print_t print_on_error)
491 {
492 	struct nvme_completion	cpl;
493 
494 	memset(&cpl, 0, sizeof(cpl));
495 
496 	struct nvme_qpair * qpair = tr->qpair;
497 
498 	cpl.sqid = qpair->id;
499 	cpl.cid = tr->cid;
500 	cpl.status |= (sct & NVME_STATUS_SCT_MASK) << NVME_STATUS_SCT_SHIFT;
501 	cpl.status |= (sc & NVME_STATUS_SC_MASK) << NVME_STATUS_SC_SHIFT;
502 	cpl.status |= (dnr & NVME_STATUS_DNR_MASK) << NVME_STATUS_DNR_SHIFT;
503 	nvme_qpair_complete_tracker(tr, &cpl, print_on_error);
504 }
505 
506 void
507 nvme_qpair_manual_complete_request(struct nvme_qpair *qpair,
508     struct nvme_request *req, uint32_t sct, uint32_t sc)
509 {
510 	struct nvme_completion	cpl;
511 	boolean_t		error;
512 
513 	memset(&cpl, 0, sizeof(cpl));
514 	cpl.sqid = qpair->id;
515 	cpl.status |= (sct & NVME_STATUS_SCT_MASK) << NVME_STATUS_SCT_SHIFT;
516 	cpl.status |= (sc & NVME_STATUS_SC_MASK) << NVME_STATUS_SC_SHIFT;
517 
518 	error = nvme_completion_is_error(&cpl);
519 
520 	if (error) {
521 		nvme_qpair_print_command(qpair, &req->cmd);
522 		nvme_qpair_print_completion(qpair, &cpl);
523 	}
524 
525 	if (req->cb_fn)
526 		req->cb_fn(req->cb_arg, &cpl);
527 
528 	nvme_free_request(req);
529 }
530 
531 bool
532 nvme_qpair_process_completions(struct nvme_qpair *qpair)
533 {
534 	struct nvme_tracker	*tr;
535 	struct nvme_completion	cpl;
536 	int done = 0;
537 	bool in_panic = dumping || SCHEDULER_STOPPED();
538 
539 	qpair->num_intr_handler_calls++;
540 
541 	/*
542 	 * qpair is not enabled, likely because a controller reset is is in
543 	 * progress.  Ignore the interrupt - any I/O that was associated with
544 	 * this interrupt will get retried when the reset is complete.
545 	 */
546 	if (!qpair->is_enabled)
547 		return (false);
548 
549 	/*
550 	 * A panic can stop the CPU this routine is running on at any point.  If
551 	 * we're called during a panic, complete the sq_head wrap protocol for
552 	 * the case where we are interrupted just after the increment at 1
553 	 * below, but before we can reset cq_head to zero at 2. Also cope with
554 	 * the case where we do the zero at 2, but may or may not have done the
555 	 * phase adjustment at step 3. The panic machinery flushes all pending
556 	 * memory writes, so we can make these strong ordering assumptions
557 	 * that would otherwise be unwise if we were racing in real time.
558 	 */
559 	if (__predict_false(in_panic)) {
560 		if (qpair->cq_head == qpair->num_entries) {
561 			/*
562 			 * Here we know that we need to zero cq_head and then negate
563 			 * the phase, which hasn't been assigned if cq_head isn't
564 			 * zero due to the atomic_store_rel.
565 			 */
566 			qpair->cq_head = 0;
567 			qpair->phase = !qpair->phase;
568 		} else if (qpair->cq_head == 0) {
569 			/*
570 			 * In this case, we know that the assignment at 2
571 			 * happened below, but we don't know if it 3 happened or
572 			 * not. To do this, we look at the last completion
573 			 * entry and set the phase to the opposite phase
574 			 * that it has. This gets us back in sync
575 			 */
576 			cpl = qpair->cpl[qpair->num_entries - 1];
577 			nvme_completion_swapbytes(&cpl);
578 			qpair->phase = !NVME_STATUS_GET_P(cpl.status);
579 		}
580 	}
581 
582 	bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
583 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
584 	while (1) {
585 		cpl = qpair->cpl[qpair->cq_head];
586 
587 		/* Convert to host endian */
588 		nvme_completion_swapbytes(&cpl);
589 
590 		if (NVME_STATUS_GET_P(cpl.status) != qpair->phase)
591 			break;
592 
593 		tr = qpair->act_tr[cpl.cid];
594 
595 		if (tr != NULL) {
596 			nvme_qpair_complete_tracker(tr, &cpl, ERROR_PRINT_ALL);
597 			qpair->sq_head = cpl.sqhd;
598 			done++;
599 		} else if (!in_panic) {
600 			/*
601 			 * A missing tracker is normally an error.  However, a
602 			 * panic can stop the CPU this routine is running on
603 			 * after completing an I/O but before updating
604 			 * qpair->cq_head at 1 below.  Later, we re-enter this
605 			 * routine to poll I/O associated with the kernel
606 			 * dump. We find that the tr has been set to null before
607 			 * calling the completion routine.  If it hasn't
608 			 * completed (or it triggers a panic), then '1' below
609 			 * won't have updated cq_head. Rather than panic again,
610 			 * ignore this condition because it's not unexpected.
611 			 */
612 			nvme_printf(qpair->ctrlr,
613 			    "cpl does not map to outstanding cmd\n");
614 			/* nvme_dump_completion expects device endianess */
615 			nvme_dump_completion(&qpair->cpl[qpair->cq_head]);
616 			KASSERT(0, ("received completion for unknown cmd"));
617 		}
618 
619 		/*
620 		 * There's a number of races with the following (see above) when
621 		 * the system panics. We compensate for each one of them by
622 		 * using the atomic store to force strong ordering (at least when
623 		 * viewed in the aftermath of a panic).
624 		 */
625 		if (++qpair->cq_head == qpair->num_entries) {		/* 1 */
626 			atomic_store_rel_int(&qpair->cq_head, 0);	/* 2 */
627 			qpair->phase = !qpair->phase;			/* 3 */
628 		}
629 
630 		bus_space_write_4(qpair->ctrlr->bus_tag, qpair->ctrlr->bus_handle,
631 		    qpair->cq_hdbl_off, qpair->cq_head);
632 	}
633 	return (done != 0);
634 }
635 
636 static void
637 nvme_qpair_msix_handler(void *arg)
638 {
639 	struct nvme_qpair *qpair = arg;
640 
641 	nvme_qpair_process_completions(qpair);
642 }
643 
644 int
645 nvme_qpair_construct(struct nvme_qpair *qpair,
646     uint32_t num_entries, uint32_t num_trackers,
647     struct nvme_controller *ctrlr)
648 {
649 	struct nvme_tracker	*tr;
650 	size_t			cmdsz, cplsz, prpsz, allocsz, prpmemsz;
651 	uint64_t		queuemem_phys, prpmem_phys, list_phys;
652 	uint8_t			*queuemem, *prpmem, *prp_list;
653 	int			i, err;
654 
655 	qpair->vector = ctrlr->msix_enabled ? qpair->id : 0;
656 	qpair->num_entries = num_entries;
657 	qpair->num_trackers = num_trackers;
658 	qpair->ctrlr = ctrlr;
659 
660 	if (ctrlr->msix_enabled) {
661 
662 		/*
663 		 * MSI-X vector resource IDs start at 1, so we add one to
664 		 *  the queue's vector to get the corresponding rid to use.
665 		 */
666 		qpair->rid = qpair->vector + 1;
667 
668 		qpair->res = bus_alloc_resource_any(ctrlr->dev, SYS_RES_IRQ,
669 		    &qpair->rid, RF_ACTIVE);
670 		bus_setup_intr(ctrlr->dev, qpair->res,
671 		    INTR_TYPE_MISC | INTR_MPSAFE, NULL,
672 		    nvme_qpair_msix_handler, qpair, &qpair->tag);
673 		if (qpair->id == 0) {
674 			bus_describe_intr(ctrlr->dev, qpair->res, qpair->tag,
675 			    "admin");
676 		} else {
677 			bus_describe_intr(ctrlr->dev, qpair->res, qpair->tag,
678 			    "io%d", qpair->id - 1);
679 		}
680 	}
681 
682 	mtx_init(&qpair->lock, "nvme qpair lock", NULL, MTX_DEF);
683 
684 	/* Note: NVMe PRP format is restricted to 4-byte alignment. */
685 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
686 	    4, PAGE_SIZE, BUS_SPACE_MAXADDR,
687 	    BUS_SPACE_MAXADDR, NULL, NULL, NVME_MAX_XFER_SIZE,
688 	    (NVME_MAX_XFER_SIZE/PAGE_SIZE)+1, PAGE_SIZE, 0,
689 	    NULL, NULL, &qpair->dma_tag_payload);
690 	if (err != 0) {
691 		nvme_printf(ctrlr, "payload tag create failed %d\n", err);
692 		goto out;
693 	}
694 
695 	/*
696 	 * Each component must be page aligned, and individual PRP lists
697 	 * cannot cross a page boundary.
698 	 */
699 	cmdsz = qpair->num_entries * sizeof(struct nvme_command);
700 	cmdsz = roundup2(cmdsz, PAGE_SIZE);
701 	cplsz = qpair->num_entries * sizeof(struct nvme_completion);
702 	cplsz = roundup2(cplsz, PAGE_SIZE);
703 	prpsz = sizeof(uint64_t) * NVME_MAX_PRP_LIST_ENTRIES;;
704 	prpmemsz = qpair->num_trackers * prpsz;
705 	allocsz = cmdsz + cplsz + prpmemsz;
706 
707 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
708 	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
709 	    allocsz, 1, allocsz, 0, NULL, NULL, &qpair->dma_tag);
710 	if (err != 0) {
711 		nvme_printf(ctrlr, "tag create failed %d\n", err);
712 		goto out;
713 	}
714 	bus_dma_tag_set_domain(qpair->dma_tag, qpair->domain);
715 
716 	if (bus_dmamem_alloc(qpair->dma_tag, (void **)&queuemem,
717 	    BUS_DMA_NOWAIT, &qpair->queuemem_map)) {
718 		nvme_printf(ctrlr, "failed to alloc qpair memory\n");
719 		goto out;
720 	}
721 
722 	if (bus_dmamap_load(qpair->dma_tag, qpair->queuemem_map,
723 	    queuemem, allocsz, nvme_single_map, &queuemem_phys, 0) != 0) {
724 		nvme_printf(ctrlr, "failed to load qpair memory\n");
725 		goto out;
726 	}
727 
728 	qpair->num_cmds = 0;
729 	qpair->num_intr_handler_calls = 0;
730 	qpair->num_retries = 0;
731 	qpair->num_failures = 0;
732 	qpair->cmd = (struct nvme_command *)queuemem;
733 	qpair->cpl = (struct nvme_completion *)(queuemem + cmdsz);
734 	prpmem = (uint8_t *)(queuemem + cmdsz + cplsz);
735 	qpair->cmd_bus_addr = queuemem_phys;
736 	qpair->cpl_bus_addr = queuemem_phys + cmdsz;
737 	prpmem_phys = queuemem_phys + cmdsz + cplsz;
738 
739 	/*
740 	 * Calcuate the stride of the doorbell register. Many emulators set this
741 	 * value to correspond to a cache line. However, some hardware has set
742 	 * it to various small values.
743 	 */
744 	qpair->sq_tdbl_off = nvme_mmio_offsetof(doorbell[0]) +
745 	    (qpair->id << (ctrlr->dstrd + 1));
746 	qpair->cq_hdbl_off = nvme_mmio_offsetof(doorbell[0]) +
747 	    (qpair->id << (ctrlr->dstrd + 1)) + (1 << ctrlr->dstrd);
748 
749 	TAILQ_INIT(&qpair->free_tr);
750 	TAILQ_INIT(&qpair->outstanding_tr);
751 	STAILQ_INIT(&qpair->queued_req);
752 
753 	list_phys = prpmem_phys;
754 	prp_list = prpmem;
755 	for (i = 0; i < qpair->num_trackers; i++) {
756 
757 		if (list_phys + prpsz > prpmem_phys + prpmemsz) {
758 			qpair->num_trackers = i;
759 			break;
760 		}
761 
762 		/*
763 		 * Make sure that the PRP list for this tracker doesn't
764 		 * overflow to another page.
765 		 */
766 		if (trunc_page(list_phys) !=
767 		    trunc_page(list_phys + prpsz - 1)) {
768 			list_phys = roundup2(list_phys, PAGE_SIZE);
769 			prp_list =
770 			    (uint8_t *)roundup2((uintptr_t)prp_list, PAGE_SIZE);
771 		}
772 
773 		tr = malloc_domainset(sizeof(*tr), M_NVME,
774 		    DOMAINSET_PREF(qpair->domain), M_ZERO | M_WAITOK);
775 		bus_dmamap_create(qpair->dma_tag_payload, 0,
776 		    &tr->payload_dma_map);
777 		callout_init(&tr->timer, 1);
778 		tr->cid = i;
779 		tr->qpair = qpair;
780 		tr->prp = (uint64_t *)prp_list;
781 		tr->prp_bus_addr = list_phys;
782 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
783 		list_phys += prpsz;
784 		prp_list += prpsz;
785 	}
786 
787 	if (qpair->num_trackers == 0) {
788 		nvme_printf(ctrlr, "failed to allocate enough trackers\n");
789 		goto out;
790 	}
791 
792 	qpair->act_tr = malloc_domainset(sizeof(struct nvme_tracker *) *
793 	    qpair->num_entries, M_NVME, DOMAINSET_PREF(qpair->domain),
794 	    M_ZERO | M_WAITOK);
795 	return (0);
796 
797 out:
798 	nvme_qpair_destroy(qpair);
799 	return (ENOMEM);
800 }
801 
802 static void
803 nvme_qpair_destroy(struct nvme_qpair *qpair)
804 {
805 	struct nvme_tracker	*tr;
806 
807 	if (qpair->tag)
808 		bus_teardown_intr(qpair->ctrlr->dev, qpair->res, qpair->tag);
809 
810 	if (mtx_initialized(&qpair->lock))
811 		mtx_destroy(&qpair->lock);
812 
813 	if (qpair->res)
814 		bus_release_resource(qpair->ctrlr->dev, SYS_RES_IRQ,
815 		    rman_get_rid(qpair->res), qpair->res);
816 
817 	if (qpair->cmd != NULL) {
818 		bus_dmamap_unload(qpair->dma_tag, qpair->queuemem_map);
819 		bus_dmamem_free(qpair->dma_tag, qpair->cmd,
820 		    qpair->queuemem_map);
821 	}
822 
823 	if (qpair->act_tr)
824 		free_domain(qpair->act_tr, M_NVME);
825 
826 	while (!TAILQ_EMPTY(&qpair->free_tr)) {
827 		tr = TAILQ_FIRST(&qpair->free_tr);
828 		TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
829 		bus_dmamap_destroy(qpair->dma_tag_payload,
830 		    tr->payload_dma_map);
831 		free_domain(tr, M_NVME);
832 	}
833 
834 	if (qpair->dma_tag)
835 		bus_dma_tag_destroy(qpair->dma_tag);
836 
837 	if (qpair->dma_tag_payload)
838 		bus_dma_tag_destroy(qpair->dma_tag_payload);
839 }
840 
841 static void
842 nvme_admin_qpair_abort_aers(struct nvme_qpair *qpair)
843 {
844 	struct nvme_tracker	*tr;
845 
846 	tr = TAILQ_FIRST(&qpair->outstanding_tr);
847 	while (tr != NULL) {
848 		if (tr->req->cmd.opc == NVME_OPC_ASYNC_EVENT_REQUEST) {
849 			nvme_qpair_manual_complete_tracker(tr,
850 			    NVME_SCT_GENERIC, NVME_SC_ABORTED_SQ_DELETION, 0,
851 			    ERROR_PRINT_NONE);
852 			tr = TAILQ_FIRST(&qpair->outstanding_tr);
853 		} else {
854 			tr = TAILQ_NEXT(tr, tailq);
855 		}
856 	}
857 }
858 
859 void
860 nvme_admin_qpair_destroy(struct nvme_qpair *qpair)
861 {
862 
863 	nvme_admin_qpair_abort_aers(qpair);
864 	nvme_qpair_destroy(qpair);
865 }
866 
867 void
868 nvme_io_qpair_destroy(struct nvme_qpair *qpair)
869 {
870 
871 	nvme_qpair_destroy(qpair);
872 }
873 
874 static void
875 nvme_abort_complete(void *arg, const struct nvme_completion *status)
876 {
877 	struct nvme_tracker	*tr = arg;
878 
879 	/*
880 	 * If cdw0 == 1, the controller was not able to abort the command
881 	 *  we requested.  We still need to check the active tracker array,
882 	 *  to cover race where I/O timed out at same time controller was
883 	 *  completing the I/O.
884 	 */
885 	if (status->cdw0 == 1 && tr->qpair->act_tr[tr->cid] != NULL) {
886 		/*
887 		 * An I/O has timed out, and the controller was unable to
888 		 *  abort it for some reason.  Construct a fake completion
889 		 *  status, and then complete the I/O's tracker manually.
890 		 */
891 		nvme_printf(tr->qpair->ctrlr,
892 		    "abort command failed, aborting command manually\n");
893 		nvme_qpair_manual_complete_tracker(tr,
894 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST, 0, ERROR_PRINT_ALL);
895 	}
896 }
897 
898 static void
899 nvme_timeout(void *arg)
900 {
901 	struct nvme_tracker	*tr = arg;
902 	struct nvme_qpair	*qpair = tr->qpair;
903 	struct nvme_controller	*ctrlr = qpair->ctrlr;
904 	uint32_t		csts;
905 	uint8_t			cfs;
906 
907 	/*
908 	 * Read csts to get value of cfs - controller fatal status.
909 	 * If no fatal status, try to call the completion routine, and
910 	 * if completes transactions, report a missed interrupt and
911 	 * return (this may need to be rate limited). Otherwise, if
912 	 * aborts are enabled and the controller is not reporting
913 	 * fatal status, abort the command. Otherwise, just reset the
914 	 * controller and hope for the best.
915 	 */
916 	csts = nvme_mmio_read_4(ctrlr, csts);
917 	cfs = (csts >> NVME_CSTS_REG_CFS_SHIFT) & NVME_CSTS_REG_CFS_MASK;
918 	if (cfs == 0 && nvme_qpair_process_completions(qpair)) {
919 		nvme_printf(ctrlr, "Missing interrupt\n");
920 		return;
921 	}
922 	if (ctrlr->enable_aborts && cfs == 0) {
923 		nvme_printf(ctrlr, "Aborting command due to a timeout.\n");
924 		nvme_ctrlr_cmd_abort(ctrlr, tr->cid, qpair->id,
925 		    nvme_abort_complete, tr);
926 	} else {
927 		nvme_printf(ctrlr, "Resetting controller due to a timeout%s.\n",
928 		    (csts == 0xffffffff) ? " and possible hot unplug" :
929 		    (cfs ? " and fatal error status" : ""));
930 		nvme_ctrlr_reset(ctrlr);
931 	}
932 }
933 
934 void
935 nvme_qpair_submit_tracker(struct nvme_qpair *qpair, struct nvme_tracker *tr)
936 {
937 	struct nvme_request	*req;
938 	struct nvme_controller	*ctrlr;
939 
940 	mtx_assert(&qpair->lock, MA_OWNED);
941 
942 	req = tr->req;
943 	req->cmd.cid = tr->cid;
944 	qpair->act_tr[tr->cid] = tr;
945 	ctrlr = qpair->ctrlr;
946 
947 	if (req->timeout)
948 		callout_reset_on(&tr->timer, ctrlr->timeout_period * hz,
949 		    nvme_timeout, tr, qpair->cpu);
950 
951 	/* Copy the command from the tracker to the submission queue. */
952 	memcpy(&qpair->cmd[qpair->sq_tail], &req->cmd, sizeof(req->cmd));
953 
954 	if (++qpair->sq_tail == qpair->num_entries)
955 		qpair->sq_tail = 0;
956 
957 	bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
958 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
959 #ifndef __powerpc__
960 	/*
961 	 * powerpc's bus_dmamap_sync() already includes a heavyweight sync, but
962 	 * no other archs do.
963 	 */
964 	wmb();
965 #endif
966 
967 	bus_space_write_4(qpair->ctrlr->bus_tag, qpair->ctrlr->bus_handle,
968 	    qpair->sq_tdbl_off, qpair->sq_tail);
969 	qpair->num_cmds++;
970 }
971 
972 static void
973 nvme_payload_map(void *arg, bus_dma_segment_t *seg, int nseg, int error)
974 {
975 	struct nvme_tracker 	*tr = arg;
976 	uint32_t		cur_nseg;
977 
978 	/*
979 	 * If the mapping operation failed, return immediately.  The caller
980 	 *  is responsible for detecting the error status and failing the
981 	 *  tracker manually.
982 	 */
983 	if (error != 0) {
984 		nvme_printf(tr->qpair->ctrlr,
985 		    "nvme_payload_map err %d\n", error);
986 		return;
987 	}
988 
989 	/*
990 	 * Note that we specified PAGE_SIZE for alignment and max
991 	 *  segment size when creating the bus dma tags.  So here
992 	 *  we can safely just transfer each segment to its
993 	 *  associated PRP entry.
994 	 */
995 	tr->req->cmd.prp1 = htole64(seg[0].ds_addr);
996 
997 	if (nseg == 2) {
998 		tr->req->cmd.prp2 = htole64(seg[1].ds_addr);
999 	} else if (nseg > 2) {
1000 		cur_nseg = 1;
1001 		tr->req->cmd.prp2 = htole64((uint64_t)tr->prp_bus_addr);
1002 		while (cur_nseg < nseg) {
1003 			tr->prp[cur_nseg-1] =
1004 			    htole64((uint64_t)seg[cur_nseg].ds_addr);
1005 			cur_nseg++;
1006 		}
1007 	} else {
1008 		/*
1009 		 * prp2 should not be used by the controller
1010 		 *  since there is only one segment, but set
1011 		 *  to 0 just to be safe.
1012 		 */
1013 		tr->req->cmd.prp2 = 0;
1014 	}
1015 
1016 	bus_dmamap_sync(tr->qpair->dma_tag_payload, tr->payload_dma_map,
1017 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1018 	nvme_qpair_submit_tracker(tr->qpair, tr);
1019 }
1020 
1021 static void
1022 _nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
1023 {
1024 	struct nvme_tracker	*tr;
1025 	int			err = 0;
1026 
1027 	mtx_assert(&qpair->lock, MA_OWNED);
1028 
1029 	tr = TAILQ_FIRST(&qpair->free_tr);
1030 	req->qpair = qpair;
1031 
1032 	if (tr == NULL || !qpair->is_enabled) {
1033 		/*
1034 		 * No tracker is available, or the qpair is disabled due to
1035 		 *  an in-progress controller-level reset or controller
1036 		 *  failure.
1037 		 */
1038 
1039 		if (qpair->ctrlr->is_failed) {
1040 			/*
1041 			 * The controller has failed.  Post the request to a
1042 			 *  task where it will be aborted, so that we do not
1043 			 *  invoke the request's callback in the context
1044 			 *  of the submission.
1045 			 */
1046 			nvme_ctrlr_post_failed_request(qpair->ctrlr, req);
1047 		} else {
1048 			/*
1049 			 * Put the request on the qpair's request queue to be
1050 			 *  processed when a tracker frees up via a command
1051 			 *  completion or when the controller reset is
1052 			 *  completed.
1053 			 */
1054 			STAILQ_INSERT_TAIL(&qpair->queued_req, req, stailq);
1055 		}
1056 		return;
1057 	}
1058 
1059 	TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
1060 	TAILQ_INSERT_TAIL(&qpair->outstanding_tr, tr, tailq);
1061 	tr->req = req;
1062 
1063 	switch (req->type) {
1064 	case NVME_REQUEST_VADDR:
1065 		KASSERT(req->payload_size <= qpair->ctrlr->max_xfer_size,
1066 		    ("payload_size (%d) exceeds max_xfer_size (%d)\n",
1067 		    req->payload_size, qpair->ctrlr->max_xfer_size));
1068 		err = bus_dmamap_load(tr->qpair->dma_tag_payload,
1069 		    tr->payload_dma_map, req->u.payload, req->payload_size,
1070 		    nvme_payload_map, tr, 0);
1071 		if (err != 0)
1072 			nvme_printf(qpair->ctrlr,
1073 			    "bus_dmamap_load returned 0x%x!\n", err);
1074 		break;
1075 	case NVME_REQUEST_NULL:
1076 		nvme_qpair_submit_tracker(tr->qpair, tr);
1077 		break;
1078 	case NVME_REQUEST_BIO:
1079 		KASSERT(req->u.bio->bio_bcount <= qpair->ctrlr->max_xfer_size,
1080 		    ("bio->bio_bcount (%jd) exceeds max_xfer_size (%d)\n",
1081 		    (intmax_t)req->u.bio->bio_bcount,
1082 		    qpair->ctrlr->max_xfer_size));
1083 		err = bus_dmamap_load_bio(tr->qpair->dma_tag_payload,
1084 		    tr->payload_dma_map, req->u.bio, nvme_payload_map, tr, 0);
1085 		if (err != 0)
1086 			nvme_printf(qpair->ctrlr,
1087 			    "bus_dmamap_load_bio returned 0x%x!\n", err);
1088 		break;
1089 	case NVME_REQUEST_CCB:
1090 		err = bus_dmamap_load_ccb(tr->qpair->dma_tag_payload,
1091 		    tr->payload_dma_map, req->u.payload,
1092 		    nvme_payload_map, tr, 0);
1093 		if (err != 0)
1094 			nvme_printf(qpair->ctrlr,
1095 			    "bus_dmamap_load_ccb returned 0x%x!\n", err);
1096 		break;
1097 	default:
1098 		panic("unknown nvme request type 0x%x\n", req->type);
1099 		break;
1100 	}
1101 
1102 	if (err != 0) {
1103 		/*
1104 		 * The dmamap operation failed, so we manually fail the
1105 		 *  tracker here with DATA_TRANSFER_ERROR status.
1106 		 *
1107 		 * nvme_qpair_manual_complete_tracker must not be called
1108 		 *  with the qpair lock held.
1109 		 */
1110 		mtx_unlock(&qpair->lock);
1111 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1112 		    NVME_SC_DATA_TRANSFER_ERROR, DO_NOT_RETRY, ERROR_PRINT_ALL);
1113 		mtx_lock(&qpair->lock);
1114 	}
1115 }
1116 
1117 void
1118 nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
1119 {
1120 
1121 	mtx_lock(&qpair->lock);
1122 	_nvme_qpair_submit_request(qpair, req);
1123 	mtx_unlock(&qpair->lock);
1124 }
1125 
1126 static void
1127 nvme_qpair_enable(struct nvme_qpair *qpair)
1128 {
1129 
1130 	qpair->is_enabled = TRUE;
1131 }
1132 
1133 void
1134 nvme_qpair_reset(struct nvme_qpair *qpair)
1135 {
1136 
1137 	qpair->sq_head = qpair->sq_tail = qpair->cq_head = 0;
1138 
1139 	/*
1140 	 * First time through the completion queue, HW will set phase
1141 	 *  bit on completions to 1.  So set this to 1 here, indicating
1142 	 *  we're looking for a 1 to know which entries have completed.
1143 	 *  we'll toggle the bit each time when the completion queue
1144 	 *  rolls over.
1145 	 */
1146 	qpair->phase = 1;
1147 
1148 	memset(qpair->cmd, 0,
1149 	    qpair->num_entries * sizeof(struct nvme_command));
1150 	memset(qpair->cpl, 0,
1151 	    qpair->num_entries * sizeof(struct nvme_completion));
1152 }
1153 
1154 void
1155 nvme_admin_qpair_enable(struct nvme_qpair *qpair)
1156 {
1157 	struct nvme_tracker		*tr;
1158 	struct nvme_tracker		*tr_temp;
1159 
1160 	/*
1161 	 * Manually abort each outstanding admin command.  Do not retry
1162 	 *  admin commands found here, since they will be left over from
1163 	 *  a controller reset and its likely the context in which the
1164 	 *  command was issued no longer applies.
1165 	 */
1166 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1167 		nvme_printf(qpair->ctrlr,
1168 		    "aborting outstanding admin command\n");
1169 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1170 		    NVME_SC_ABORTED_BY_REQUEST, DO_NOT_RETRY, ERROR_PRINT_ALL);
1171 	}
1172 
1173 	nvme_qpair_enable(qpair);
1174 }
1175 
1176 void
1177 nvme_io_qpair_enable(struct nvme_qpair *qpair)
1178 {
1179 	STAILQ_HEAD(, nvme_request)	temp;
1180 	struct nvme_tracker		*tr;
1181 	struct nvme_tracker		*tr_temp;
1182 	struct nvme_request		*req;
1183 
1184 	/*
1185 	 * Manually abort each outstanding I/O.  This normally results in a
1186 	 *  retry, unless the retry count on the associated request has
1187 	 *  reached its limit.
1188 	 */
1189 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1190 		nvme_printf(qpair->ctrlr, "aborting outstanding i/o\n");
1191 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1192 		    NVME_SC_ABORTED_BY_REQUEST, 0, ERROR_PRINT_NO_RETRY);
1193 	}
1194 
1195 	mtx_lock(&qpair->lock);
1196 
1197 	nvme_qpair_enable(qpair);
1198 
1199 	STAILQ_INIT(&temp);
1200 	STAILQ_SWAP(&qpair->queued_req, &temp, nvme_request);
1201 
1202 	while (!STAILQ_EMPTY(&temp)) {
1203 		req = STAILQ_FIRST(&temp);
1204 		STAILQ_REMOVE_HEAD(&temp, stailq);
1205 		nvme_printf(qpair->ctrlr, "resubmitting queued i/o\n");
1206 		nvme_qpair_print_command(qpair, &req->cmd);
1207 		_nvme_qpair_submit_request(qpair, req);
1208 	}
1209 
1210 	mtx_unlock(&qpair->lock);
1211 }
1212 
1213 static void
1214 nvme_qpair_disable(struct nvme_qpair *qpair)
1215 {
1216 	struct nvme_tracker *tr;
1217 
1218 	qpair->is_enabled = FALSE;
1219 	mtx_lock(&qpair->lock);
1220 	TAILQ_FOREACH(tr, &qpair->outstanding_tr, tailq)
1221 		callout_stop(&tr->timer);
1222 	mtx_unlock(&qpair->lock);
1223 }
1224 
1225 void
1226 nvme_admin_qpair_disable(struct nvme_qpair *qpair)
1227 {
1228 
1229 	nvme_qpair_disable(qpair);
1230 	nvme_admin_qpair_abort_aers(qpair);
1231 }
1232 
1233 void
1234 nvme_io_qpair_disable(struct nvme_qpair *qpair)
1235 {
1236 
1237 	nvme_qpair_disable(qpair);
1238 }
1239 
1240 void
1241 nvme_qpair_fail(struct nvme_qpair *qpair)
1242 {
1243 	struct nvme_tracker		*tr;
1244 	struct nvme_request		*req;
1245 
1246 	if (!mtx_initialized(&qpair->lock))
1247 		return;
1248 
1249 	mtx_lock(&qpair->lock);
1250 
1251 	while (!STAILQ_EMPTY(&qpair->queued_req)) {
1252 		req = STAILQ_FIRST(&qpair->queued_req);
1253 		STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
1254 		nvme_printf(qpair->ctrlr, "failing queued i/o\n");
1255 		mtx_unlock(&qpair->lock);
1256 		nvme_qpair_manual_complete_request(qpair, req, NVME_SCT_GENERIC,
1257 		    NVME_SC_ABORTED_BY_REQUEST);
1258 		mtx_lock(&qpair->lock);
1259 	}
1260 
1261 	/* Manually abort each outstanding I/O. */
1262 	while (!TAILQ_EMPTY(&qpair->outstanding_tr)) {
1263 		tr = TAILQ_FIRST(&qpair->outstanding_tr);
1264 		/*
1265 		 * Do not remove the tracker.  The abort_tracker path will
1266 		 *  do that for us.
1267 		 */
1268 		nvme_printf(qpair->ctrlr, "failing outstanding i/o\n");
1269 		mtx_unlock(&qpair->lock);
1270 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1271 		    NVME_SC_ABORTED_BY_REQUEST, DO_NOT_RETRY, ERROR_PRINT_ALL);
1272 		mtx_lock(&qpair->lock);
1273 	}
1274 
1275 	mtx_unlock(&qpair->lock);
1276 }
1277