xref: /freebsd/sys/dev/nvme/nvme_qpair.c (revision 4f52dfbb8d6c4d446500c5b097e3806ec219fbd4)
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 
35 #include <dev/pci/pcivar.h>
36 
37 #include "nvme_private.h"
38 
39 static void	_nvme_qpair_submit_request(struct nvme_qpair *qpair,
40 					   struct nvme_request *req);
41 static void	nvme_qpair_destroy(struct nvme_qpair *qpair);
42 
43 struct nvme_opcode_string {
44 
45 	uint16_t	opc;
46 	const char *	str;
47 };
48 
49 static struct nvme_opcode_string admin_opcode[] = {
50 	{ NVME_OPC_DELETE_IO_SQ, "DELETE IO SQ" },
51 	{ NVME_OPC_CREATE_IO_SQ, "CREATE IO SQ" },
52 	{ NVME_OPC_GET_LOG_PAGE, "GET LOG PAGE" },
53 	{ NVME_OPC_DELETE_IO_CQ, "DELETE IO CQ" },
54 	{ NVME_OPC_CREATE_IO_CQ, "CREATE IO CQ" },
55 	{ NVME_OPC_IDENTIFY, "IDENTIFY" },
56 	{ NVME_OPC_ABORT, "ABORT" },
57 	{ NVME_OPC_SET_FEATURES, "SET FEATURES" },
58 	{ NVME_OPC_GET_FEATURES, "GET FEATURES" },
59 	{ NVME_OPC_ASYNC_EVENT_REQUEST, "ASYNC EVENT REQUEST" },
60 	{ NVME_OPC_FIRMWARE_ACTIVATE, "FIRMWARE ACTIVATE" },
61 	{ NVME_OPC_FIRMWARE_IMAGE_DOWNLOAD, "FIRMWARE IMAGE DOWNLOAD" },
62 	{ NVME_OPC_DEVICE_SELF_TEST, "DEVICE SELF-TEST" },
63 	{ NVME_OPC_NAMESPACE_ATTACHMENT, "NAMESPACE ATTACHMENT" },
64 	{ NVME_OPC_KEEP_ALIVE, "KEEP ALIVE" },
65 	{ NVME_OPC_DIRECTIVE_SEND, "DIRECTIVE SEND" },
66 	{ NVME_OPC_DIRECTIVE_RECEIVE, "DIRECTIVE RECEIVE" },
67 	{ NVME_OPC_VIRTUALIZATION_MANAGEMENT, "VIRTUALIZATION MANAGEMENT" },
68 	{ NVME_OPC_NVME_MI_SEND, "NVME-MI SEND" },
69 	{ NVME_OPC_NVME_MI_RECEIVE, "NVME-MI RECEIVE" },
70 	{ NVME_OPC_DOORBELL_BUFFER_CONFIG, "DOORBELL BUFFER CONFIG" },
71 	{ NVME_OPC_FORMAT_NVM, "FORMAT NVM" },
72 	{ NVME_OPC_SECURITY_SEND, "SECURITY SEND" },
73 	{ NVME_OPC_SECURITY_RECEIVE, "SECURITY RECEIVE" },
74 	{ NVME_OPC_SANITIZE, "SANITIZE" },
75 	{ 0xFFFF, "ADMIN COMMAND" }
76 };
77 
78 static struct nvme_opcode_string io_opcode[] = {
79 	{ NVME_OPC_FLUSH, "FLUSH" },
80 	{ NVME_OPC_WRITE, "WRITE" },
81 	{ NVME_OPC_READ, "READ" },
82 	{ NVME_OPC_WRITE_UNCORRECTABLE, "WRITE UNCORRECTABLE" },
83 	{ NVME_OPC_COMPARE, "COMPARE" },
84 	{ NVME_OPC_WRITE_ZEROES, "WRITE ZEROES" },
85 	{ NVME_OPC_DATASET_MANAGEMENT, "DATASET MANAGEMENT" },
86 	{ NVME_OPC_RESERVATION_REGISTER, "RESERVATION REGISTER" },
87 	{ NVME_OPC_RESERVATION_REPORT, "RESERVATION REPORT" },
88 	{ NVME_OPC_RESERVATION_ACQUIRE, "RESERVATION ACQUIRE" },
89 	{ NVME_OPC_RESERVATION_RELEASE, "RESERVATION RELEASE" },
90 	{ 0xFFFF, "IO COMMAND" }
91 };
92 
93 static const char *
94 get_admin_opcode_string(uint16_t opc)
95 {
96 	struct nvme_opcode_string *entry;
97 
98 	entry = admin_opcode;
99 
100 	while (entry->opc != 0xFFFF) {
101 		if (entry->opc == opc)
102 			return (entry->str);
103 		entry++;
104 	}
105 	return (entry->str);
106 }
107 
108 static const char *
109 get_io_opcode_string(uint16_t opc)
110 {
111 	struct nvme_opcode_string *entry;
112 
113 	entry = io_opcode;
114 
115 	while (entry->opc != 0xFFFF) {
116 		if (entry->opc == opc)
117 			return (entry->str);
118 		entry++;
119 	}
120 	return (entry->str);
121 }
122 
123 
124 static void
125 nvme_admin_qpair_print_command(struct nvme_qpair *qpair,
126     struct nvme_command *cmd)
127 {
128 	uint16_t opc;
129 
130 	opc = le16toh(cmd->opc_fuse) & NVME_CMD_OPC_MASK;
131 	nvme_printf(qpair->ctrlr, "%s (%02x) sqid:%d cid:%d nsid:%x "
132 	    "cdw10:%08x cdw11:%08x\n",
133 	    get_admin_opcode_string(opc), opc, qpair->id, cmd->cid,
134 	    le32toh(cmd->nsid), le32toh(cmd->cdw10), le32toh(cmd->cdw11));
135 }
136 
137 static void
138 nvme_io_qpair_print_command(struct nvme_qpair *qpair,
139     struct nvme_command *cmd)
140 {
141 	uint16_t opc;
142 
143 	opc = le16toh(cmd->opc_fuse) & NVME_CMD_OPC_MASK;
144 	switch (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 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d "
151 		    "lba:%llu len:%d\n",
152 		    get_io_opcode_string(opc), qpair->id, cmd->cid, le32toh(cmd->nsid),
153 		    ((unsigned long long)le32toh(cmd->cdw11) << 32) + le32toh(cmd->cdw10),
154 		    (le32toh(cmd->cdw12) & 0xFFFF) + 1);
155 		break;
156 	case NVME_OPC_FLUSH:
157 	case NVME_OPC_DATASET_MANAGEMENT:
158 	case NVME_OPC_RESERVATION_REGISTER:
159 	case NVME_OPC_RESERVATION_REPORT:
160 	case NVME_OPC_RESERVATION_ACQUIRE:
161 	case NVME_OPC_RESERVATION_RELEASE:
162 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d\n",
163 		    get_io_opcode_string(opc), qpair->id, cmd->cid, le32toh(cmd->nsid));
164 		break;
165 	default:
166 		nvme_printf(qpair->ctrlr, "%s (%02x) sqid:%d cid:%d nsid:%d\n",
167 		    get_io_opcode_string(opc), opc, qpair->id,
168 		    cmd->cid, le32toh(cmd->nsid));
169 		break;
170 	}
171 }
172 
173 static void
174 nvme_qpair_print_command(struct nvme_qpair *qpair, struct nvme_command *cmd)
175 {
176 	if (qpair->id == 0)
177 		nvme_admin_qpair_print_command(qpair, cmd);
178 	else
179 		nvme_io_qpair_print_command(qpair, cmd);
180 }
181 
182 struct nvme_status_string {
183 
184 	uint16_t	sc;
185 	const char *	str;
186 };
187 
188 static struct nvme_status_string generic_status[] = {
189 	{ NVME_SC_SUCCESS, "SUCCESS" },
190 	{ NVME_SC_INVALID_OPCODE, "INVALID OPCODE" },
191 	{ NVME_SC_INVALID_FIELD, "INVALID_FIELD" },
192 	{ NVME_SC_COMMAND_ID_CONFLICT, "COMMAND ID CONFLICT" },
193 	{ NVME_SC_DATA_TRANSFER_ERROR, "DATA TRANSFER ERROR" },
194 	{ NVME_SC_ABORTED_POWER_LOSS, "ABORTED - POWER LOSS" },
195 	{ NVME_SC_INTERNAL_DEVICE_ERROR, "INTERNAL DEVICE ERROR" },
196 	{ NVME_SC_ABORTED_BY_REQUEST, "ABORTED - BY REQUEST" },
197 	{ NVME_SC_ABORTED_SQ_DELETION, "ABORTED - SQ DELETION" },
198 	{ NVME_SC_ABORTED_FAILED_FUSED, "ABORTED - FAILED FUSED" },
199 	{ NVME_SC_ABORTED_MISSING_FUSED, "ABORTED - MISSING FUSED" },
200 	{ NVME_SC_INVALID_NAMESPACE_OR_FORMAT, "INVALID NAMESPACE OR FORMAT" },
201 	{ NVME_SC_COMMAND_SEQUENCE_ERROR, "COMMAND SEQUENCE ERROR" },
202 	{ NVME_SC_INVALID_SGL_SEGMENT_DESCR, "INVALID SGL SEGMENT DESCRIPTOR" },
203 	{ NVME_SC_INVALID_NUMBER_OF_SGL_DESCR, "INVALID NUMBER OF SGL DESCRIPTORS" },
204 	{ NVME_SC_DATA_SGL_LENGTH_INVALID, "DATA SGL LENGTH INVALID" },
205 	{ NVME_SC_METADATA_SGL_LENGTH_INVALID, "METADATA SGL LENGTH INVALID" },
206 	{ NVME_SC_SGL_DESCRIPTOR_TYPE_INVALID, "SGL DESCRIPTOR TYPE INVALID" },
207 	{ NVME_SC_INVALID_USE_OF_CMB, "INVALID USE OF CONTROLLER MEMORY BUFFER" },
208 	{ NVME_SC_PRP_OFFET_INVALID, "PRP OFFET INVALID" },
209 	{ NVME_SC_ATOMIC_WRITE_UNIT_EXCEEDED, "ATOMIC WRITE UNIT EXCEEDED" },
210 	{ NVME_SC_OPERATION_DENIED, "OPERATION DENIED" },
211 	{ NVME_SC_SGL_OFFSET_INVALID, "SGL OFFSET INVALID" },
212 	{ NVME_SC_HOST_ID_INCONSISTENT_FORMAT, "HOST IDENTIFIER INCONSISTENT FORMAT" },
213 	{ NVME_SC_KEEP_ALIVE_TIMEOUT_EXPIRED, "KEEP ALIVE TIMEOUT EXPIRED" },
214 	{ NVME_SC_KEEP_ALIVE_TIMEOUT_INVALID, "KEEP ALIVE TIMEOUT INVALID" },
215 	{ NVME_SC_ABORTED_DUE_TO_PREEMPT, "COMMAND ABORTED DUE TO PREEMPT AND ABORT" },
216 	{ NVME_SC_SANITIZE_FAILED, "SANITIZE FAILED" },
217 	{ NVME_SC_SANITIZE_IN_PROGRESS, "SANITIZE IN PROGRESS" },
218 	{ NVME_SC_SGL_DATA_BLOCK_GRAN_INVALID, "SGL_DATA_BLOCK_GRANULARITY_INVALID" },
219 	{ NVME_SC_NOT_SUPPORTED_IN_CMB, "COMMAND NOT SUPPORTED FOR QUEUE IN CMB" },
220 
221 	{ NVME_SC_LBA_OUT_OF_RANGE, "LBA OUT OF RANGE" },
222 	{ NVME_SC_CAPACITY_EXCEEDED, "CAPACITY EXCEEDED" },
223 	{ NVME_SC_NAMESPACE_NOT_READY, "NAMESPACE NOT READY" },
224 	{ NVME_SC_RESERVATION_CONFLICT, "RESERVATION CONFLICT" },
225 	{ NVME_SC_FORMAT_IN_PROGRESS, "FORMAT IN PROGRESS" },
226 	{ 0xFFFF, "GENERIC" }
227 };
228 
229 static struct nvme_status_string command_specific_status[] = {
230 	{ NVME_SC_COMPLETION_QUEUE_INVALID, "INVALID COMPLETION QUEUE" },
231 	{ NVME_SC_INVALID_QUEUE_IDENTIFIER, "INVALID QUEUE IDENTIFIER" },
232 	{ NVME_SC_MAXIMUM_QUEUE_SIZE_EXCEEDED, "MAX QUEUE SIZE EXCEEDED" },
233 	{ NVME_SC_ABORT_COMMAND_LIMIT_EXCEEDED, "ABORT CMD LIMIT EXCEEDED" },
234 	{ NVME_SC_ASYNC_EVENT_REQUEST_LIMIT_EXCEEDED, "ASYNC LIMIT EXCEEDED" },
235 	{ NVME_SC_INVALID_FIRMWARE_SLOT, "INVALID FIRMWARE SLOT" },
236 	{ NVME_SC_INVALID_FIRMWARE_IMAGE, "INVALID FIRMWARE IMAGE" },
237 	{ NVME_SC_INVALID_INTERRUPT_VECTOR, "INVALID INTERRUPT VECTOR" },
238 	{ NVME_SC_INVALID_LOG_PAGE, "INVALID LOG PAGE" },
239 	{ NVME_SC_INVALID_FORMAT, "INVALID FORMAT" },
240 	{ NVME_SC_FIRMWARE_REQUIRES_RESET, "FIRMWARE REQUIRES RESET" },
241 	{ NVME_SC_INVALID_QUEUE_DELETION, "INVALID QUEUE DELETION" },
242 	{ NVME_SC_FEATURE_NOT_SAVEABLE, "FEATURE IDENTIFIER NOT SAVEABLE" },
243 	{ NVME_SC_FEATURE_NOT_CHANGEABLE, "FEATURE NOT CHANGEABLE" },
244 	{ NVME_SC_FEATURE_NOT_NS_SPECIFIC, "FEATURE NOT NAMESPACE SPECIFIC" },
245 	{ NVME_SC_FW_ACT_REQUIRES_NVMS_RESET, "FIRMWARE ACTIVATION REQUIRES NVM SUBSYSTEM RESET" },
246 	{ NVME_SC_FW_ACT_REQUIRES_RESET, "FIRMWARE ACTIVATION REQUIRES RESET" },
247 	{ NVME_SC_FW_ACT_REQUIRES_TIME, "FIRMWARE ACTIVATION REQUIRES MAXIMUM TIME VIOLATION" },
248 	{ NVME_SC_FW_ACT_PROHIBITED, "FIRMWARE ACTIVATION PROHIBITED" },
249 	{ NVME_SC_OVERLAPPING_RANGE, "OVERLAPPING RANGE" },
250 	{ NVME_SC_NS_INSUFFICIENT_CAPACITY, "NAMESPACE INSUFFICIENT CAPACITY" },
251 	{ NVME_SC_NS_ID_UNAVAILABLE, "NAMESPACE IDENTIFIER UNAVAILABLE" },
252 	{ NVME_SC_NS_ALREADY_ATTACHED, "NAMESPACE ALREADY ATTACHED" },
253 	{ NVME_SC_NS_IS_PRIVATE, "NAMESPACE IS PRIVATE" },
254 	{ NVME_SC_NS_NOT_ATTACHED, "NS NOT ATTACHED" },
255 	{ NVME_SC_THIN_PROV_NOT_SUPPORTED, "THIN PROVISIONING NOT SUPPORTED" },
256 	{ NVME_SC_CTRLR_LIST_INVALID, "CONTROLLER LIST INVALID" },
257 	{ NVME_SC_SELT_TEST_IN_PROGRESS, "DEVICE SELT-TEST IN PROGRESS" },
258 	{ NVME_SC_BOOT_PART_WRITE_PROHIB, "BOOT PARTITION WRITE PROHIBITED" },
259 	{ NVME_SC_INVALID_CTRLR_ID, "INVALID CONTROLLER IDENTIFIER" },
260 	{ NVME_SC_INVALID_SEC_CTRLR_STATE, "INVALID SECONDARY CONTROLLER STATE" },
261 	{ NVME_SC_INVALID_NUM_OF_CTRLR_RESRC, "INVALID NUMBER OF CONTROLLER RESOURCES" },
262 	{ NVME_SC_INVALID_RESOURCE_ID, "INVALID RESOURCE IDENTIFIER" },
263 
264 	{ NVME_SC_CONFLICTING_ATTRIBUTES, "CONFLICTING ATTRIBUTES" },
265 	{ NVME_SC_INVALID_PROTECTION_INFO, "INVALID PROTECTION INFO" },
266 	{ NVME_SC_ATTEMPTED_WRITE_TO_RO_PAGE, "WRITE TO RO PAGE" },
267 	{ 0xFFFF, "COMMAND SPECIFIC" }
268 };
269 
270 static struct nvme_status_string media_error_status[] = {
271 	{ NVME_SC_WRITE_FAULTS, "WRITE FAULTS" },
272 	{ NVME_SC_UNRECOVERED_READ_ERROR, "UNRECOVERED READ ERROR" },
273 	{ NVME_SC_GUARD_CHECK_ERROR, "GUARD CHECK ERROR" },
274 	{ NVME_SC_APPLICATION_TAG_CHECK_ERROR, "APPLICATION TAG CHECK ERROR" },
275 	{ NVME_SC_REFERENCE_TAG_CHECK_ERROR, "REFERENCE TAG CHECK ERROR" },
276 	{ NVME_SC_COMPARE_FAILURE, "COMPARE FAILURE" },
277 	{ NVME_SC_ACCESS_DENIED, "ACCESS DENIED" },
278 	{ NVME_SC_DEALLOCATED_OR_UNWRITTEN, "DEALLOCATED OR UNWRITTEN LOGICAL BLOCK" },
279 	{ 0xFFFF, "MEDIA ERROR" }
280 };
281 
282 static const char *
283 get_status_string(uint16_t sct, uint16_t sc)
284 {
285 	struct nvme_status_string *entry;
286 
287 	switch (sct) {
288 	case NVME_SCT_GENERIC:
289 		entry = generic_status;
290 		break;
291 	case NVME_SCT_COMMAND_SPECIFIC:
292 		entry = command_specific_status;
293 		break;
294 	case NVME_SCT_MEDIA_ERROR:
295 		entry = media_error_status;
296 		break;
297 	case NVME_SCT_VENDOR_SPECIFIC:
298 		return ("VENDOR SPECIFIC");
299 	default:
300 		return ("RESERVED");
301 	}
302 
303 	while (entry->sc != 0xFFFF) {
304 		if (entry->sc == sc)
305 			return (entry->str);
306 		entry++;
307 	}
308 	return (entry->str);
309 }
310 
311 static void
312 nvme_qpair_print_completion(struct nvme_qpair *qpair,
313     struct nvme_completion *cpl)
314 {
315 	uint16_t sct, sc;
316 
317 	sct = NVME_STATUS_GET_SCT(cpl->status);
318 	sc = NVME_STATUS_GET_SC(cpl->status);
319 
320 	nvme_printf(qpair->ctrlr, "%s (%02x/%02x) sqid:%d cid:%d cdw0:%x\n",
321 	    get_status_string(sct, sc), sct, sc, cpl->sqid, cpl->cid,
322 	    cpl->cdw0);
323 }
324 
325 static boolean_t
326 nvme_completion_is_retry(const struct nvme_completion *cpl)
327 {
328 	uint8_t sct, sc, dnr;
329 
330 	sct = NVME_STATUS_GET_SCT(cpl->status);
331 	sc = NVME_STATUS_GET_SC(cpl->status);
332 	dnr = NVME_STATUS_GET_DNR(cpl->status);
333 
334 	/*
335 	 * TODO: spec is not clear how commands that are aborted due
336 	 *  to TLER will be marked.  So for now, it seems
337 	 *  NAMESPACE_NOT_READY is the only case where we should
338 	 *  look at the DNR bit.
339 	 */
340 	switch (sct) {
341 	case NVME_SCT_GENERIC:
342 		switch (sc) {
343 		case NVME_SC_ABORTED_BY_REQUEST:
344 		case NVME_SC_NAMESPACE_NOT_READY:
345 			if (dnr)
346 				return (0);
347 			else
348 				return (1);
349 		case NVME_SC_INVALID_OPCODE:
350 		case NVME_SC_INVALID_FIELD:
351 		case NVME_SC_COMMAND_ID_CONFLICT:
352 		case NVME_SC_DATA_TRANSFER_ERROR:
353 		case NVME_SC_ABORTED_POWER_LOSS:
354 		case NVME_SC_INTERNAL_DEVICE_ERROR:
355 		case NVME_SC_ABORTED_SQ_DELETION:
356 		case NVME_SC_ABORTED_FAILED_FUSED:
357 		case NVME_SC_ABORTED_MISSING_FUSED:
358 		case NVME_SC_INVALID_NAMESPACE_OR_FORMAT:
359 		case NVME_SC_COMMAND_SEQUENCE_ERROR:
360 		case NVME_SC_LBA_OUT_OF_RANGE:
361 		case NVME_SC_CAPACITY_EXCEEDED:
362 		default:
363 			return (0);
364 		}
365 	case NVME_SCT_COMMAND_SPECIFIC:
366 	case NVME_SCT_MEDIA_ERROR:
367 	case NVME_SCT_VENDOR_SPECIFIC:
368 	default:
369 		return (0);
370 	}
371 }
372 
373 static void
374 nvme_qpair_complete_tracker(struct nvme_qpair *qpair, struct nvme_tracker *tr,
375     struct nvme_completion *cpl, boolean_t print_on_error)
376 {
377 	struct nvme_request	*req;
378 	boolean_t		retry, error;
379 
380 	req = tr->req;
381 	error = nvme_completion_is_error(cpl);
382 	retry = error && nvme_completion_is_retry(cpl) &&
383 	   req->retries < nvme_retry_count;
384 
385 	if (error && print_on_error) {
386 		nvme_qpair_print_command(qpair, &req->cmd);
387 		nvme_qpair_print_completion(qpair, cpl);
388 	}
389 
390 	qpair->act_tr[cpl->cid] = NULL;
391 
392 	KASSERT(cpl->cid == req->cmd.cid, ("cpl cid does not match cmd cid\n"));
393 
394 	if (req->cb_fn && !retry)
395 		req->cb_fn(req->cb_arg, cpl);
396 
397 	mtx_lock(&qpair->lock);
398 	callout_stop(&tr->timer);
399 
400 	if (retry) {
401 		req->retries++;
402 		nvme_qpair_submit_tracker(qpair, tr);
403 	} else {
404 		if (req->type != NVME_REQUEST_NULL)
405 			bus_dmamap_unload(qpair->dma_tag_payload,
406 			    tr->payload_dma_map);
407 
408 		nvme_free_request(req);
409 		tr->req = NULL;
410 
411 		TAILQ_REMOVE(&qpair->outstanding_tr, tr, tailq);
412 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
413 
414 		/*
415 		 * If the controller is in the middle of resetting, don't
416 		 *  try to submit queued requests here - let the reset logic
417 		 *  handle that instead.
418 		 */
419 		if (!STAILQ_EMPTY(&qpair->queued_req) &&
420 		    !qpair->ctrlr->is_resetting) {
421 			req = STAILQ_FIRST(&qpair->queued_req);
422 			STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
423 			_nvme_qpair_submit_request(qpair, req);
424 		}
425 	}
426 
427 	mtx_unlock(&qpair->lock);
428 }
429 
430 static void
431 nvme_qpair_manual_complete_tracker(struct nvme_qpair *qpair,
432     struct nvme_tracker *tr, uint32_t sct, uint32_t sc, uint32_t dnr,
433     boolean_t print_on_error)
434 {
435 	struct nvme_completion	cpl;
436 
437 	memset(&cpl, 0, sizeof(cpl));
438 	cpl.sqid = qpair->id;
439 	cpl.cid = tr->cid;
440 	cpl.status |= (sct & NVME_STATUS_SCT_MASK) << NVME_STATUS_SCT_SHIFT;
441 	cpl.status |= (sc & NVME_STATUS_SC_MASK) << NVME_STATUS_SC_SHIFT;
442 	cpl.status |= (dnr & NVME_STATUS_DNR_MASK) << NVME_STATUS_DNR_SHIFT;
443 	nvme_qpair_complete_tracker(qpair, tr, &cpl, print_on_error);
444 }
445 
446 void
447 nvme_qpair_manual_complete_request(struct nvme_qpair *qpair,
448     struct nvme_request *req, uint32_t sct, uint32_t sc,
449     boolean_t print_on_error)
450 {
451 	struct nvme_completion	cpl;
452 	boolean_t		error;
453 
454 	memset(&cpl, 0, sizeof(cpl));
455 	cpl.sqid = qpair->id;
456 	cpl.status |= (sct & NVME_STATUS_SCT_MASK) << NVME_STATUS_SCT_SHIFT;
457 	cpl.status |= (sc & NVME_STATUS_SC_MASK) << NVME_STATUS_SC_SHIFT;
458 
459 	error = nvme_completion_is_error(&cpl);
460 
461 	if (error && print_on_error) {
462 		nvme_qpair_print_command(qpair, &req->cmd);
463 		nvme_qpair_print_completion(qpair, &cpl);
464 	}
465 
466 	if (req->cb_fn)
467 		req->cb_fn(req->cb_arg, &cpl);
468 
469 	nvme_free_request(req);
470 }
471 
472 bool
473 nvme_qpair_process_completions(struct nvme_qpair *qpair)
474 {
475 	struct nvme_tracker	*tr;
476 	struct nvme_completion	cpl;
477 	int done = 0;
478 
479 	qpair->num_intr_handler_calls++;
480 
481 	if (!qpair->is_enabled)
482 		/*
483 		 * qpair is not enabled, likely because a controller reset is
484 		 *  is in progress.  Ignore the interrupt - any I/O that was
485 		 *  associated with this interrupt will get retried when the
486 		 *  reset is complete.
487 		 */
488 		return (false);
489 
490 	while (1) {
491 		cpl = qpair->cpl[qpair->cq_head];
492 
493 		/* Convert to host endian */
494 		nvme_completion_swapbytes(&cpl);
495 
496 		if (NVME_STATUS_GET_P(cpl.status) != qpair->phase)
497 			break;
498 
499 		tr = qpair->act_tr[cpl.cid];
500 
501 		if (tr != NULL) {
502 			nvme_qpair_complete_tracker(qpair, tr, &cpl, TRUE);
503 			qpair->sq_head = cpl.sqhd;
504 			done++;
505 		} else {
506 			nvme_printf(qpair->ctrlr,
507 			    "cpl does not map to outstanding cmd\n");
508 			/* nvme_dump_completion expects device endianess */
509 			nvme_dump_completion(&qpair->cpl[qpair->cq_head]);
510 			KASSERT(0, ("received completion for unknown cmd\n"));
511 		}
512 
513 		if (++qpair->cq_head == qpair->num_entries) {
514 			qpair->cq_head = 0;
515 			qpair->phase = !qpair->phase;
516 		}
517 
518 		nvme_mmio_write_4(qpair->ctrlr, doorbell[qpair->id].cq_hdbl,
519 		    qpair->cq_head);
520 	}
521 	return (done != 0);
522 }
523 
524 static void
525 nvme_qpair_msix_handler(void *arg)
526 {
527 	struct nvme_qpair *qpair = arg;
528 
529 	nvme_qpair_process_completions(qpair);
530 }
531 
532 int
533 nvme_qpair_construct(struct nvme_qpair *qpair, uint32_t id,
534     uint16_t vector, uint32_t num_entries, uint32_t num_trackers,
535     struct nvme_controller *ctrlr)
536 {
537 	struct nvme_tracker	*tr;
538 	size_t			cmdsz, cplsz, prpsz, allocsz, prpmemsz;
539 	uint64_t		queuemem_phys, prpmem_phys, list_phys;
540 	uint8_t			*queuemem, *prpmem, *prp_list;
541 	int			i, err;
542 
543 	qpair->id = id;
544 	qpair->vector = vector;
545 	qpair->num_entries = num_entries;
546 	qpair->num_trackers = num_trackers;
547 	qpair->ctrlr = ctrlr;
548 
549 	if (ctrlr->msix_enabled) {
550 
551 		/*
552 		 * MSI-X vector resource IDs start at 1, so we add one to
553 		 *  the queue's vector to get the corresponding rid to use.
554 		 */
555 		qpair->rid = vector + 1;
556 
557 		qpair->res = bus_alloc_resource_any(ctrlr->dev, SYS_RES_IRQ,
558 		    &qpair->rid, RF_ACTIVE);
559 		bus_setup_intr(ctrlr->dev, qpair->res,
560 		    INTR_TYPE_MISC | INTR_MPSAFE, NULL,
561 		    nvme_qpair_msix_handler, qpair, &qpair->tag);
562 	}
563 
564 	mtx_init(&qpair->lock, "nvme qpair lock", NULL, MTX_DEF);
565 
566 	/* Note: NVMe PRP format is restricted to 4-byte alignment. */
567 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
568 	    4, PAGE_SIZE, BUS_SPACE_MAXADDR,
569 	    BUS_SPACE_MAXADDR, NULL, NULL, NVME_MAX_XFER_SIZE,
570 	    (NVME_MAX_XFER_SIZE/PAGE_SIZE)+1, PAGE_SIZE, 0,
571 	    NULL, NULL, &qpair->dma_tag_payload);
572 	if (err != 0) {
573 		nvme_printf(ctrlr, "payload tag create failed %d\n", err);
574 		goto out;
575 	}
576 
577 	/*
578 	 * Each component must be page aligned, and individual PRP lists
579 	 * cannot cross a page boundary.
580 	 */
581 	cmdsz = qpair->num_entries * sizeof(struct nvme_command);
582 	cmdsz = roundup2(cmdsz, PAGE_SIZE);
583 	cplsz = qpair->num_entries * sizeof(struct nvme_completion);
584 	cplsz = roundup2(cplsz, PAGE_SIZE);
585 	prpsz = sizeof(uint64_t) * NVME_MAX_PRP_LIST_ENTRIES;;
586 	prpmemsz = qpair->num_trackers * prpsz;
587 	allocsz = cmdsz + cplsz + prpmemsz;
588 
589 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
590 	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
591 	    allocsz, 1, allocsz, 0, NULL, NULL, &qpair->dma_tag);
592 	if (err != 0) {
593 		nvme_printf(ctrlr, "tag create failed %d\n", err);
594 		goto out;
595 	}
596 
597 	if (bus_dmamem_alloc(qpair->dma_tag, (void **)&queuemem,
598 	    BUS_DMA_NOWAIT, &qpair->queuemem_map)) {
599 		nvme_printf(ctrlr, "failed to alloc qpair memory\n");
600 		goto out;
601 	}
602 
603 	if (bus_dmamap_load(qpair->dma_tag, qpair->queuemem_map,
604 	    queuemem, allocsz, nvme_single_map, &queuemem_phys, 0) != 0) {
605 		nvme_printf(ctrlr, "failed to load qpair memory\n");
606 		goto out;
607 	}
608 
609 	qpair->num_cmds = 0;
610 	qpair->num_intr_handler_calls = 0;
611 	qpair->cmd = (struct nvme_command *)queuemem;
612 	qpair->cpl = (struct nvme_completion *)(queuemem + cmdsz);
613 	prpmem = (uint8_t *)(queuemem + cmdsz + cplsz);
614 	qpair->cmd_bus_addr = queuemem_phys;
615 	qpair->cpl_bus_addr = queuemem_phys + cmdsz;
616 	prpmem_phys = queuemem_phys + cmdsz + cplsz;
617 
618 	qpair->sq_tdbl_off = nvme_mmio_offsetof(doorbell[id].sq_tdbl);
619 	qpair->cq_hdbl_off = nvme_mmio_offsetof(doorbell[id].cq_hdbl);
620 
621 	TAILQ_INIT(&qpair->free_tr);
622 	TAILQ_INIT(&qpair->outstanding_tr);
623 	STAILQ_INIT(&qpair->queued_req);
624 
625 	list_phys = prpmem_phys;
626 	prp_list = prpmem;
627 	for (i = 0; i < qpair->num_trackers; i++) {
628 
629 		if (list_phys + prpsz > prpmem_phys + prpmemsz) {
630 			qpair->num_trackers = i;
631 			break;
632 		}
633 
634 		/*
635 		 * Make sure that the PRP list for this tracker doesn't
636 		 * overflow to another page.
637 		 */
638 		if (trunc_page(list_phys) !=
639 		    trunc_page(list_phys + prpsz - 1)) {
640 			list_phys = roundup2(list_phys, PAGE_SIZE);
641 			prp_list =
642 			    (uint8_t *)roundup2((uintptr_t)prp_list, PAGE_SIZE);
643 		}
644 
645 		tr = malloc(sizeof(*tr), M_NVME, M_ZERO | M_WAITOK);
646 		bus_dmamap_create(qpair->dma_tag_payload, 0,
647 		    &tr->payload_dma_map);
648 		callout_init(&tr->timer, 1);
649 		tr->cid = i;
650 		tr->qpair = qpair;
651 		tr->prp = (uint64_t *)prp_list;
652 		tr->prp_bus_addr = list_phys;
653 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
654 		list_phys += prpsz;
655 		prp_list += prpsz;
656 	}
657 
658 	if (qpair->num_trackers == 0) {
659 		nvme_printf(ctrlr, "failed to allocate enough trackers\n");
660 		goto out;
661 	}
662 
663 	qpair->act_tr = malloc(sizeof(struct nvme_tracker *) *
664 	    qpair->num_entries, M_NVME, M_ZERO | M_WAITOK);
665 	return (0);
666 
667 out:
668 	nvme_qpair_destroy(qpair);
669 	return (ENOMEM);
670 }
671 
672 static void
673 nvme_qpair_destroy(struct nvme_qpair *qpair)
674 {
675 	struct nvme_tracker	*tr;
676 
677 	if (qpair->tag)
678 		bus_teardown_intr(qpair->ctrlr->dev, qpair->res, qpair->tag);
679 
680 	if (mtx_initialized(&qpair->lock))
681 		mtx_destroy(&qpair->lock);
682 
683 	if (qpair->res)
684 		bus_release_resource(qpair->ctrlr->dev, SYS_RES_IRQ,
685 		    rman_get_rid(qpair->res), qpair->res);
686 
687 	if (qpair->cmd != NULL) {
688 		bus_dmamap_unload(qpair->dma_tag, qpair->queuemem_map);
689 		bus_dmamem_free(qpair->dma_tag, qpair->cmd,
690 		    qpair->queuemem_map);
691 	}
692 
693 	if (qpair->act_tr)
694 		free(qpair->act_tr, M_NVME);
695 
696 	while (!TAILQ_EMPTY(&qpair->free_tr)) {
697 		tr = TAILQ_FIRST(&qpair->free_tr);
698 		TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
699 		bus_dmamap_destroy(qpair->dma_tag_payload,
700 		    tr->payload_dma_map);
701 		free(tr, M_NVME);
702 	}
703 
704 	if (qpair->dma_tag)
705 		bus_dma_tag_destroy(qpair->dma_tag);
706 
707 	if (qpair->dma_tag_payload)
708 		bus_dma_tag_destroy(qpair->dma_tag_payload);
709 }
710 
711 static void
712 nvme_admin_qpair_abort_aers(struct nvme_qpair *qpair)
713 {
714 	struct nvme_tracker	*tr;
715 
716 	tr = TAILQ_FIRST(&qpair->outstanding_tr);
717 	while (tr != NULL) {
718 		if ((le16toh(tr->req->cmd.opc_fuse) & NVME_CMD_OPC_MASK) == NVME_OPC_ASYNC_EVENT_REQUEST) {
719 			nvme_qpair_manual_complete_tracker(qpair, tr,
720 			    NVME_SCT_GENERIC, NVME_SC_ABORTED_SQ_DELETION, 0,
721 			    FALSE);
722 			tr = TAILQ_FIRST(&qpair->outstanding_tr);
723 		} else {
724 			tr = TAILQ_NEXT(tr, tailq);
725 		}
726 	}
727 }
728 
729 void
730 nvme_admin_qpair_destroy(struct nvme_qpair *qpair)
731 {
732 
733 	nvme_admin_qpair_abort_aers(qpair);
734 	nvme_qpair_destroy(qpair);
735 }
736 
737 void
738 nvme_io_qpair_destroy(struct nvme_qpair *qpair)
739 {
740 
741 	nvme_qpair_destroy(qpair);
742 }
743 
744 static void
745 nvme_abort_complete(void *arg, const struct nvme_completion *status)
746 {
747 	struct nvme_tracker	*tr = arg;
748 
749 	/*
750 	 * If cdw0 == 1, the controller was not able to abort the command
751 	 *  we requested.  We still need to check the active tracker array,
752 	 *  to cover race where I/O timed out at same time controller was
753 	 *  completing the I/O.
754 	 */
755 	if (status->cdw0 == 1 && tr->qpair->act_tr[tr->cid] != NULL) {
756 		/*
757 		 * An I/O has timed out, and the controller was unable to
758 		 *  abort it for some reason.  Construct a fake completion
759 		 *  status, and then complete the I/O's tracker manually.
760 		 */
761 		nvme_printf(tr->qpair->ctrlr,
762 		    "abort command failed, aborting command manually\n");
763 		nvme_qpair_manual_complete_tracker(tr->qpair, tr,
764 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST, 0, TRUE);
765 	}
766 }
767 
768 static void
769 nvme_timeout(void *arg)
770 {
771 	struct nvme_tracker	*tr = arg;
772 	struct nvme_qpair	*qpair = tr->qpair;
773 	struct nvme_controller	*ctrlr = qpair->ctrlr;
774 	uint32_t		csts;
775 	uint8_t			cfs;
776 
777 	/*
778 	 * Read csts to get value of cfs - controller fatal status.
779 	 * If no fatal status, try to call the completion routine, and
780 	 * if completes transactions, report a missed interrupt and
781 	 * return (this may need to be rate limited). Otherwise, if
782 	 * aborts are enabled and the controller is not reporting
783 	 * fatal status, abort the command. Otherwise, just reset the
784 	 * controller and hope for the best.
785 	 */
786 	csts = nvme_mmio_read_4(ctrlr, csts);
787 	cfs = (csts >> NVME_CSTS_REG_CFS_SHIFT) & NVME_CSTS_REG_CFS_MASK;
788 	if (cfs == 0 && nvme_qpair_process_completions(qpair)) {
789 		nvme_printf(ctrlr, "Missing interrupt\n");
790 		return;
791 	}
792 	if (ctrlr->enable_aborts && cfs == 0) {
793 		nvme_printf(ctrlr, "Aborting command due to a timeout.\n");
794 		nvme_ctrlr_cmd_abort(ctrlr, tr->cid, qpair->id,
795 		    nvme_abort_complete, tr);
796 	} else {
797 		nvme_printf(ctrlr, "Resetting controller due to a timeout%s.\n",
798 		    cfs ? " and fatal error status" : "");
799 		nvme_ctrlr_reset(ctrlr);
800 	}
801 }
802 
803 void
804 nvme_qpair_submit_tracker(struct nvme_qpair *qpair, struct nvme_tracker *tr)
805 {
806 	struct nvme_request	*req;
807 	struct nvme_controller	*ctrlr;
808 
809 	mtx_assert(&qpair->lock, MA_OWNED);
810 
811 	req = tr->req;
812 	req->cmd.cid = tr->cid;
813 	qpair->act_tr[tr->cid] = tr;
814 	ctrlr = qpair->ctrlr;
815 
816 	if (req->timeout)
817 #if __FreeBSD_version >= 800030
818 		callout_reset_curcpu(&tr->timer, ctrlr->timeout_period * hz,
819 		    nvme_timeout, tr);
820 #else
821 		callout_reset(&tr->timer, ctrlr->timeout_period * hz,
822 		    nvme_timeout, tr);
823 #endif
824 
825 	/* Copy the command from the tracker to the submission queue. */
826 	memcpy(&qpair->cmd[qpair->sq_tail], &req->cmd, sizeof(req->cmd));
827 
828 	if (++qpair->sq_tail == qpair->num_entries)
829 		qpair->sq_tail = 0;
830 
831 	wmb();
832 	nvme_mmio_write_4(qpair->ctrlr, doorbell[qpair->id].sq_tdbl,
833 	    qpair->sq_tail);
834 
835 	qpair->num_cmds++;
836 }
837 
838 static void
839 nvme_payload_map(void *arg, bus_dma_segment_t *seg, int nseg, int error)
840 {
841 	struct nvme_tracker 	*tr = arg;
842 	uint32_t		cur_nseg;
843 
844 	/*
845 	 * If the mapping operation failed, return immediately.  The caller
846 	 *  is responsible for detecting the error status and failing the
847 	 *  tracker manually.
848 	 */
849 	if (error != 0) {
850 		nvme_printf(tr->qpair->ctrlr,
851 		    "nvme_payload_map err %d\n", error);
852 		return;
853 	}
854 
855 	/*
856 	 * Note that we specified PAGE_SIZE for alignment and max
857 	 *  segment size when creating the bus dma tags.  So here
858 	 *  we can safely just transfer each segment to its
859 	 *  associated PRP entry.
860 	 */
861 	tr->req->cmd.prp1 = htole64(seg[0].ds_addr);
862 
863 	if (nseg == 2) {
864 		tr->req->cmd.prp2 = htole64(seg[1].ds_addr);
865 	} else if (nseg > 2) {
866 		cur_nseg = 1;
867 		tr->req->cmd.prp2 = htole64((uint64_t)tr->prp_bus_addr);
868 		while (cur_nseg < nseg) {
869 			tr->prp[cur_nseg-1] =
870 			    htole64((uint64_t)seg[cur_nseg].ds_addr);
871 			cur_nseg++;
872 		}
873 	} else {
874 		/*
875 		 * prp2 should not be used by the controller
876 		 *  since there is only one segment, but set
877 		 *  to 0 just to be safe.
878 		 */
879 		tr->req->cmd.prp2 = 0;
880 	}
881 
882 	nvme_qpair_submit_tracker(tr->qpair, tr);
883 }
884 
885 static void
886 _nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
887 {
888 	struct nvme_tracker	*tr;
889 	int			err = 0;
890 
891 	mtx_assert(&qpair->lock, MA_OWNED);
892 
893 	tr = TAILQ_FIRST(&qpair->free_tr);
894 	req->qpair = qpair;
895 
896 	if (tr == NULL || !qpair->is_enabled) {
897 		/*
898 		 * No tracker is available, or the qpair is disabled due to
899 		 *  an in-progress controller-level reset or controller
900 		 *  failure.
901 		 */
902 
903 		if (qpair->ctrlr->is_failed) {
904 			/*
905 			 * The controller has failed.  Post the request to a
906 			 *  task where it will be aborted, so that we do not
907 			 *  invoke the request's callback in the context
908 			 *  of the submission.
909 			 */
910 			nvme_ctrlr_post_failed_request(qpair->ctrlr, req);
911 		} else {
912 			/*
913 			 * Put the request on the qpair's request queue to be
914 			 *  processed when a tracker frees up via a command
915 			 *  completion or when the controller reset is
916 			 *  completed.
917 			 */
918 			STAILQ_INSERT_TAIL(&qpair->queued_req, req, stailq);
919 		}
920 		return;
921 	}
922 
923 	TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
924 	TAILQ_INSERT_TAIL(&qpair->outstanding_tr, tr, tailq);
925 	tr->req = req;
926 
927 	switch (req->type) {
928 	case NVME_REQUEST_VADDR:
929 		KASSERT(req->payload_size <= qpair->ctrlr->max_xfer_size,
930 		    ("payload_size (%d) exceeds max_xfer_size (%d)\n",
931 		    req->payload_size, qpair->ctrlr->max_xfer_size));
932 		err = bus_dmamap_load(tr->qpair->dma_tag_payload,
933 		    tr->payload_dma_map, req->u.payload, req->payload_size,
934 		    nvme_payload_map, tr, 0);
935 		if (err != 0)
936 			nvme_printf(qpair->ctrlr,
937 			    "bus_dmamap_load returned 0x%x!\n", err);
938 		break;
939 	case NVME_REQUEST_NULL:
940 		nvme_qpair_submit_tracker(tr->qpair, tr);
941 		break;
942 #ifdef NVME_UNMAPPED_BIO_SUPPORT
943 	case NVME_REQUEST_BIO:
944 		KASSERT(req->u.bio->bio_bcount <= qpair->ctrlr->max_xfer_size,
945 		    ("bio->bio_bcount (%jd) exceeds max_xfer_size (%d)\n",
946 		    (intmax_t)req->u.bio->bio_bcount,
947 		    qpair->ctrlr->max_xfer_size));
948 		err = bus_dmamap_load_bio(tr->qpair->dma_tag_payload,
949 		    tr->payload_dma_map, req->u.bio, nvme_payload_map, tr, 0);
950 		if (err != 0)
951 			nvme_printf(qpair->ctrlr,
952 			    "bus_dmamap_load_bio returned 0x%x!\n", err);
953 		break;
954 #endif
955 	case NVME_REQUEST_CCB:
956 		err = bus_dmamap_load_ccb(tr->qpair->dma_tag_payload,
957 		    tr->payload_dma_map, req->u.payload,
958 		    nvme_payload_map, tr, 0);
959 		if (err != 0)
960 			nvme_printf(qpair->ctrlr,
961 			    "bus_dmamap_load_ccb returned 0x%x!\n", err);
962 		break;
963 	default:
964 		panic("unknown nvme request type 0x%x\n", req->type);
965 		break;
966 	}
967 
968 	if (err != 0) {
969 		/*
970 		 * The dmamap operation failed, so we manually fail the
971 		 *  tracker here with DATA_TRANSFER_ERROR status.
972 		 *
973 		 * nvme_qpair_manual_complete_tracker must not be called
974 		 *  with the qpair lock held.
975 		 */
976 		mtx_unlock(&qpair->lock);
977 		nvme_qpair_manual_complete_tracker(qpair, tr, NVME_SCT_GENERIC,
978 		    NVME_SC_DATA_TRANSFER_ERROR, 1 /* do not retry */, TRUE);
979 		mtx_lock(&qpair->lock);
980 	}
981 }
982 
983 void
984 nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
985 {
986 
987 	mtx_lock(&qpair->lock);
988 	_nvme_qpair_submit_request(qpair, req);
989 	mtx_unlock(&qpair->lock);
990 }
991 
992 static void
993 nvme_qpair_enable(struct nvme_qpair *qpair)
994 {
995 
996 	qpair->is_enabled = TRUE;
997 }
998 
999 void
1000 nvme_qpair_reset(struct nvme_qpair *qpair)
1001 {
1002 
1003 	qpair->sq_head = qpair->sq_tail = qpair->cq_head = 0;
1004 
1005 	/*
1006 	 * First time through the completion queue, HW will set phase
1007 	 *  bit on completions to 1.  So set this to 1 here, indicating
1008 	 *  we're looking for a 1 to know which entries have completed.
1009 	 *  we'll toggle the bit each time when the completion queue
1010 	 *  rolls over.
1011 	 */
1012 	qpair->phase = 1;
1013 
1014 	memset(qpair->cmd, 0,
1015 	    qpair->num_entries * sizeof(struct nvme_command));
1016 	memset(qpair->cpl, 0,
1017 	    qpair->num_entries * sizeof(struct nvme_completion));
1018 }
1019 
1020 void
1021 nvme_admin_qpair_enable(struct nvme_qpair *qpair)
1022 {
1023 	struct nvme_tracker		*tr;
1024 	struct nvme_tracker		*tr_temp;
1025 
1026 	/*
1027 	 * Manually abort each outstanding admin command.  Do not retry
1028 	 *  admin commands found here, since they will be left over from
1029 	 *  a controller reset and its likely the context in which the
1030 	 *  command was issued no longer applies.
1031 	 */
1032 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1033 		nvme_printf(qpair->ctrlr,
1034 		    "aborting outstanding admin command\n");
1035 		nvme_qpair_manual_complete_tracker(qpair, tr, NVME_SCT_GENERIC,
1036 		    NVME_SC_ABORTED_BY_REQUEST, 1 /* do not retry */, TRUE);
1037 	}
1038 
1039 	nvme_qpair_enable(qpair);
1040 }
1041 
1042 void
1043 nvme_io_qpair_enable(struct nvme_qpair *qpair)
1044 {
1045 	STAILQ_HEAD(, nvme_request)	temp;
1046 	struct nvme_tracker		*tr;
1047 	struct nvme_tracker		*tr_temp;
1048 	struct nvme_request		*req;
1049 
1050 	/*
1051 	 * Manually abort each outstanding I/O.  This normally results in a
1052 	 *  retry, unless the retry count on the associated request has
1053 	 *  reached its limit.
1054 	 */
1055 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1056 		nvme_printf(qpair->ctrlr, "aborting outstanding i/o\n");
1057 		nvme_qpair_manual_complete_tracker(qpair, tr, NVME_SCT_GENERIC,
1058 		    NVME_SC_ABORTED_BY_REQUEST, 0, TRUE);
1059 	}
1060 
1061 	mtx_lock(&qpair->lock);
1062 
1063 	nvme_qpair_enable(qpair);
1064 
1065 	STAILQ_INIT(&temp);
1066 	STAILQ_SWAP(&qpair->queued_req, &temp, nvme_request);
1067 
1068 	while (!STAILQ_EMPTY(&temp)) {
1069 		req = STAILQ_FIRST(&temp);
1070 		STAILQ_REMOVE_HEAD(&temp, stailq);
1071 		nvme_printf(qpair->ctrlr, "resubmitting queued i/o\n");
1072 		nvme_qpair_print_command(qpair, &req->cmd);
1073 		_nvme_qpair_submit_request(qpair, req);
1074 	}
1075 
1076 	mtx_unlock(&qpair->lock);
1077 }
1078 
1079 static void
1080 nvme_qpair_disable(struct nvme_qpair *qpair)
1081 {
1082 	struct nvme_tracker *tr;
1083 
1084 	qpair->is_enabled = FALSE;
1085 	mtx_lock(&qpair->lock);
1086 	TAILQ_FOREACH(tr, &qpair->outstanding_tr, tailq)
1087 		callout_stop(&tr->timer);
1088 	mtx_unlock(&qpair->lock);
1089 }
1090 
1091 void
1092 nvme_admin_qpair_disable(struct nvme_qpair *qpair)
1093 {
1094 
1095 	nvme_qpair_disable(qpair);
1096 	nvme_admin_qpair_abort_aers(qpair);
1097 }
1098 
1099 void
1100 nvme_io_qpair_disable(struct nvme_qpair *qpair)
1101 {
1102 
1103 	nvme_qpair_disable(qpair);
1104 }
1105 
1106 void
1107 nvme_qpair_fail(struct nvme_qpair *qpair)
1108 {
1109 	struct nvme_tracker		*tr;
1110 	struct nvme_request		*req;
1111 
1112 	if (!mtx_initialized(&qpair->lock))
1113 		return;
1114 
1115 	mtx_lock(&qpair->lock);
1116 
1117 	while (!STAILQ_EMPTY(&qpair->queued_req)) {
1118 		req = STAILQ_FIRST(&qpair->queued_req);
1119 		STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
1120 		nvme_printf(qpair->ctrlr, "failing queued i/o\n");
1121 		mtx_unlock(&qpair->lock);
1122 		nvme_qpair_manual_complete_request(qpair, req, NVME_SCT_GENERIC,
1123 		    NVME_SC_ABORTED_BY_REQUEST, TRUE);
1124 		mtx_lock(&qpair->lock);
1125 	}
1126 
1127 	/* Manually abort each outstanding I/O. */
1128 	while (!TAILQ_EMPTY(&qpair->outstanding_tr)) {
1129 		tr = TAILQ_FIRST(&qpair->outstanding_tr);
1130 		/*
1131 		 * Do not remove the tracker.  The abort_tracker path will
1132 		 *  do that for us.
1133 		 */
1134 		nvme_printf(qpair->ctrlr, "failing outstanding i/o\n");
1135 		mtx_unlock(&qpair->lock);
1136 		nvme_qpair_manual_complete_tracker(qpair, tr, NVME_SCT_GENERIC,
1137 		    NVME_SC_ABORTED_BY_REQUEST, 1 /* do not retry */, TRUE);
1138 		mtx_lock(&qpair->lock);
1139 	}
1140 
1141 	mtx_unlock(&qpair->lock);
1142 }
1143 
1144