xref: /freebsd/sys/dev/nvme/nvme_qpair.c (revision 5e0ba47aa00ed82a4a06cc45f0d1b34b6948e47f)
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/param.h>
30 #include <sys/bus.h>
31 #include <sys/conf.h>
32 #include <sys/domainset.h>
33 #include <sys/proc.h>
34 #include <sys/sbuf.h>
35 
36 #include <dev/pci/pcivar.h>
37 
38 #include "nvme_private.h"
39 
40 typedef enum error_print { ERROR_PRINT_NONE, ERROR_PRINT_NO_RETRY, ERROR_PRINT_ALL } error_print_t;
41 #define DO_NOT_RETRY	1
42 
43 static void	_nvme_qpair_submit_request(struct nvme_qpair *qpair,
44 					   struct nvme_request *req);
45 static void	nvme_qpair_destroy(struct nvme_qpair *qpair);
46 
47 static const char *
get_opcode_string(bool admin,uint8_t opc,char * buf,size_t len)48 get_opcode_string(bool admin, uint8_t opc, char *buf, size_t len)
49 {
50 	struct sbuf sb;
51 
52 	sbuf_new(&sb, buf, len, SBUF_FIXEDLEN);
53 	nvme_opcode_sbuf(admin, opc, &sb);
54 	if (sbuf_finish(&sb) != 0)
55 		return ("");
56 	return (buf);
57 }
58 
59 static void
nvme_admin_qpair_print_command(struct nvme_qpair * qpair,struct nvme_command * cmd)60 nvme_admin_qpair_print_command(struct nvme_qpair *qpair,
61     struct nvme_command *cmd)
62 {
63 	char buf[64];
64 
65 	nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%x "
66 	    "cdw10:%08x cdw11:%08x\n",
67 	    get_opcode_string(true, cmd->opc, buf, sizeof(buf)), qpair->id,
68 	    cmd->cid, le32toh(cmd->nsid), le32toh(cmd->cdw10),
69 	    le32toh(cmd->cdw11));
70 }
71 
72 static void
nvme_io_qpair_print_command(struct nvme_qpair * qpair,struct nvme_command * cmd)73 nvme_io_qpair_print_command(struct nvme_qpair *qpair,
74     struct nvme_command *cmd)
75 {
76 	char buf[64];
77 
78 	switch (cmd->opc) {
79 	case NVME_OPC_WRITE:
80 	case NVME_OPC_READ:
81 	case NVME_OPC_WRITE_UNCORRECTABLE:
82 	case NVME_OPC_COMPARE:
83 	case NVME_OPC_WRITE_ZEROES:
84 	case NVME_OPC_VERIFY:
85 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d "
86 		    "lba:%llu len:%d\n",
87 		    get_opcode_string(false, cmd->opc, buf, sizeof(buf)),
88 		    qpair->id, cmd->cid, le32toh(cmd->nsid),
89 		    ((unsigned long long)le32toh(cmd->cdw11) << 32) + le32toh(cmd->cdw10),
90 		    (le32toh(cmd->cdw12) & 0xFFFF) + 1);
91 		break;
92 	default:
93 		nvme_printf(qpair->ctrlr, "%s sqid:%d cid:%d nsid:%d\n",
94 		    get_opcode_string(false, cmd->opc, buf, sizeof(buf)),
95 		    qpair->id, cmd->cid, le32toh(cmd->nsid));
96 		break;
97 	}
98 }
99 
100 void
nvme_qpair_print_command(struct nvme_qpair * qpair,struct nvme_command * cmd)101 nvme_qpair_print_command(struct nvme_qpair *qpair, struct nvme_command *cmd)
102 {
103 	if (qpair->id == 0)
104 		nvme_admin_qpair_print_command(qpair, cmd);
105 	else
106 		nvme_io_qpair_print_command(qpair, cmd);
107 	if (nvme_verbose_cmd_dump) {
108 		nvme_printf(qpair->ctrlr,
109 		    "nsid:%#x rsvd2:%#x rsvd3:%#x mptr:%#jx prp1:%#jx prp2:%#jx\n",
110 		    cmd->nsid, cmd->rsvd2, cmd->rsvd3, (uintmax_t)cmd->mptr,
111 		    (uintmax_t)cmd->prp1, (uintmax_t)cmd->prp2);
112 		nvme_printf(qpair->ctrlr,
113 		    "cdw10: %#x cdw11:%#x cdw12:%#x cdw13:%#x cdw14:%#x cdw15:%#x\n",
114 		    cmd->cdw10, cmd->cdw11, cmd->cdw12, cmd->cdw13, cmd->cdw14,
115 		    cmd->cdw15);
116 	}
117 }
118 
119 static const char *
get_status_string(const struct nvme_completion * cpl,char * buf,size_t len)120 get_status_string(const struct nvme_completion *cpl, char *buf, size_t len)
121 {
122 	struct sbuf sb;
123 
124 	sbuf_new(&sb, buf, len, SBUF_FIXEDLEN);
125 	nvme_sc_sbuf(cpl, &sb);
126 	if (sbuf_finish(&sb) != 0)
127 		return ("");
128 	return (buf);
129 }
130 
131 void
nvme_qpair_print_completion(struct nvme_qpair * qpair,struct nvme_completion * cpl)132 nvme_qpair_print_completion(struct nvme_qpair *qpair,
133     struct nvme_completion *cpl)
134 {
135 	char buf[64];
136 	uint8_t crd, m, dnr, p;
137 
138 	crd = NVME_STATUS_GET_CRD(cpl->status);
139 	m = NVME_STATUS_GET_M(cpl->status);
140 	dnr = NVME_STATUS_GET_DNR(cpl->status);
141 	p = NVME_STATUS_GET_P(cpl->status);
142 
143 	nvme_printf(qpair->ctrlr, "%s crd:%x m:%x dnr:%x p:%d "
144 	    "sqid:%d cid:%d cdw0:%x\n",
145 	    get_status_string(cpl, buf, sizeof(buf)), crd, m, dnr, p,
146 	    cpl->sqid, cpl->cid, cpl->cdw0);
147 }
148 
149 static bool
nvme_completion_is_retry(const struct nvme_completion * cpl)150 nvme_completion_is_retry(const struct nvme_completion *cpl)
151 {
152 	uint8_t sct, sc, dnr;
153 
154 	sct = NVME_STATUS_GET_SCT(cpl->status);
155 	sc = NVME_STATUS_GET_SC(cpl->status);
156 	dnr = NVME_STATUS_GET_DNR(cpl->status);	/* Do Not Retry Bit */
157 
158 	/*
159 	 * TODO: spec is not clear how commands that are aborted due
160 	 *  to TLER will be marked.  So for now, it seems
161 	 *  NAMESPACE_NOT_READY is the only case where we should
162 	 *  look at the DNR bit. Requests failed with ABORTED_BY_REQUEST
163 	 *  set the DNR bit correctly since the driver controls that.
164 	 */
165 	switch (sct) {
166 	case NVME_SCT_GENERIC:
167 		switch (sc) {
168 		case NVME_SC_ABORTED_BY_REQUEST:
169 		case NVME_SC_NAMESPACE_NOT_READY:
170 			if (dnr)
171 				return (0);
172 			else
173 				return (1);
174 		case NVME_SC_INVALID_OPCODE:
175 		case NVME_SC_INVALID_FIELD:
176 		case NVME_SC_COMMAND_ID_CONFLICT:
177 		case NVME_SC_DATA_TRANSFER_ERROR:
178 		case NVME_SC_ABORTED_POWER_LOSS:
179 		case NVME_SC_INTERNAL_DEVICE_ERROR:
180 		case NVME_SC_ABORTED_SQ_DELETION:
181 		case NVME_SC_ABORTED_FAILED_FUSED:
182 		case NVME_SC_ABORTED_MISSING_FUSED:
183 		case NVME_SC_INVALID_NAMESPACE_OR_FORMAT:
184 		case NVME_SC_COMMAND_SEQUENCE_ERROR:
185 		case NVME_SC_LBA_OUT_OF_RANGE:
186 		case NVME_SC_CAPACITY_EXCEEDED:
187 		default:
188 			return (0);
189 		}
190 	case NVME_SCT_COMMAND_SPECIFIC:
191 	case NVME_SCT_MEDIA_ERROR:
192 		return (0);
193 	case NVME_SCT_PATH_RELATED:
194 		switch (sc) {
195 		case NVME_SC_INTERNAL_PATH_ERROR:
196 			if (dnr)
197 				return (0);
198 			else
199 				return (1);
200 		default:
201 			return (0);
202 		}
203 	case NVME_SCT_VENDOR_SPECIFIC:
204 	default:
205 		return (0);
206 	}
207 }
208 
209 static void
nvme_qpair_complete_tracker(struct nvme_tracker * tr,struct nvme_completion * cpl,error_print_t print_on_error)210 nvme_qpair_complete_tracker(struct nvme_tracker *tr,
211     struct nvme_completion *cpl, error_print_t print_on_error)
212 {
213 	struct nvme_qpair	*qpair = tr->qpair;
214 	struct nvme_request	*req;
215 	bool			retry, error, retriable;
216 
217 	mtx_assert(&qpair->lock, MA_NOTOWNED);
218 
219 	req = tr->req;
220 	error = nvme_completion_is_error(cpl);
221 	retriable = nvme_completion_is_retry(cpl);
222 	retry = error && retriable && req->retries < nvme_retry_count;
223 	if (retry)
224 		qpair->num_retries++;
225 	if (error && req->retries >= nvme_retry_count && retriable)
226 		qpair->num_failures++;
227 
228 	if (error && (print_on_error == ERROR_PRINT_ALL ||
229 		(!retry && print_on_error == ERROR_PRINT_NO_RETRY))) {
230 		nvme_qpair_print_command(qpair, &req->cmd);
231 		nvme_qpair_print_completion(qpair, cpl);
232 	}
233 
234 	qpair->act_tr[cpl->cid - qpair->cid_base] = NULL;
235 
236 	KASSERT(cpl->cid == req->cmd.cid, ("cpl cid does not match cmd cid\n"));
237 
238 	if (!retry) {
239 		if (req->payload_valid) {
240 			bus_dmamap_sync(qpair->dma_tag_payload,
241 			    tr->payload_dma_map,
242 			    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
243 		}
244 		if (req->cb_fn)
245 			req->cb_fn(req->cb_arg, cpl);
246 	}
247 
248 	mtx_lock(&qpair->lock);
249 
250 	if (retry) {
251 		req->retries++;
252 		nvme_qpair_submit_tracker(qpair, tr);
253 	} else {
254 		if (req->payload_valid) {
255 			bus_dmamap_unload(qpair->dma_tag_payload,
256 			    tr->payload_dma_map);
257 		}
258 
259 		nvme_free_request(req);
260 		tr->req = NULL;
261 
262 		TAILQ_REMOVE(&qpair->outstanding_tr, tr, tailq);
263 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
264 
265 		/*
266 		 * If the controller is in the middle of resetting, don't
267 		 *  try to submit queued requests here - let the reset logic
268 		 *  handle that instead.
269 		 */
270 		if (!STAILQ_EMPTY(&qpair->queued_req) &&
271 		    !qpair->ctrlr->is_resetting) {
272 			req = STAILQ_FIRST(&qpair->queued_req);
273 			STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
274 			_nvme_qpair_submit_request(qpair, req);
275 		}
276 	}
277 
278 	mtx_unlock(&qpair->lock);
279 }
280 
281 static uint32_t
nvme_qpair_make_status(uint32_t sct,uint32_t sc,uint32_t dnr)282 nvme_qpair_make_status(uint32_t sct, uint32_t sc, uint32_t dnr)
283 {
284 	uint32_t status = 0;
285 
286 	status |= NVMEF(NVME_STATUS_SCT, sct);
287 	status |= NVMEF(NVME_STATUS_SC, sc);
288 	status |= NVMEF(NVME_STATUS_DNR, dnr);
289 	/* M=0 : this is artificial so no data in error log page */
290 	/* CRD=0 : this is artificial and no delayed retry support anyway */
291 	/* P=0 : phase not checked */
292 	return (status);
293 }
294 
295 static void
nvme_qpair_manual_complete_tracker(struct nvme_tracker * tr,uint32_t sct,uint32_t sc,uint32_t dnr,error_print_t print_on_error)296 nvme_qpair_manual_complete_tracker(
297     struct nvme_tracker *tr, uint32_t sct, uint32_t sc, uint32_t dnr,
298     error_print_t print_on_error)
299 {
300 	struct nvme_completion	cpl;
301 	struct nvme_qpair * qpair = tr->qpair;
302 
303 	mtx_assert(&qpair->lock, MA_NOTOWNED);
304 
305 	memset(&cpl, 0, sizeof(cpl));
306 
307 	cpl.sqid = qpair->id;
308 	cpl.cid = qpair->cid_base + tr->cid;
309 	cpl.status = nvme_qpair_make_status(sct, sc, dnr);
310 	nvme_qpair_complete_tracker(tr, &cpl, print_on_error);
311 }
312 
313 static void
nvme_qpair_manual_complete_request(struct nvme_qpair * qpair,struct nvme_request * req,uint32_t sct,uint32_t sc,uint32_t dnr,error_print_t print_on_error)314 nvme_qpair_manual_complete_request(struct nvme_qpair *qpair,
315     struct nvme_request *req, uint32_t sct, uint32_t sc, uint32_t dnr,
316     error_print_t print_on_error)
317 {
318 	struct nvme_completion	cpl;
319 	bool			error;
320 
321 	memset(&cpl, 0, sizeof(cpl));
322 	cpl.sqid = qpair->id;
323 	cpl.status = nvme_qpair_make_status(sct, sc, dnr);
324 	error = nvme_completion_is_error(&cpl);
325 
326 	if (error && print_on_error == ERROR_PRINT_ALL) {
327 		nvme_qpair_print_command(qpair, &req->cmd);
328 		nvme_qpair_print_completion(qpair, &cpl);
329 	}
330 
331 	if (req->cb_fn)
332 		req->cb_fn(req->cb_arg, &cpl);
333 
334 	nvme_free_request(req);
335 }
336 
337 /* Locked version of completion processor */
338 static bool
_nvme_qpair_process_completions(struct nvme_qpair * qpair)339 _nvme_qpair_process_completions(struct nvme_qpair *qpair)
340 {
341 	struct nvme_tracker	*tr;
342 	struct nvme_completion	cpl;
343 	bool done = false;
344 	bool in_panic = dumping || SCHEDULER_STOPPED();
345 
346 	mtx_assert(&qpair->recovery, MA_OWNED);
347 
348 	/*
349 	 * qpair is not enabled, likely because a controller reset is in
350 	 * progress.  Ignore the interrupt - any I/O that was associated with
351 	 * this interrupt will get retried when the reset is complete. Any
352 	 * pending completions for when we're in startup will be completed
353 	 * as soon as initialization is complete and we start sending commands
354 	 * to the device.
355 	 */
356 	if (qpair->recovery_state != RECOVERY_NONE) {
357 		qpair->num_ignored++;
358 		return (false);
359 	}
360 
361 	/*
362 	 * Sanity check initialization. After we reset the hardware, the phase
363 	 * is defined to be 1. So if we get here with zero prior calls and the
364 	 * phase is 0, it means that we've lost a race between the
365 	 * initialization and the ISR running. With the phase wrong, we'll
366 	 * process a bunch of completions that aren't really completions leading
367 	 * to a KASSERT below.
368 	 */
369 	KASSERT(!(qpair->num_intr_handler_calls == 0 && qpair->phase == 0),
370 	    ("%s: Phase wrong for first interrupt call.",
371 		device_get_nameunit(qpair->ctrlr->dev)));
372 
373 	qpair->num_intr_handler_calls++;
374 
375 	bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
376 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
377 	/*
378 	 * A panic can stop the CPU this routine is running on at any point.  If
379 	 * we're called during a panic, complete the sq_head wrap protocol for
380 	 * the case where we are interrupted just after the increment at 1
381 	 * below, but before we can reset cq_head to zero at 2. Also cope with
382 	 * the case where we do the zero at 2, but may or may not have done the
383 	 * phase adjustment at step 3. The panic machinery flushes all pending
384 	 * memory writes, so we can make these strong ordering assumptions
385 	 * that would otherwise be unwise if we were racing in real time.
386 	 */
387 	if (__predict_false(in_panic)) {
388 		if (qpair->cq_head == qpair->num_entries) {
389 			/*
390 			 * Here we know that we need to zero cq_head and then negate
391 			 * the phase, which hasn't been assigned if cq_head isn't
392 			 * zero due to the atomic_store_rel.
393 			 */
394 			qpair->cq_head = 0;
395 			qpair->phase = !qpair->phase;
396 		} else if (qpair->cq_head == 0) {
397 			/*
398 			 * In this case, we know that the assignment at 2
399 			 * happened below, but we don't know if it 3 happened or
400 			 * not. To do this, we look at the last completion
401 			 * entry and set the phase to the opposite phase
402 			 * that it has. This gets us back in sync
403 			 */
404 			cpl = qpair->cpl[qpair->num_entries - 1];
405 			nvme_completion_swapbytes(&cpl);
406 			qpair->phase = !NVME_STATUS_GET_P(cpl.status);
407 		}
408 	}
409 
410 	while (1) {
411 		uint16_t status;
412 
413 		/*
414 		 * We need to do this dance to avoid a race between the host and
415 		 * the device where the device overtakes the host while the host
416 		 * is reading this record, leaving the status field 'new' and
417 		 * the sqhd and cid fields potentially stale. If the phase
418 		 * doesn't match, that means status hasn't yet been updated and
419 		 * we'll get any pending changes next time. It also means that
420 		 * the phase must be the same the second time. We have to sync
421 		 * before reading to ensure any bouncing completes.
422 		 */
423 		status = le16toh(qpair->cpl[qpair->cq_head].status);
424 		if (NVME_STATUS_GET_P(status) != qpair->phase)
425 			break;
426 
427 		bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
428 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
429 		cpl = qpair->cpl[qpair->cq_head];
430 		nvme_completion_swapbytes(&cpl);
431 
432 		KASSERT(
433 		    NVME_STATUS_GET_P(status) == NVME_STATUS_GET_P(cpl.status),
434 		    ("Phase unexpectedly inconsistent"));
435 
436 		if (cpl.cid >= qpair->cid_base &&
437 		    cpl.cid < qpair->cid_base + qpair->num_trackers)
438 			tr = qpair->act_tr[cpl.cid - qpair->cid_base];
439 		else
440 			tr = NULL;
441 
442 		done = true;
443 		if (tr != NULL) {
444 			nvme_qpair_complete_tracker(tr, &cpl, ERROR_PRINT_ALL);
445 			qpair->sq_head = cpl.sqhd;
446 		} else if (!in_panic) {
447 			/*
448 			 * A missing tracker is normally an error.  However, a
449 			 * panic can stop the CPU this routine is running on
450 			 * after completing an I/O but before updating
451 			 * qpair->cq_head at 1 below.  Later, we re-enter this
452 			 * routine to poll I/O associated with the kernel
453 			 * dump. We find that the tr has been set to null before
454 			 * calling the completion routine.  If it hasn't
455 			 * completed (or it triggers a panic), then '1' below
456 			 * won't have updated cq_head. Rather than panic again,
457 			 * ignore this condition because it's not unexpected.
458 			 */
459 			nvme_printf(qpair->ctrlr,
460 			    "cpl (cid = %u) does not map to outstanding cmd\n",
461 				cpl.cid);
462 			nvme_qpair_print_completion(qpair,
463 			    &qpair->cpl[qpair->cq_head]);
464 			KASSERT(0, ("received completion for unknown cmd"));
465 		}
466 
467 		/*
468 		 * There's a number of races with the following (see above) when
469 		 * the system panics. We compensate for each one of them by
470 		 * using the atomic store to force strong ordering (at least when
471 		 * viewed in the aftermath of a panic).
472 		 */
473 		if (++qpair->cq_head == qpair->num_entries) {		/* 1 */
474 			atomic_store_rel_int(&qpair->cq_head, 0);	/* 2 */
475 			qpair->phase = !qpair->phase;			/* 3 */
476 		}
477 	}
478 
479 	if (done) {
480 		bus_write_4(qpair->ctrlr->resource, qpair->cq_hdbl_off,
481 		    qpair->cq_head);
482 	}
483 
484 	return (done);
485 }
486 
487 bool
nvme_qpair_process_completions(struct nvme_qpair * qpair)488 nvme_qpair_process_completions(struct nvme_qpair *qpair)
489 {
490 	bool done = false;
491 
492 	/*
493 	 * Interlock with reset / recovery code. This is an usually uncontended
494 	 * to make sure that we drain out of the ISRs before we reset the card
495 	 * and to prevent races with the recovery process called from a timeout
496 	 * context.
497 	 */
498 	mtx_lock(&qpair->recovery);
499 
500 	if (__predict_true(qpair->recovery_state == RECOVERY_NONE))
501 		done = _nvme_qpair_process_completions(qpair);
502 	else
503 		qpair->num_recovery_nolock++;	// XXX likely need to rename
504 
505 	mtx_unlock(&qpair->recovery);
506 
507 	return (done);
508 }
509 
510 static void
nvme_qpair_msi_handler(void * arg)511 nvme_qpair_msi_handler(void *arg)
512 {
513 	struct nvme_qpair *qpair = arg;
514 
515 	nvme_qpair_process_completions(qpair);
516 }
517 
518 int
nvme_qpair_construct(struct nvme_qpair * qpair,uint32_t num_entries,uint32_t num_trackers,struct nvme_controller * ctrlr)519 nvme_qpair_construct(struct nvme_qpair *qpair,
520     uint32_t num_entries, uint32_t num_trackers,
521     struct nvme_controller *ctrlr)
522 {
523 	struct nvme_tracker	*tr;
524 	size_t			cmdsz, cplsz, prpsz, allocsz, prpmemsz;
525 	uint64_t		queuemem_phys, prpmem_phys, list_phys;
526 	uint8_t			*queuemem, *prpmem, *prp_list;
527 	int			i, err;
528 
529 	qpair->vector = ctrlr->msi_count > 1 ? qpair->id : 0;
530 	qpair->num_entries = num_entries;
531 	qpair->num_trackers = num_trackers;
532 	qpair->ctrlr = ctrlr;
533 
534 	/* sqes[7:4]: max SQE size exponent; admin always 64 bytes per spec. */
535 	if (qpair->id != 0) {
536 		uint8_t sqes_max = (ctrlr->cdata.sqes >> 4) & 0xf;
537 		qpair->sqe_shift = (sqes_max > 6) ? (sqes_max - 6) : 0;
538 	} else {
539 		qpair->sqe_shift = 0;
540 	}
541 	if ((ctrlr->quirks & QUIRK_APPLE_SHARED_CID_SPACE) && qpair->id != 0)
542 		qpair->cid_base = ctrlr->adminq.num_trackers;
543 	else
544 		qpair->cid_base = 0;
545 
546 	mtx_init(&qpair->lock, "nvme qpair lock", NULL, MTX_DEF);
547 	mtx_init(&qpair->recovery, "nvme qpair recovery", NULL, MTX_DEF);
548 
549 	callout_init_mtx(&qpair->timer, &qpair->recovery, 0);
550 	qpair->timer_armed = false;
551 	qpair->recovery_state = RECOVERY_WAITING;
552 
553 	/* Note: NVMe PRP format is restricted to 4-byte alignment. */
554 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
555 	    4, ctrlr->page_size, BUS_SPACE_MAXADDR,
556 	    BUS_SPACE_MAXADDR, NULL, NULL, ctrlr->max_xfer_size,
557 	    howmany(ctrlr->max_xfer_size, ctrlr->page_size) + 1,
558 	    ctrlr->page_size, 0,
559 	    NULL, NULL, &qpair->dma_tag_payload);
560 	if (err != 0) {
561 		nvme_printf(ctrlr, "payload tag create failed %d\n", err);
562 		goto out;
563 	}
564 
565 	/*
566 	 * Each component must be page aligned, and individual PRP lists
567 	 * cannot cross a page boundary.
568 	 */
569 	cmdsz = qpair->num_entries * sizeof(struct nvme_command) << qpair->sqe_shift;
570 	cmdsz = roundup2(cmdsz, ctrlr->page_size);
571 	cplsz = qpair->num_entries * sizeof(struct nvme_completion);
572 	cplsz = roundup2(cplsz, ctrlr->page_size);
573 	/*
574 	 * For commands requiring more than 2 PRP entries, one PRP will be
575 	 * embedded in the command (prp1), and the rest of the PRP entries
576 	 * will be in a list pointed to by the command (prp2).
577 	 */
578 	prpsz = sizeof(uint64_t) *
579 	    howmany(ctrlr->max_xfer_size, ctrlr->page_size);
580 	prpmemsz = qpair->num_trackers * prpsz;
581 	allocsz = cmdsz + cplsz + prpmemsz;
582 
583 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
584 	    ctrlr->page_size, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
585 	    allocsz, 1, allocsz, 0, NULL, NULL, &qpair->dma_tag);
586 	if (err != 0) {
587 		nvme_printf(ctrlr, "tag create failed %d\n", err);
588 		goto out;
589 	}
590 	bus_dma_tag_set_domain(qpair->dma_tag, qpair->domain);
591 
592 	if (bus_dmamem_alloc(qpair->dma_tag, (void **)&queuemem,
593 	     BUS_DMA_COHERENT | BUS_DMA_NOWAIT, &qpair->queuemem_map)) {
594 		nvme_printf(ctrlr, "failed to alloc qpair memory\n");
595 		goto out;
596 	}
597 
598 	if (bus_dmamap_load(qpair->dma_tag, qpair->queuemem_map,
599 	    queuemem, allocsz, nvme_single_map, &queuemem_phys, 0) != 0) {
600 		nvme_printf(ctrlr, "failed to load qpair memory\n");
601 		bus_dmamem_free(qpair->dma_tag, qpair->cmd,
602 		    qpair->queuemem_map);
603 		goto out;
604 	}
605 
606 	qpair->num_cmds = 0;
607 	qpair->num_intr_handler_calls = 0;
608 	qpair->num_retries = 0;
609 	qpair->num_failures = 0;
610 	qpair->num_ignored = 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 	/*
619 	 * Calcuate the stride of the doorbell register. Many emulators set this
620 	 * value to correspond to a cache line. However, some hardware has set
621 	 * it to various small values.
622 	 */
623 	qpair->sq_tdbl_off = nvme_mmio_offsetof(doorbell[0]) +
624 	    (qpair->id << (ctrlr->dstrd + 1));
625 	qpair->cq_hdbl_off = nvme_mmio_offsetof(doorbell[0]) +
626 	    (qpair->id << (ctrlr->dstrd + 1)) + (1 << ctrlr->dstrd);
627 
628 	TAILQ_INIT(&qpair->free_tr);
629 	TAILQ_INIT(&qpair->outstanding_tr);
630 	STAILQ_INIT(&qpair->queued_req);
631 
632 	list_phys = prpmem_phys;
633 	prp_list = prpmem;
634 	for (i = 0; i < qpair->num_trackers; i++) {
635 		if (list_phys + prpsz > prpmem_phys + prpmemsz) {
636 			qpair->num_trackers = i;
637 			break;
638 		}
639 
640 		/*
641 		 * Make sure that the PRP list for this tracker doesn't
642 		 * overflow to another nvme page.
643 		 */
644 		if (trunc_page(list_phys) !=
645 		    trunc_page(list_phys + prpsz - 1)) {
646 			list_phys = roundup2(list_phys, ctrlr->page_size);
647 			prp_list =
648 			    (uint8_t *)roundup2((uintptr_t)prp_list, ctrlr->page_size);
649 		}
650 
651 		tr = malloc_domainset(sizeof(*tr), M_NVME,
652 		    DOMAINSET_PREF(qpair->domain), M_ZERO | M_WAITOK);
653 		bus_dmamap_create(qpair->dma_tag_payload, 0,
654 		    &tr->payload_dma_map);
655 		tr->cid = i;
656 		tr->qpair = qpair;
657 		tr->prp = (uint64_t *)prp_list;
658 		tr->prp_bus_addr = list_phys;
659 		TAILQ_INSERT_HEAD(&qpair->free_tr, tr, tailq);
660 		list_phys += prpsz;
661 		prp_list += prpsz;
662 	}
663 
664 	if (qpair->num_trackers == 0) {
665 		nvme_printf(ctrlr, "failed to allocate enough trackers\n");
666 		goto out;
667 	}
668 
669 	qpair->act_tr = malloc_domainset(sizeof(struct nvme_tracker *) *
670 	    qpair->num_entries, M_NVME, DOMAINSET_PREF(qpair->domain),
671 	    M_ZERO | M_WAITOK);
672 
673 	if (ctrlr->msi_count > 1) {
674 		/*
675 		 * MSI-X vector resource IDs start at 1, so we add one to
676 		 *  the queue's vector to get the corresponding rid to use.
677 		 */
678 		qpair->rid = qpair->vector + 1;
679 
680 		qpair->res = bus_alloc_resource_any(ctrlr->dev, SYS_RES_IRQ,
681 		    &qpair->rid, RF_ACTIVE);
682 		if (qpair->res == NULL) {
683 			nvme_printf(ctrlr, "unable to allocate MSI\n");
684 			goto out;
685 		}
686 		if (bus_setup_intr(ctrlr->dev, qpair->res,
687 		    INTR_TYPE_MISC | INTR_MPSAFE, NULL,
688 		    nvme_qpair_msi_handler, qpair, &qpair->tag) != 0) {
689 			nvme_printf(ctrlr, "unable to setup MSI\n");
690 			goto out;
691 		}
692 		if (qpair->id == 0) {
693 			bus_describe_intr(ctrlr->dev, qpair->res, qpair->tag,
694 			    "admin");
695 		} else {
696 			bus_describe_intr(ctrlr->dev, qpair->res, qpair->tag,
697 			    "io%d", qpair->id - 1);
698 		}
699 	}
700 
701 	return (0);
702 
703 out:
704 	nvme_qpair_destroy(qpair);
705 	return (ENOMEM);
706 }
707 
708 static void
nvme_qpair_destroy(struct nvme_qpair * qpair)709 nvme_qpair_destroy(struct nvme_qpair *qpair)
710 {
711 	struct nvme_tracker	*tr;
712 
713 	mtx_lock(&qpair->recovery);
714 	qpair->timer_armed = false;
715 	mtx_unlock(&qpair->recovery);
716 	callout_drain(&qpair->timer);
717 
718 	if (qpair->tag) {
719 		bus_teardown_intr(qpair->ctrlr->dev, qpair->res, qpair->tag);
720 		qpair->tag = NULL;
721 	}
722 
723 	if (qpair->act_tr) {
724 		free(qpair->act_tr, M_NVME);
725 		qpair->act_tr = NULL;
726 	}
727 
728 	while (!TAILQ_EMPTY(&qpair->free_tr)) {
729 		tr = TAILQ_FIRST(&qpair->free_tr);
730 		TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
731 		bus_dmamap_destroy(qpair->dma_tag_payload,
732 		    tr->payload_dma_map);
733 		free(tr, M_NVME);
734 	}
735 
736 	if (qpair->cmd != NULL) {
737 		bus_dmamap_unload(qpair->dma_tag, qpair->queuemem_map);
738 		bus_dmamem_free(qpair->dma_tag, qpair->cmd,
739 		    qpair->queuemem_map);
740 		qpair->cmd = NULL;
741 	}
742 
743 	if (qpair->dma_tag) {
744 		bus_dma_tag_destroy(qpair->dma_tag);
745 		qpair->dma_tag = NULL;
746 	}
747 
748 	if (qpair->dma_tag_payload) {
749 		bus_dma_tag_destroy(qpair->dma_tag_payload);
750 		qpair->dma_tag_payload = NULL;
751 	}
752 
753 	if (mtx_initialized(&qpair->lock))
754 		mtx_destroy(&qpair->lock);
755 	if (mtx_initialized(&qpair->recovery))
756 		mtx_destroy(&qpair->recovery);
757 
758 	if (qpair->res) {
759 		bus_release_resource(qpair->ctrlr->dev, SYS_RES_IRQ,
760 		    rman_get_rid(qpair->res), qpair->res);
761 		qpair->res = NULL;
762 	}
763 }
764 
765 static void
nvme_admin_qpair_abort_aers(struct nvme_qpair * qpair)766 nvme_admin_qpair_abort_aers(struct nvme_qpair *qpair)
767 {
768 	struct nvme_tracker	*tr;
769 
770 	/*
771 	 * nvme_complete_tracker must be called without the qpair lock held. It
772 	 * takes the lock to adjust outstanding_tr list, so make sure we don't
773 	 * have it yet. We need the lock to make the list traverse safe, but
774 	 * have to drop the lock to complete any AER. We restart the list scan
775 	 * when we do this to make this safe. There's interlock with the ISR so
776 	 * we know this tracker won't be completed twice.
777 	 */
778 	mtx_assert(&qpair->lock, MA_NOTOWNED);
779 
780 	mtx_lock(&qpair->lock);
781 	tr = TAILQ_FIRST(&qpair->outstanding_tr);
782 	while (tr != NULL) {
783 		if (tr->req->cmd.opc != NVME_OPC_ASYNC_EVENT_REQUEST) {
784 			tr = TAILQ_NEXT(tr, tailq);
785 			continue;
786 		}
787 		mtx_unlock(&qpair->lock);
788 		nvme_qpair_manual_complete_tracker(tr,
789 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_SQ_DELETION, 0,
790 		    ERROR_PRINT_NONE);
791 		mtx_lock(&qpair->lock);
792 		tr = TAILQ_FIRST(&qpair->outstanding_tr);
793 	}
794 	mtx_unlock(&qpair->lock);
795 }
796 
797 void
nvme_admin_qpair_destroy(struct nvme_qpair * qpair)798 nvme_admin_qpair_destroy(struct nvme_qpair *qpair)
799 {
800 	mtx_assert(&qpair->lock, MA_NOTOWNED);
801 
802 	nvme_admin_qpair_abort_aers(qpair);
803 	nvme_qpair_destroy(qpair);
804 }
805 
806 void
nvme_io_qpair_destroy(struct nvme_qpair * qpair)807 nvme_io_qpair_destroy(struct nvme_qpair *qpair)
808 {
809 	nvme_qpair_destroy(qpair);
810 }
811 
812 static void
nvme_abort_complete(void * arg,const struct nvme_completion * status)813 nvme_abort_complete(void *arg, const struct nvme_completion *status)
814 {
815 	struct nvme_tracker     *tr = arg;
816 
817 	/*
818 	 * If cdw0 bit 0 == 1, the controller was not able to abort the command
819 	 * we requested.  We still need to check the active tracker array, to
820 	 * cover race where I/O timed out at same time controller was completing
821 	 * the I/O. An abort command always is on the admin queue, but affects
822 	 * either an admin or an I/O queue, so take the appropriate qpair lock
823 	 * for the original command's queue, since we'll need it to avoid races
824 	 * with the completion code and to complete the command manually.
825 	 */
826 	mtx_lock(&tr->qpair->lock);
827 	if ((status->cdw0 & 1) == 1 && tr->qpair->act_tr[tr->cid] != NULL) {
828 		/*
829 		 * An I/O has timed out, and the controller was unable to abort
830 		 * it for some reason.  And we've not processed a completion for
831 		 * it yet. Construct a fake completion status, and then complete
832 		 * the I/O's tracker manually.
833 		 */
834 		nvme_printf(tr->qpair->ctrlr,
835 		    "abort command failed, aborting command manually\n");
836 		nvme_qpair_manual_complete_tracker(tr,
837 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST, 0, ERROR_PRINT_ALL);
838 	}
839 	/*
840 	 * XXX We don't check status for the possible 'Could not abort because
841 	 * excess aborts were submitted to the controller'. We don't prevent
842 	 * that, either. Document for the future here, since the standard is
843 	 * squishy and only says 'may generate' but implies anything is possible
844 	 * including hangs if you exceed the ACL.
845 	 */
846 	mtx_unlock(&tr->qpair->lock);
847 }
848 
849 static void
nvme_qpair_timeout(void * arg)850 nvme_qpair_timeout(void *arg)
851 {
852 	struct nvme_qpair	*qpair = arg;
853 	struct nvme_controller	*ctrlr = qpair->ctrlr;
854 	struct nvme_tracker	*tr;
855 	sbintime_t		now;
856 	bool			idle = true;
857 	bool			is_admin = qpair == &ctrlr->adminq;
858 	bool			fast;
859 	uint32_t		csts;
860 	uint8_t			cfs;
861 
862 	mtx_assert(&qpair->recovery, MA_OWNED);
863 
864 	/*
865 	 * If the controller is failed, then stop polling. This ensures that any
866 	 * failure processing that races with the qpair timeout will fail
867 	 * safely.
868 	 */
869 	if (is_admin ? qpair->ctrlr->is_failed_admin : qpair->ctrlr->is_failed) {
870 		nvme_printf(qpair->ctrlr,
871 		    "%sFailed controller, stopping watchdog timeout.\n",
872 		    is_admin ? "Complete " : "");
873 		qpair->timer_armed = false;
874 		return;
875 	}
876 
877 	/*
878 	 * Shutdown condition: We set qpair->timer_armed to false in
879 	 * nvme_qpair_destroy before calling callout_drain. When we call that,
880 	 * this routine might get called one last time. Exit w/o setting a
881 	 * timeout. None of the watchdog stuff needs to be done since we're
882 	 * destroying the qpair.
883 	 */
884 	if (!qpair->timer_armed) {
885 		nvme_printf(qpair->ctrlr,
886 		    "Timeout fired during nvme_qpair_destroy\n");
887 		return;
888 	}
889 
890 	switch (qpair->recovery_state) {
891 	case RECOVERY_NONE:
892 		/*
893 		 * Read csts to get value of cfs - controller fatal status.  If
894 		 * we are in the hot-plug or controller failed status proceed
895 		 * directly to reset. We also bail early if the status reads all
896 		 * 1's or the control fatal status bit is now 1. The latter is
897 		 * always true when the former is true, but not vice versa.  The
898 		 * intent of the code is that if the card is gone (all 1's) or
899 		 * we've failed, then try to do a reset (which someitmes
900 		 * unwedges a card reading all 1's that's not gone away, but
901 		 * usually doesn't).
902 		 */
903 		csts = nvme_mmio_read_4(ctrlr, csts);
904 		cfs = NVMEV(NVME_CSTS_REG_CFS, csts);
905 		if (csts == NVME_GONE || cfs == 1) {
906 			/*
907 			 * We've had a command timeout that we weren't able to
908 			 * abort or we have aborts disabled and any command
909 			 * timed out.
910 			 *
911 			 * If we get here due to a possible surprise hot-unplug
912 			 * event, then we let nvme_ctrlr_reset confirm and fail
913 			 * the controller.
914 			 */
915 do_reset:
916 			nvme_printf(ctrlr, "Resetting controller due to a timeout%s.\n",
917 			    (csts == 0xffffffff) ? " and possible hot unplug" :
918 			    (cfs ? " and fatal error status" : ""));
919 			qpair->recovery_state = RECOVERY_WAITING;
920 			nvme_ctrlr_reset(ctrlr);
921 			idle = false;
922 			break;
923 		}
924 
925 
926 		/*
927 		 * See if there's any recovery needed. First, do a fast check to
928 		 * see if anything could have timed out. If not, then skip
929 		 * everything else.
930 		 */
931 		fast = false;
932 		mtx_lock(&qpair->lock);
933 		now = getsbinuptime();
934 		TAILQ_FOREACH(tr, &qpair->outstanding_tr, tailq) {
935 			/*
936 			 * Skip async commands, they are posted to the card for
937 			 * an indefinite amount of time and have no deadline.
938 			 */
939 			if (tr->deadline == SBT_MAX)
940 				continue;
941 
942 			/*
943 			 * If the first real transaction is not in timeout, then
944 			 * we're done. Otherwise, we try recovery.
945 			 */
946 			idle = false;
947 			if (now <= tr->deadline)
948 				fast = true;
949 			break;
950 		}
951 		mtx_unlock(&qpair->lock);
952 		if (idle || fast)
953 			break;
954 
955 		/*
956 		 * There's a stale transaction at the start of the queue whose
957 		 * deadline has passed. Poll the competions as a last-ditch
958 		 * effort in case an interrupt has been missed. Warn the user if
959 		 * transactions were found of possible interrupt issues, but
960 		 * just once per controller.
961 		 */
962 		if (_nvme_qpair_process_completions(qpair) && !ctrlr->isr_warned) {
963 			nvme_printf(ctrlr, "System interrupt issues?\n");
964 			ctrlr->isr_warned = true;
965 		}
966 
967 		/*
968 		 * Now that we've run the ISR, re-rheck to see if there's any
969 		 * timed out commands and abort them or reset the card if so.
970 		 */
971 		mtx_lock(&qpair->lock);
972 		idle = true;
973 		TAILQ_FOREACH(tr, &qpair->outstanding_tr, tailq) {
974 			/*
975 			 * Skip async commands, they are posted to the card for
976 			 * an indefinite amount of time and have no deadline.
977 			 */
978 			if (tr->deadline == SBT_MAX)
979 				continue;
980 
981 			/*
982 			 * If we know this tracker hasn't timed out, we also
983 			 * know all subsequent ones haven't timed out. The tr
984 			 * queue is in submission order and all normal commands
985 			 * in a queue have the same timeout (or the timeout was
986 			 * changed by the user, but we eventually timeout then).
987 			 */
988 			idle = false;
989 			if (now <= tr->deadline)
990 				break;
991 
992 			/*
993 			 * Timeout expired, abort it or reset controller.
994 			 */
995 			if (ctrlr->enable_aborts &&
996 			    tr->req->cb_fn != nvme_abort_complete) {
997 				/*
998 				 * This isn't an abort command, ask for a
999 				 * hardware abort. This goes to the admin
1000 				 * queue which will reset the card if it
1001 				 * times out.
1002 				 */
1003 				nvme_ctrlr_cmd_abort(ctrlr,
1004 				    qpair->cid_base + tr->cid, qpair->id,
1005 				    nvme_abort_complete, tr);
1006 			} else {
1007 				/*
1008 				 * We have a live command in the card (either
1009 				 * one we couldn't abort, or aborts weren't
1010 				 * enabled).  We can only reset.
1011 				 */
1012 				mtx_unlock(&qpair->lock);
1013 				goto do_reset;
1014 			}
1015 		}
1016 		mtx_unlock(&qpair->lock);
1017 		break;
1018 
1019 	case RECOVERY_WAITING:
1020 		/*
1021 		 * These messages aren't interesting while we're suspended. We
1022 		 * put the queues into waiting state while
1023 		 * suspending. Suspending takes a while, so we'll see these
1024 		 * during that time and they aren't diagnostic. At other times,
1025 		 * they indicate a problem that's worth complaining about.
1026 		 */
1027 		if (!device_is_suspended(ctrlr->dev))
1028 			nvme_printf(ctrlr, "Waiting for reset to complete\n");
1029 		idle = false;		/* We want to keep polling */
1030 		break;
1031 	}
1032 
1033 	/*
1034 	 * Rearm the timeout.
1035 	 */
1036 	if (!idle) {
1037 		callout_schedule_sbt(&qpair->timer, SBT_1S / 2, SBT_1S / 2, 0);
1038 	} else {
1039 		qpair->timer_armed = false;
1040 	}
1041 }
1042 
1043 /*
1044  * Submit the tracker to the hardware. Must already be in the
1045  * outstanding queue when called.
1046  */
1047 void
nvme_qpair_submit_tracker(struct nvme_qpair * qpair,struct nvme_tracker * tr)1048 nvme_qpair_submit_tracker(struct nvme_qpair *qpair, struct nvme_tracker *tr)
1049 {
1050 	struct nvme_request	*req;
1051 	struct nvme_controller	*ctrlr;
1052 	int timeout;
1053 
1054 	mtx_assert(&qpair->lock, MA_OWNED);
1055 
1056 	req = tr->req;
1057 	req->cmd.cid = qpair->cid_base + tr->cid;
1058 	qpair->act_tr[tr->cid] = tr;
1059 	ctrlr = qpair->ctrlr;
1060 
1061 	if (req->timeout) {
1062 		if (req->cb_fn == nvme_completion_poll_cb)
1063 			timeout = 1;
1064 		else if (qpair->id == 0)
1065 			timeout = ctrlr->admin_timeout_period;
1066 		else
1067 			timeout = ctrlr->timeout_period;
1068 		tr->deadline = getsbinuptime() + timeout * SBT_1S;
1069 		if (!qpair->timer_armed) {
1070 			qpair->timer_armed = true;
1071 			callout_reset_sbt_on(&qpair->timer, SBT_1S / 2, SBT_1S / 2,
1072 			    nvme_qpair_timeout, qpair, qpair->cpu, 0);
1073 		}
1074 	} else
1075 		tr->deadline = SBT_MAX;
1076 
1077 	/* Copy the command from the tracker to the submission queue. */
1078 	memcpy(NVME_SQE(qpair, qpair->sq_tail), &req->cmd, sizeof(req->cmd));
1079 
1080 	if (++qpair->sq_tail == qpair->num_entries)
1081 		qpair->sq_tail = 0;
1082 
1083 	bus_dmamap_sync(qpair->dma_tag, qpair->queuemem_map,
1084 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1085 	bus_write_4(ctrlr->resource, qpair->sq_tdbl_off, qpair->sq_tail);
1086 	qpair->num_cmds++;
1087 }
1088 
1089 static void
nvme_payload_map(void * arg,bus_dma_segment_t * seg,int nseg,int error)1090 nvme_payload_map(void *arg, bus_dma_segment_t *seg, int nseg, int error)
1091 {
1092 	struct nvme_tracker 	*tr = arg;
1093 	uint32_t		cur_nseg;
1094 
1095 	/*
1096 	 * If the mapping operation failed, return immediately.  The caller
1097 	 *  is responsible for detecting the error status and failing the
1098 	 *  tracker manually.
1099 	 */
1100 	if (error != 0) {
1101 		nvme_printf(tr->qpair->ctrlr,
1102 		    "nvme_payload_map err %d\n", error);
1103 		return;
1104 	}
1105 
1106 	/*
1107 	 * Note that we specified ctrlr->page_size for alignment and max
1108 	 * segment size when creating the bus dma tags.  So here we can safely
1109 	 * just transfer each segment to its associated PRP entry.
1110 	 */
1111 	tr->req->cmd.prp1 = htole64(seg[0].ds_addr);
1112 
1113 	if (nseg == 2) {
1114 		tr->req->cmd.prp2 = htole64(seg[1].ds_addr);
1115 	} else if (nseg > 2) {
1116 		cur_nseg = 1;
1117 		tr->req->cmd.prp2 = htole64((uint64_t)tr->prp_bus_addr);
1118 		while (cur_nseg < nseg) {
1119 			tr->prp[cur_nseg-1] =
1120 			    htole64((uint64_t)seg[cur_nseg].ds_addr);
1121 			cur_nseg++;
1122 		}
1123 	} else {
1124 		/*
1125 		 * prp2 should not be used by the controller
1126 		 *  since there is only one segment, but set
1127 		 *  to 0 just to be safe.
1128 		 */
1129 		tr->req->cmd.prp2 = 0;
1130 	}
1131 
1132 	bus_dmamap_sync(tr->qpair->dma_tag_payload, tr->payload_dma_map,
1133 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1134 	nvme_qpair_submit_tracker(tr->qpair, tr);
1135 }
1136 
1137 static void
_nvme_qpair_submit_request(struct nvme_qpair * qpair,struct nvme_request * req)1138 _nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
1139 {
1140 	struct nvme_tracker	*tr;
1141 	int			err = 0;
1142 	bool			is_admin = qpair == &qpair->ctrlr->adminq;
1143 
1144 	mtx_assert(&qpair->lock, MA_OWNED);
1145 
1146 	tr = TAILQ_FIRST(&qpair->free_tr);
1147 	req->qpair = qpair;
1148 
1149 	/*
1150 	 * The controller has failed, so fail the request. Note, that this races
1151 	 * the recovery / timeout code. Since we hold the qpair lock, we know
1152 	 * it's safe to fail directly. is_failed is set when we fail the
1153 	 * controller.  It is only ever reset in the ioctl reset controller
1154 	 * path, which is safe to race (for failed controllers, we make no
1155 	 * guarantees about bringing it out of failed state relative to other
1156 	 * commands). We try hard to allow admin commands when the entire
1157 	 * controller hasn't failed, only something related to I/O queues.
1158 	 */
1159 	if (is_admin ? qpair->ctrlr->is_failed_admin : qpair->ctrlr->is_failed) {
1160 		nvme_qpair_manual_complete_request(qpair, req,
1161 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST, 1,
1162 		    ERROR_PRINT_NONE);
1163 		return;
1164 	}
1165 
1166 	/*
1167 	 * No tracker is available, or the qpair is disabled due to an
1168 	 * in-progress controller-level reset. If we lose the race with
1169 	 * recovery_state, then we may add an extra request to the queue which
1170 	 * will be resubmitted later.  We only set recovery_state to NONE with
1171 	 * qpair->lock also held, so if we observe that the state is not NONE,
1172 	 * we know it won't transition back to NONE without retrying queued
1173 	 * request.
1174 	 */
1175 	if (tr == NULL || qpair->recovery_state != RECOVERY_NONE) {
1176 		STAILQ_INSERT_TAIL(&qpair->queued_req, req, stailq);
1177 		return;
1178 	}
1179 
1180 	TAILQ_REMOVE(&qpair->free_tr, tr, tailq);
1181 	TAILQ_INSERT_TAIL(&qpair->outstanding_tr, tr, tailq);
1182 	tr->deadline = SBT_MAX;
1183 	tr->req = req;
1184 
1185 	if (!req->payload_valid) {
1186 		nvme_qpair_submit_tracker(tr->qpair, tr);
1187 		return;
1188 	}
1189 
1190 	/*
1191 	 * tr->deadline updating when nvme_payload_map calls
1192 	 * nvme_qpair_submit_tracker (we call it above directly
1193 	 * when there's no map to load).
1194 	 */
1195 	err = bus_dmamap_load_mem(tr->qpair->dma_tag_payload,
1196 	    tr->payload_dma_map, &req->payload, nvme_payload_map, tr, 0);
1197 	if (err != 0) {
1198 		/*
1199 		 * The dmamap operation failed, so we manually fail the
1200 		 *  tracker here with DATA_TRANSFER_ERROR status.
1201 		 *
1202 		 * nvme_qpair_manual_complete_tracker must not be called
1203 		 *  with the qpair lock held.
1204 		 */
1205 		nvme_printf(qpair->ctrlr,
1206 		    "bus_dmamap_load_mem returned 0x%x!\n", err);
1207 		mtx_unlock(&qpair->lock);
1208 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1209 		    NVME_SC_DATA_TRANSFER_ERROR, DO_NOT_RETRY, ERROR_PRINT_ALL);
1210 		mtx_lock(&qpair->lock);
1211 	}
1212 }
1213 
1214 void
nvme_qpair_submit_request(struct nvme_qpair * qpair,struct nvme_request * req)1215 nvme_qpair_submit_request(struct nvme_qpair *qpair, struct nvme_request *req)
1216 {
1217 	mtx_lock(&qpair->lock);
1218 	_nvme_qpair_submit_request(qpair, req);
1219 	mtx_unlock(&qpair->lock);
1220 }
1221 
1222 static void
nvme_qpair_enable(struct nvme_qpair * qpair)1223 nvme_qpair_enable(struct nvme_qpair *qpair)
1224 {
1225 	bool is_admin __diagused = qpair == &qpair->ctrlr->adminq;
1226 
1227 	if (mtx_initialized(&qpair->recovery))
1228 		mtx_assert(&qpair->recovery, MA_OWNED);
1229 	if (mtx_initialized(&qpair->lock))
1230 		mtx_assert(&qpair->lock, MA_OWNED);
1231 	KASSERT(!(is_admin ? qpair->ctrlr->is_failed_admin : qpair->ctrlr->is_failed),
1232 	    ("Enabling a failed qpair\n"));
1233 
1234 	qpair->recovery_state = RECOVERY_NONE;
1235 }
1236 
1237 void
nvme_qpair_reset(struct nvme_qpair * qpair)1238 nvme_qpair_reset(struct nvme_qpair *qpair)
1239 {
1240 	qpair->sq_head = qpair->sq_tail = qpair->cq_head = 0;
1241 
1242 	/*
1243 	 * First time through the completion queue, HW will set phase
1244 	 *  bit on completions to 1.  So set this to 1 here, indicating
1245 	 *  we're looking for a 1 to know which entries have completed.
1246 	 *  we'll toggle the bit each time when the completion queue
1247 	 *  rolls over.
1248 	 */
1249 	qpair->phase = 1;
1250 
1251 	memset(qpair->cmd, 0,
1252 	    qpair->num_entries * sizeof(struct nvme_command) << qpair->sqe_shift);
1253 	memset(qpair->cpl, 0,
1254 	    qpair->num_entries * sizeof(struct nvme_completion));
1255 }
1256 
1257 void
nvme_admin_qpair_enable(struct nvme_qpair * qpair)1258 nvme_admin_qpair_enable(struct nvme_qpair *qpair)
1259 {
1260 	struct nvme_tracker		*tr;
1261 	struct nvme_tracker		*tr_temp;
1262 	bool				rpt;
1263 
1264 	/*
1265 	 * Manually abort each outstanding admin command.  Do not retry
1266 	 * admin commands found here, since they will be left over from
1267 	 * a controller reset and its likely the context in which the
1268 	 * command was issued no longer applies.
1269 	 */
1270 	rpt = !TAILQ_EMPTY(&qpair->outstanding_tr);
1271 	if (rpt)
1272 		nvme_printf(qpair->ctrlr,
1273 		    "aborting outstanding admin command\n");
1274 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1275 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1276 		    NVME_SC_ABORTED_BY_REQUEST, DO_NOT_RETRY, ERROR_PRINT_ALL);
1277 	}
1278 	if (rpt)
1279 		nvme_printf(qpair->ctrlr,
1280 		    "done aborting outstanding admin\n");
1281 
1282 	mtx_lock(&qpair->recovery);
1283 	mtx_lock(&qpair->lock);
1284 	nvme_qpair_enable(qpair);
1285 	mtx_unlock(&qpair->lock);
1286 	mtx_unlock(&qpair->recovery);
1287 }
1288 
1289 void
nvme_io_qpair_enable(struct nvme_qpair * qpair)1290 nvme_io_qpair_enable(struct nvme_qpair *qpair)
1291 {
1292 	STAILQ_HEAD(, nvme_request)	temp;
1293 	struct nvme_tracker		*tr;
1294 	struct nvme_tracker		*tr_temp;
1295 	struct nvme_request		*req;
1296 	bool				report;
1297 
1298 	/*
1299 	 * Manually abort each outstanding I/O.  This normally results in a
1300 	 * retry, unless the retry count on the associated request has
1301 	 * reached its limit.
1302 	 */
1303 	report = !TAILQ_EMPTY(&qpair->outstanding_tr);
1304 	if (report)
1305 		nvme_printf(qpair->ctrlr, "aborting outstanding i/o\n");
1306 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1307 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1308 		    NVME_SC_ABORTED_BY_REQUEST, 0, ERROR_PRINT_NO_RETRY);
1309 	}
1310 	if (report)
1311 		nvme_printf(qpair->ctrlr, "done aborting outstanding i/o\n");
1312 
1313 	mtx_lock(&qpair->recovery);
1314 	mtx_lock(&qpair->lock);
1315 	nvme_qpair_enable(qpair);
1316 
1317 	STAILQ_INIT(&temp);
1318 	STAILQ_SWAP(&qpair->queued_req, &temp, nvme_request);
1319 
1320 	report = !STAILQ_EMPTY(&temp);
1321 	if (report)
1322 		nvme_printf(qpair->ctrlr, "resubmitting queued i/o\n");
1323 	while (!STAILQ_EMPTY(&temp)) {
1324 		req = STAILQ_FIRST(&temp);
1325 		STAILQ_REMOVE_HEAD(&temp, stailq);
1326 		nvme_qpair_print_command(qpair, &req->cmd);
1327 		_nvme_qpair_submit_request(qpair, req);
1328 	}
1329 	if (report)
1330 		nvme_printf(qpair->ctrlr, "done resubmitting i/o\n");
1331 
1332 	mtx_unlock(&qpair->lock);
1333 	mtx_unlock(&qpair->recovery);
1334 }
1335 
1336 static void
nvme_qpair_disable(struct nvme_qpair * qpair)1337 nvme_qpair_disable(struct nvme_qpair *qpair)
1338 {
1339 	struct nvme_tracker	*tr, *tr_temp;
1340 
1341 	if (mtx_initialized(&qpair->recovery))
1342 		mtx_assert(&qpair->recovery, MA_OWNED);
1343 	if (mtx_initialized(&qpair->lock))
1344 		mtx_assert(&qpair->lock, MA_OWNED);
1345 
1346 	qpair->recovery_state = RECOVERY_WAITING;
1347 	TAILQ_FOREACH_SAFE(tr, &qpair->outstanding_tr, tailq, tr_temp) {
1348 		tr->deadline = SBT_MAX;
1349 	}
1350 }
1351 
1352 void
nvme_admin_qpair_disable(struct nvme_qpair * qpair)1353 nvme_admin_qpair_disable(struct nvme_qpair *qpair)
1354 {
1355 	mtx_lock(&qpair->recovery);
1356 
1357 	mtx_lock(&qpair->lock);
1358 	nvme_qpair_disable(qpair);
1359 	mtx_unlock(&qpair->lock);
1360 
1361 	nvme_admin_qpair_abort_aers(qpair);
1362 
1363 	mtx_unlock(&qpair->recovery);
1364 }
1365 
1366 void
nvme_io_qpair_disable(struct nvme_qpair * qpair)1367 nvme_io_qpair_disable(struct nvme_qpair *qpair)
1368 {
1369 	mtx_lock(&qpair->recovery);
1370 	mtx_lock(&qpair->lock);
1371 
1372 	nvme_qpair_disable(qpair);
1373 
1374 	mtx_unlock(&qpair->lock);
1375 	mtx_unlock(&qpair->recovery);
1376 }
1377 
1378 void
nvme_qpair_fail(struct nvme_qpair * qpair)1379 nvme_qpair_fail(struct nvme_qpair *qpair)
1380 {
1381 	struct nvme_tracker		*tr;
1382 	struct nvme_request		*req;
1383 
1384 	if (!mtx_initialized(&qpair->lock))
1385 		return;
1386 
1387 	mtx_lock(&qpair->lock);
1388 
1389 	if (!STAILQ_EMPTY(&qpair->queued_req)) {
1390 		nvme_printf(qpair->ctrlr, "failing queued i/o\n");
1391 	}
1392 	while (!STAILQ_EMPTY(&qpair->queued_req)) {
1393 		req = STAILQ_FIRST(&qpair->queued_req);
1394 		STAILQ_REMOVE_HEAD(&qpair->queued_req, stailq);
1395 		mtx_unlock(&qpair->lock);
1396 		nvme_qpair_manual_complete_request(qpair, req, NVME_SCT_GENERIC,
1397 		    NVME_SC_ABORTED_BY_REQUEST, 1, ERROR_PRINT_ALL);
1398 		mtx_lock(&qpair->lock);
1399 	}
1400 
1401 	if (!TAILQ_EMPTY(&qpair->outstanding_tr)) {
1402 		nvme_printf(qpair->ctrlr, "failing outstanding i/o\n");
1403 	}
1404 	/* Manually abort each outstanding I/O. */
1405 	while (!TAILQ_EMPTY(&qpair->outstanding_tr)) {
1406 		tr = TAILQ_FIRST(&qpair->outstanding_tr);
1407 		/*
1408 		 * Do not remove the tracker.  The abort_tracker path will
1409 		 *  do that for us.
1410 		 */
1411 		mtx_unlock(&qpair->lock);
1412 		nvme_qpair_manual_complete_tracker(tr, NVME_SCT_GENERIC,
1413 		    NVME_SC_ABORTED_BY_REQUEST, DO_NOT_RETRY, ERROR_PRINT_ALL);
1414 		mtx_lock(&qpair->lock);
1415 	}
1416 
1417 	mtx_unlock(&qpair->lock);
1418 }
1419