xref: /freebsd/sys/dev/nvme/nvme_ctrlr.c (revision 05248206f720394d95c2a7475429311df670a2e9)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2012-2016 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 #include "opt_cam.h"
31 #include "opt_nvme.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/buf.h>
36 #include <sys/bus.h>
37 #include <sys/conf.h>
38 #include <sys/ioccom.h>
39 #include <sys/proc.h>
40 #include <sys/smp.h>
41 #include <sys/uio.h>
42 #include <sys/sbuf.h>
43 #include <sys/endian.h>
44 #include <machine/stdarg.h>
45 #include <vm/vm.h>
46 
47 #include "nvme_private.h"
48 
49 #define B4_CHK_RDY_DELAY_MS	2300		/* work around controller bug */
50 
51 static void nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
52 						struct nvme_async_event_request *aer);
53 
54 static void
55 nvme_ctrlr_barrier(struct nvme_controller *ctrlr, int flags)
56 {
57 	bus_barrier(ctrlr->resource, 0, rman_get_size(ctrlr->resource), flags);
58 }
59 
60 static void
61 nvme_ctrlr_devctl_log(struct nvme_controller *ctrlr, const char *type, const char *msg, ...)
62 {
63 	struct sbuf sb;
64 	va_list ap;
65 	int error;
66 
67 	if (sbuf_new(&sb, NULL, 0, SBUF_AUTOEXTEND | SBUF_NOWAIT) == NULL)
68 		return;
69 	sbuf_printf(&sb, "%s: ", device_get_nameunit(ctrlr->dev));
70 	va_start(ap, msg);
71 	sbuf_vprintf(&sb, msg, ap);
72 	va_end(ap);
73 	error = sbuf_finish(&sb);
74 	if (error == 0)
75 		printf("%s\n", sbuf_data(&sb));
76 
77 	sbuf_clear(&sb);
78 	sbuf_printf(&sb, "name=\"%s\" reason=\"", device_get_nameunit(ctrlr->dev));
79 	va_start(ap, msg);
80 	sbuf_vprintf(&sb, msg, ap);
81 	va_end(ap);
82 	sbuf_printf(&sb, "\"");
83 	error = sbuf_finish(&sb);
84 	if (error == 0)
85 		devctl_notify("nvme", "controller", type, sbuf_data(&sb));
86 	sbuf_delete(&sb);
87 }
88 
89 static int
90 nvme_ctrlr_construct_admin_qpair(struct nvme_controller *ctrlr)
91 {
92 	struct nvme_qpair	*qpair;
93 	uint32_t		num_entries;
94 	int			error;
95 
96 	qpair = &ctrlr->adminq;
97 	qpair->id = 0;
98 	qpair->cpu = CPU_FFS(&cpuset_domain[ctrlr->domain]) - 1;
99 	qpair->domain = ctrlr->domain;
100 
101 	num_entries = NVME_ADMIN_ENTRIES;
102 	TUNABLE_INT_FETCH("hw.nvme.admin_entries", &num_entries);
103 	/*
104 	 * If admin_entries was overridden to an invalid value, revert it
105 	 *  back to our default value.
106 	 */
107 	if (num_entries < NVME_MIN_ADMIN_ENTRIES ||
108 	    num_entries > NVME_MAX_ADMIN_ENTRIES) {
109 		nvme_printf(ctrlr, "invalid hw.nvme.admin_entries=%d "
110 		    "specified\n", num_entries);
111 		num_entries = NVME_ADMIN_ENTRIES;
112 	}
113 
114 	/*
115 	 * The admin queue's max xfer size is treated differently than the
116 	 *  max I/O xfer size.  16KB is sufficient here - maybe even less?
117 	 */
118 	error = nvme_qpair_construct(qpair, num_entries, NVME_ADMIN_TRACKERS,
119 	     ctrlr);
120 	return (error);
121 }
122 
123 #define QP(ctrlr, c)	((c) * (ctrlr)->num_io_queues / mp_ncpus)
124 
125 static int
126 nvme_ctrlr_construct_io_qpairs(struct nvme_controller *ctrlr)
127 {
128 	struct nvme_qpair	*qpair;
129 	uint32_t		cap_lo;
130 	uint16_t		mqes;
131 	int			c, error, i, n;
132 	int			num_entries, num_trackers, max_entries;
133 
134 	/*
135 	 * NVMe spec sets a hard limit of 64K max entries, but devices may
136 	 * specify a smaller limit, so we need to check the MQES field in the
137 	 * capabilities register. We have to cap the number of entries to the
138 	 * current stride allows for in BAR 0/1, otherwise the remainder entries
139 	 * are inaccessible. MQES should reflect this, and this is just a
140 	 * fail-safe.
141 	 */
142 	max_entries =
143 	    (rman_get_size(ctrlr->resource) - nvme_mmio_offsetof(doorbell[0])) /
144 	    (1 << (ctrlr->dstrd + 1));
145 	num_entries = NVME_IO_ENTRIES;
146 	TUNABLE_INT_FETCH("hw.nvme.io_entries", &num_entries);
147 	cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
148 	mqes = NVME_CAP_LO_MQES(cap_lo);
149 	num_entries = min(num_entries, mqes + 1);
150 	num_entries = min(num_entries, max_entries);
151 
152 	num_trackers = NVME_IO_TRACKERS;
153 	TUNABLE_INT_FETCH("hw.nvme.io_trackers", &num_trackers);
154 
155 	num_trackers = max(num_trackers, NVME_MIN_IO_TRACKERS);
156 	num_trackers = min(num_trackers, NVME_MAX_IO_TRACKERS);
157 	/*
158 	 * No need to have more trackers than entries in the submit queue.  Note
159 	 * also that for a queue size of N, we can only have (N-1) commands
160 	 * outstanding, hence the "-1" here.
161 	 */
162 	num_trackers = min(num_trackers, (num_entries-1));
163 
164 	/*
165 	 * Our best estimate for the maximum number of I/Os that we should
166 	 * normally have in flight at one time. This should be viewed as a hint,
167 	 * not a hard limit and will need to be revisited when the upper layers
168 	 * of the storage system grows multi-queue support.
169 	 */
170 	ctrlr->max_hw_pend_io = num_trackers * ctrlr->num_io_queues * 3 / 4;
171 
172 	ctrlr->ioq = malloc(ctrlr->num_io_queues * sizeof(struct nvme_qpair),
173 	    M_NVME, M_ZERO | M_WAITOK);
174 
175 	for (i = c = n = 0; i < ctrlr->num_io_queues; i++, c += n) {
176 		qpair = &ctrlr->ioq[i];
177 
178 		/*
179 		 * Admin queue has ID=0. IO queues start at ID=1 -
180 		 *  hence the 'i+1' here.
181 		 */
182 		qpair->id = i + 1;
183 		if (ctrlr->num_io_queues > 1) {
184 			/* Find number of CPUs served by this queue. */
185 			for (n = 1; QP(ctrlr, c + n) == i; n++)
186 				;
187 			/* Shuffle multiple NVMe devices between CPUs. */
188 			qpair->cpu = c + (device_get_unit(ctrlr->dev)+n/2) % n;
189 			qpair->domain = pcpu_find(qpair->cpu)->pc_domain;
190 		} else {
191 			qpair->cpu = CPU_FFS(&cpuset_domain[ctrlr->domain]) - 1;
192 			qpair->domain = ctrlr->domain;
193 		}
194 
195 		/*
196 		 * For I/O queues, use the controller-wide max_xfer_size
197 		 *  calculated in nvme_attach().
198 		 */
199 		error = nvme_qpair_construct(qpair, num_entries, num_trackers,
200 		    ctrlr);
201 		if (error)
202 			return (error);
203 
204 		/*
205 		 * Do not bother binding interrupts if we only have one I/O
206 		 *  interrupt thread for this controller.
207 		 */
208 		if (ctrlr->num_io_queues > 1)
209 			bus_bind_intr(ctrlr->dev, qpair->res, qpair->cpu);
210 	}
211 
212 	return (0);
213 }
214 
215 static void
216 nvme_ctrlr_fail(struct nvme_controller *ctrlr)
217 {
218 	int i;
219 
220 	ctrlr->is_failed = true;
221 	nvme_admin_qpair_disable(&ctrlr->adminq);
222 	nvme_qpair_fail(&ctrlr->adminq);
223 	if (ctrlr->ioq != NULL) {
224 		for (i = 0; i < ctrlr->num_io_queues; i++) {
225 			nvme_io_qpair_disable(&ctrlr->ioq[i]);
226 			nvme_qpair_fail(&ctrlr->ioq[i]);
227 		}
228 	}
229 	nvme_notify_fail_consumers(ctrlr);
230 }
231 
232 void
233 nvme_ctrlr_post_failed_request(struct nvme_controller *ctrlr,
234     struct nvme_request *req)
235 {
236 
237 	mtx_lock(&ctrlr->lock);
238 	STAILQ_INSERT_TAIL(&ctrlr->fail_req, req, stailq);
239 	mtx_unlock(&ctrlr->lock);
240 	if (!ctrlr->is_dying)
241 		taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->fail_req_task);
242 }
243 
244 static void
245 nvme_ctrlr_fail_req_task(void *arg, int pending)
246 {
247 	struct nvme_controller	*ctrlr = arg;
248 	struct nvme_request	*req;
249 
250 	mtx_lock(&ctrlr->lock);
251 	while ((req = STAILQ_FIRST(&ctrlr->fail_req)) != NULL) {
252 		STAILQ_REMOVE_HEAD(&ctrlr->fail_req, stailq);
253 		mtx_unlock(&ctrlr->lock);
254 		nvme_qpair_manual_complete_request(req->qpair, req,
255 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST);
256 		mtx_lock(&ctrlr->lock);
257 	}
258 	mtx_unlock(&ctrlr->lock);
259 }
260 
261 /*
262  * Wait for RDY to change.
263  *
264  * Starts sleeping for 1us and geometrically increases it the longer we wait,
265  * capped at 1ms.
266  */
267 static int
268 nvme_ctrlr_wait_for_ready(struct nvme_controller *ctrlr, int desired_val)
269 {
270 	int timeout = ticks + MSEC_2_TICKS(ctrlr->ready_timeout_in_ms);
271 	sbintime_t delta_t = SBT_1US;
272 	uint32_t csts;
273 
274 	while (1) {
275 		csts = nvme_mmio_read_4(ctrlr, csts);
276 		if (csts == NVME_GONE)		/* Hot unplug. */
277 			return (ENXIO);
278 		if (((csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK)
279 		    == desired_val)
280 			break;
281 		if (timeout - ticks < 0) {
282 			nvme_printf(ctrlr, "controller ready did not become %d "
283 			    "within %d ms\n", desired_val, ctrlr->ready_timeout_in_ms);
284 			return (ENXIO);
285 		}
286 
287 		pause_sbt("nvmerdy", delta_t, 0, C_PREL(1));
288 		delta_t = min(SBT_1MS, delta_t * 3 / 2);
289 	}
290 
291 	return (0);
292 }
293 
294 static int
295 nvme_ctrlr_disable(struct nvme_controller *ctrlr)
296 {
297 	uint32_t cc;
298 	uint32_t csts;
299 	uint8_t  en, rdy;
300 	int err;
301 
302 	cc = nvme_mmio_read_4(ctrlr, cc);
303 	csts = nvme_mmio_read_4(ctrlr, csts);
304 
305 	en = (cc >> NVME_CC_REG_EN_SHIFT) & NVME_CC_REG_EN_MASK;
306 	rdy = (csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK;
307 
308 	/*
309 	 * Per 3.1.5 in NVME 1.3 spec, transitioning CC.EN from 0 to 1
310 	 * when CSTS.RDY is 1 or transitioning CC.EN from 1 to 0 when
311 	 * CSTS.RDY is 0 "has undefined results" So make sure that CSTS.RDY
312 	 * isn't the desired value. Short circuit if we're already disabled.
313 	 */
314 	if (en == 0) {
315 		/* Wait for RDY == 0 or timeout & fail */
316 		if (rdy == 0)
317 			return (0);
318 		return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
319 	}
320 	if (rdy == 0) {
321 		/* EN == 1, wait for  RDY == 1 or timeout & fail */
322 		err = nvme_ctrlr_wait_for_ready(ctrlr, 1);
323 		if (err != 0)
324 			return (err);
325 	}
326 
327 	cc &= ~NVME_CC_REG_EN_MASK;
328 	nvme_mmio_write_4(ctrlr, cc, cc);
329 
330 	/*
331 	 * A few drives have firmware bugs that freeze the drive if we access
332 	 * the mmio too soon after we disable.
333 	 */
334 	if (ctrlr->quirks & QUIRK_DELAY_B4_CHK_RDY)
335 		pause("nvmeR", MSEC_2_TICKS(B4_CHK_RDY_DELAY_MS));
336 	return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
337 }
338 
339 static int
340 nvme_ctrlr_enable(struct nvme_controller *ctrlr)
341 {
342 	uint32_t	cc;
343 	uint32_t	csts;
344 	uint32_t	aqa;
345 	uint32_t	qsize;
346 	uint8_t		en, rdy;
347 	int		err;
348 
349 	cc = nvme_mmio_read_4(ctrlr, cc);
350 	csts = nvme_mmio_read_4(ctrlr, csts);
351 
352 	en = (cc >> NVME_CC_REG_EN_SHIFT) & NVME_CC_REG_EN_MASK;
353 	rdy = (csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK;
354 
355 	/*
356 	 * See note in nvme_ctrlr_disable. Short circuit if we're already enabled.
357 	 */
358 	if (en == 1) {
359 		if (rdy == 1)
360 			return (0);
361 		return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
362 	}
363 
364 	/* EN == 0 already wait for RDY == 0 or timeout & fail */
365 	err = nvme_ctrlr_wait_for_ready(ctrlr, 0);
366 	if (err != 0)
367 		return (err);
368 
369 	nvme_mmio_write_8(ctrlr, asq, ctrlr->adminq.cmd_bus_addr);
370 	nvme_mmio_write_8(ctrlr, acq, ctrlr->adminq.cpl_bus_addr);
371 
372 	/* acqs and asqs are 0-based. */
373 	qsize = ctrlr->adminq.num_entries - 1;
374 
375 	aqa = 0;
376 	aqa = (qsize & NVME_AQA_REG_ACQS_MASK) << NVME_AQA_REG_ACQS_SHIFT;
377 	aqa |= (qsize & NVME_AQA_REG_ASQS_MASK) << NVME_AQA_REG_ASQS_SHIFT;
378 	nvme_mmio_write_4(ctrlr, aqa, aqa);
379 
380 	/* Initialization values for CC */
381 	cc = 0;
382 	cc |= 1 << NVME_CC_REG_EN_SHIFT;
383 	cc |= 0 << NVME_CC_REG_CSS_SHIFT;
384 	cc |= 0 << NVME_CC_REG_AMS_SHIFT;
385 	cc |= 0 << NVME_CC_REG_SHN_SHIFT;
386 	cc |= 6 << NVME_CC_REG_IOSQES_SHIFT; /* SQ entry size == 64 == 2^6 */
387 	cc |= 4 << NVME_CC_REG_IOCQES_SHIFT; /* CQ entry size == 16 == 2^4 */
388 
389 	/*
390 	 * Use the Memory Page Size selected during device initialization.  Note
391 	 * that value stored in mps is suitable to use here without adjusting by
392 	 * NVME_MPS_SHIFT.
393 	 */
394 	cc |= ctrlr->mps << NVME_CC_REG_MPS_SHIFT;
395 
396 	nvme_ctrlr_barrier(ctrlr, BUS_SPACE_BARRIER_WRITE);
397 	nvme_mmio_write_4(ctrlr, cc, cc);
398 
399 	return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
400 }
401 
402 static void
403 nvme_ctrlr_disable_qpairs(struct nvme_controller *ctrlr)
404 {
405 	int i;
406 
407 	nvme_admin_qpair_disable(&ctrlr->adminq);
408 	/*
409 	 * I/O queues are not allocated before the initial HW
410 	 *  reset, so do not try to disable them.  Use is_initialized
411 	 *  to determine if this is the initial HW reset.
412 	 */
413 	if (ctrlr->is_initialized) {
414 		for (i = 0; i < ctrlr->num_io_queues; i++)
415 			nvme_io_qpair_disable(&ctrlr->ioq[i]);
416 	}
417 }
418 
419 static int
420 nvme_ctrlr_hw_reset(struct nvme_controller *ctrlr)
421 {
422 	int err;
423 
424 	TSENTER();
425 
426 	nvme_ctrlr_disable_qpairs(ctrlr);
427 
428 	err = nvme_ctrlr_disable(ctrlr);
429 	if (err != 0)
430 		return err;
431 
432 	err = nvme_ctrlr_enable(ctrlr);
433 	TSEXIT();
434 	return (err);
435 }
436 
437 void
438 nvme_ctrlr_reset(struct nvme_controller *ctrlr)
439 {
440 	int cmpset;
441 
442 	cmpset = atomic_cmpset_32(&ctrlr->is_resetting, 0, 1);
443 
444 	if (cmpset == 0 || ctrlr->is_failed)
445 		/*
446 		 * Controller is already resetting or has failed.  Return
447 		 *  immediately since there is no need to kick off another
448 		 *  reset in these cases.
449 		 */
450 		return;
451 
452 	if (!ctrlr->is_dying)
453 		taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->reset_task);
454 }
455 
456 static int
457 nvme_ctrlr_identify(struct nvme_controller *ctrlr)
458 {
459 	struct nvme_completion_poll_status	status;
460 
461 	status.done = 0;
462 	nvme_ctrlr_cmd_identify_controller(ctrlr, &ctrlr->cdata,
463 	    nvme_completion_poll_cb, &status);
464 	nvme_completion_poll(&status);
465 	if (nvme_completion_is_error(&status.cpl)) {
466 		nvme_printf(ctrlr, "nvme_identify_controller failed!\n");
467 		return (ENXIO);
468 	}
469 
470 	/* Convert data to host endian */
471 	nvme_controller_data_swapbytes(&ctrlr->cdata);
472 
473 	/*
474 	 * Use MDTS to ensure our default max_xfer_size doesn't exceed what the
475 	 *  controller supports.
476 	 */
477 	if (ctrlr->cdata.mdts > 0)
478 		ctrlr->max_xfer_size = min(ctrlr->max_xfer_size,
479 		    1 << (ctrlr->cdata.mdts + NVME_MPS_SHIFT +
480 			NVME_CAP_HI_MPSMIN(ctrlr->cap_hi)));
481 
482 	return (0);
483 }
484 
485 static int
486 nvme_ctrlr_set_num_qpairs(struct nvme_controller *ctrlr)
487 {
488 	struct nvme_completion_poll_status	status;
489 	int					cq_allocated, sq_allocated;
490 
491 	status.done = 0;
492 	nvme_ctrlr_cmd_set_num_queues(ctrlr, ctrlr->num_io_queues,
493 	    nvme_completion_poll_cb, &status);
494 	nvme_completion_poll(&status);
495 	if (nvme_completion_is_error(&status.cpl)) {
496 		nvme_printf(ctrlr, "nvme_ctrlr_set_num_qpairs failed!\n");
497 		return (ENXIO);
498 	}
499 
500 	/*
501 	 * Data in cdw0 is 0-based.
502 	 * Lower 16-bits indicate number of submission queues allocated.
503 	 * Upper 16-bits indicate number of completion queues allocated.
504 	 */
505 	sq_allocated = (status.cpl.cdw0 & 0xFFFF) + 1;
506 	cq_allocated = (status.cpl.cdw0 >> 16) + 1;
507 
508 	/*
509 	 * Controller may allocate more queues than we requested,
510 	 *  so use the minimum of the number requested and what was
511 	 *  actually allocated.
512 	 */
513 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, sq_allocated);
514 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, cq_allocated);
515 	if (ctrlr->num_io_queues > vm_ndomains)
516 		ctrlr->num_io_queues -= ctrlr->num_io_queues % vm_ndomains;
517 
518 	return (0);
519 }
520 
521 static int
522 nvme_ctrlr_create_qpairs(struct nvme_controller *ctrlr)
523 {
524 	struct nvme_completion_poll_status	status;
525 	struct nvme_qpair			*qpair;
526 	int					i;
527 
528 	for (i = 0; i < ctrlr->num_io_queues; i++) {
529 		qpair = &ctrlr->ioq[i];
530 
531 		status.done = 0;
532 		nvme_ctrlr_cmd_create_io_cq(ctrlr, qpair,
533 		    nvme_completion_poll_cb, &status);
534 		nvme_completion_poll(&status);
535 		if (nvme_completion_is_error(&status.cpl)) {
536 			nvme_printf(ctrlr, "nvme_create_io_cq failed!\n");
537 			return (ENXIO);
538 		}
539 
540 		status.done = 0;
541 		nvme_ctrlr_cmd_create_io_sq(ctrlr, qpair,
542 		    nvme_completion_poll_cb, &status);
543 		nvme_completion_poll(&status);
544 		if (nvme_completion_is_error(&status.cpl)) {
545 			nvme_printf(ctrlr, "nvme_create_io_sq failed!\n");
546 			return (ENXIO);
547 		}
548 	}
549 
550 	return (0);
551 }
552 
553 static int
554 nvme_ctrlr_delete_qpairs(struct nvme_controller *ctrlr)
555 {
556 	struct nvme_completion_poll_status	status;
557 	struct nvme_qpair			*qpair;
558 
559 	for (int i = 0; i < ctrlr->num_io_queues; i++) {
560 		qpair = &ctrlr->ioq[i];
561 
562 		status.done = 0;
563 		nvme_ctrlr_cmd_delete_io_sq(ctrlr, qpair,
564 		    nvme_completion_poll_cb, &status);
565 		nvme_completion_poll(&status);
566 		if (nvme_completion_is_error(&status.cpl)) {
567 			nvme_printf(ctrlr, "nvme_destroy_io_sq failed!\n");
568 			return (ENXIO);
569 		}
570 
571 		status.done = 0;
572 		nvme_ctrlr_cmd_delete_io_cq(ctrlr, qpair,
573 		    nvme_completion_poll_cb, &status);
574 		nvme_completion_poll(&status);
575 		if (nvme_completion_is_error(&status.cpl)) {
576 			nvme_printf(ctrlr, "nvme_destroy_io_cq failed!\n");
577 			return (ENXIO);
578 		}
579 	}
580 
581 	return (0);
582 }
583 
584 static int
585 nvme_ctrlr_construct_namespaces(struct nvme_controller *ctrlr)
586 {
587 	struct nvme_namespace	*ns;
588 	uint32_t 		i;
589 
590 	for (i = 0; i < min(ctrlr->cdata.nn, NVME_MAX_NAMESPACES); i++) {
591 		ns = &ctrlr->ns[i];
592 		nvme_ns_construct(ns, i+1, ctrlr);
593 	}
594 
595 	return (0);
596 }
597 
598 static bool
599 is_log_page_id_valid(uint8_t page_id)
600 {
601 
602 	switch (page_id) {
603 	case NVME_LOG_ERROR:
604 	case NVME_LOG_HEALTH_INFORMATION:
605 	case NVME_LOG_FIRMWARE_SLOT:
606 	case NVME_LOG_CHANGED_NAMESPACE:
607 	case NVME_LOG_COMMAND_EFFECT:
608 	case NVME_LOG_RES_NOTIFICATION:
609 	case NVME_LOG_SANITIZE_STATUS:
610 		return (true);
611 	}
612 
613 	return (false);
614 }
615 
616 static uint32_t
617 nvme_ctrlr_get_log_page_size(struct nvme_controller *ctrlr, uint8_t page_id)
618 {
619 	uint32_t	log_page_size;
620 
621 	switch (page_id) {
622 	case NVME_LOG_ERROR:
623 		log_page_size = min(
624 		    sizeof(struct nvme_error_information_entry) *
625 		    (ctrlr->cdata.elpe + 1), NVME_MAX_AER_LOG_SIZE);
626 		break;
627 	case NVME_LOG_HEALTH_INFORMATION:
628 		log_page_size = sizeof(struct nvme_health_information_page);
629 		break;
630 	case NVME_LOG_FIRMWARE_SLOT:
631 		log_page_size = sizeof(struct nvme_firmware_page);
632 		break;
633 	case NVME_LOG_CHANGED_NAMESPACE:
634 		log_page_size = sizeof(struct nvme_ns_list);
635 		break;
636 	case NVME_LOG_COMMAND_EFFECT:
637 		log_page_size = sizeof(struct nvme_command_effects_page);
638 		break;
639 	case NVME_LOG_RES_NOTIFICATION:
640 		log_page_size = sizeof(struct nvme_res_notification_page);
641 		break;
642 	case NVME_LOG_SANITIZE_STATUS:
643 		log_page_size = sizeof(struct nvme_sanitize_status_page);
644 		break;
645 	default:
646 		log_page_size = 0;
647 		break;
648 	}
649 
650 	return (log_page_size);
651 }
652 
653 static void
654 nvme_ctrlr_log_critical_warnings(struct nvme_controller *ctrlr,
655     uint8_t state)
656 {
657 
658 	if (state & NVME_CRIT_WARN_ST_AVAILABLE_SPARE)
659 		nvme_ctrlr_devctl_log(ctrlr, "critical",
660 		    "available spare space below threshold");
661 
662 	if (state & NVME_CRIT_WARN_ST_TEMPERATURE)
663 		nvme_ctrlr_devctl_log(ctrlr, "critical",
664 		    "temperature above threshold");
665 
666 	if (state & NVME_CRIT_WARN_ST_DEVICE_RELIABILITY)
667 		nvme_ctrlr_devctl_log(ctrlr, "critical",
668 		    "device reliability degraded");
669 
670 	if (state & NVME_CRIT_WARN_ST_READ_ONLY)
671 		nvme_ctrlr_devctl_log(ctrlr, "critical",
672 		    "media placed in read only mode");
673 
674 	if (state & NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP)
675 		nvme_ctrlr_devctl_log(ctrlr, "critical",
676 		    "volatile memory backup device failed");
677 
678 	if (state & NVME_CRIT_WARN_ST_RESERVED_MASK)
679 		nvme_ctrlr_devctl_log(ctrlr, "critical",
680 		    "unknown critical warning(s): state = 0x%02x", state);
681 }
682 
683 static void
684 nvme_ctrlr_async_event_log_page_cb(void *arg, const struct nvme_completion *cpl)
685 {
686 	struct nvme_async_event_request		*aer = arg;
687 	struct nvme_health_information_page	*health_info;
688 	struct nvme_ns_list			*nsl;
689 	struct nvme_error_information_entry	*err;
690 	int i;
691 
692 	/*
693 	 * If the log page fetch for some reason completed with an error,
694 	 *  don't pass log page data to the consumers.  In practice, this case
695 	 *  should never happen.
696 	 */
697 	if (nvme_completion_is_error(cpl))
698 		nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
699 		    aer->log_page_id, NULL, 0);
700 	else {
701 		/* Convert data to host endian */
702 		switch (aer->log_page_id) {
703 		case NVME_LOG_ERROR:
704 			err = (struct nvme_error_information_entry *)aer->log_page_buffer;
705 			for (i = 0; i < (aer->ctrlr->cdata.elpe + 1); i++)
706 				nvme_error_information_entry_swapbytes(err++);
707 			break;
708 		case NVME_LOG_HEALTH_INFORMATION:
709 			nvme_health_information_page_swapbytes(
710 			    (struct nvme_health_information_page *)aer->log_page_buffer);
711 			break;
712 		case NVME_LOG_FIRMWARE_SLOT:
713 			nvme_firmware_page_swapbytes(
714 			    (struct nvme_firmware_page *)aer->log_page_buffer);
715 			break;
716 		case NVME_LOG_CHANGED_NAMESPACE:
717 			nvme_ns_list_swapbytes(
718 			    (struct nvme_ns_list *)aer->log_page_buffer);
719 			break;
720 		case NVME_LOG_COMMAND_EFFECT:
721 			nvme_command_effects_page_swapbytes(
722 			    (struct nvme_command_effects_page *)aer->log_page_buffer);
723 			break;
724 		case NVME_LOG_RES_NOTIFICATION:
725 			nvme_res_notification_page_swapbytes(
726 			    (struct nvme_res_notification_page *)aer->log_page_buffer);
727 			break;
728 		case NVME_LOG_SANITIZE_STATUS:
729 			nvme_sanitize_status_page_swapbytes(
730 			    (struct nvme_sanitize_status_page *)aer->log_page_buffer);
731 			break;
732 		case INTEL_LOG_TEMP_STATS:
733 			intel_log_temp_stats_swapbytes(
734 			    (struct intel_log_temp_stats *)aer->log_page_buffer);
735 			break;
736 		default:
737 			break;
738 		}
739 
740 		if (aer->log_page_id == NVME_LOG_HEALTH_INFORMATION) {
741 			health_info = (struct nvme_health_information_page *)
742 			    aer->log_page_buffer;
743 			nvme_ctrlr_log_critical_warnings(aer->ctrlr,
744 			    health_info->critical_warning);
745 			/*
746 			 * Critical warnings reported through the
747 			 *  SMART/health log page are persistent, so
748 			 *  clear the associated bits in the async event
749 			 *  config so that we do not receive repeated
750 			 *  notifications for the same event.
751 			 */
752 			aer->ctrlr->async_event_config &=
753 			    ~health_info->critical_warning;
754 			nvme_ctrlr_cmd_set_async_event_config(aer->ctrlr,
755 			    aer->ctrlr->async_event_config, NULL, NULL);
756 		} else if (aer->log_page_id == NVME_LOG_CHANGED_NAMESPACE &&
757 		    !nvme_use_nvd) {
758 			nsl = (struct nvme_ns_list *)aer->log_page_buffer;
759 			for (i = 0; i < nitems(nsl->ns) && nsl->ns[i] != 0; i++) {
760 				if (nsl->ns[i] > NVME_MAX_NAMESPACES)
761 					break;
762 				nvme_notify_ns(aer->ctrlr, nsl->ns[i]);
763 			}
764 		}
765 
766 		/*
767 		 * Pass the cpl data from the original async event completion,
768 		 *  not the log page fetch.
769 		 */
770 		nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
771 		    aer->log_page_id, aer->log_page_buffer, aer->log_page_size);
772 	}
773 
774 	/*
775 	 * Repost another asynchronous event request to replace the one
776 	 *  that just completed.
777 	 */
778 	nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
779 }
780 
781 static void
782 nvme_ctrlr_async_event_cb(void *arg, const struct nvme_completion *cpl)
783 {
784 	struct nvme_async_event_request	*aer = arg;
785 
786 	if (nvme_completion_is_error(cpl)) {
787 		/*
788 		 *  Do not retry failed async event requests.  This avoids
789 		 *  infinite loops where a new async event request is submitted
790 		 *  to replace the one just failed, only to fail again and
791 		 *  perpetuate the loop.
792 		 */
793 		return;
794 	}
795 
796 	/* Associated log page is in bits 23:16 of completion entry dw0. */
797 	aer->log_page_id = (cpl->cdw0 & 0xFF0000) >> 16;
798 
799 	nvme_printf(aer->ctrlr, "async event occurred (type 0x%x, info 0x%02x,"
800 	    " page 0x%02x)\n", (cpl->cdw0 & 0x07), (cpl->cdw0 & 0xFF00) >> 8,
801 	    aer->log_page_id);
802 
803 	if (is_log_page_id_valid(aer->log_page_id)) {
804 		aer->log_page_size = nvme_ctrlr_get_log_page_size(aer->ctrlr,
805 		    aer->log_page_id);
806 		memcpy(&aer->cpl, cpl, sizeof(*cpl));
807 		nvme_ctrlr_cmd_get_log_page(aer->ctrlr, aer->log_page_id,
808 		    NVME_GLOBAL_NAMESPACE_TAG, aer->log_page_buffer,
809 		    aer->log_page_size, nvme_ctrlr_async_event_log_page_cb,
810 		    aer);
811 		/* Wait to notify consumers until after log page is fetched. */
812 	} else {
813 		nvme_notify_async_consumers(aer->ctrlr, cpl, aer->log_page_id,
814 		    NULL, 0);
815 
816 		/*
817 		 * Repost another asynchronous event request to replace the one
818 		 *  that just completed.
819 		 */
820 		nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
821 	}
822 }
823 
824 static void
825 nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
826     struct nvme_async_event_request *aer)
827 {
828 	struct nvme_request *req;
829 
830 	aer->ctrlr = ctrlr;
831 	req = nvme_allocate_request_null(nvme_ctrlr_async_event_cb, aer);
832 	aer->req = req;
833 
834 	/*
835 	 * Disable timeout here, since asynchronous event requests should by
836 	 *  nature never be timed out.
837 	 */
838 	req->timeout = false;
839 	req->cmd.opc = NVME_OPC_ASYNC_EVENT_REQUEST;
840 	nvme_ctrlr_submit_admin_request(ctrlr, req);
841 }
842 
843 static void
844 nvme_ctrlr_configure_aer(struct nvme_controller *ctrlr)
845 {
846 	struct nvme_completion_poll_status	status;
847 	struct nvme_async_event_request		*aer;
848 	uint32_t				i;
849 
850 	ctrlr->async_event_config = NVME_CRIT_WARN_ST_AVAILABLE_SPARE |
851 	    NVME_CRIT_WARN_ST_DEVICE_RELIABILITY |
852 	    NVME_CRIT_WARN_ST_READ_ONLY |
853 	    NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP;
854 	if (ctrlr->cdata.ver >= NVME_REV(1, 2))
855 		ctrlr->async_event_config |= NVME_ASYNC_EVENT_NS_ATTRIBUTE |
856 		    NVME_ASYNC_EVENT_FW_ACTIVATE;
857 
858 	status.done = 0;
859 	nvme_ctrlr_cmd_get_feature(ctrlr, NVME_FEAT_TEMPERATURE_THRESHOLD,
860 	    0, NULL, 0, nvme_completion_poll_cb, &status);
861 	nvme_completion_poll(&status);
862 	if (nvme_completion_is_error(&status.cpl) ||
863 	    (status.cpl.cdw0 & 0xFFFF) == 0xFFFF ||
864 	    (status.cpl.cdw0 & 0xFFFF) == 0x0000) {
865 		nvme_printf(ctrlr, "temperature threshold not supported\n");
866 	} else
867 		ctrlr->async_event_config |= NVME_CRIT_WARN_ST_TEMPERATURE;
868 
869 	nvme_ctrlr_cmd_set_async_event_config(ctrlr,
870 	    ctrlr->async_event_config, NULL, NULL);
871 
872 	/* aerl is a zero-based value, so we need to add 1 here. */
873 	ctrlr->num_aers = min(NVME_MAX_ASYNC_EVENTS, (ctrlr->cdata.aerl+1));
874 
875 	for (i = 0; i < ctrlr->num_aers; i++) {
876 		aer = &ctrlr->aer[i];
877 		nvme_ctrlr_construct_and_submit_aer(ctrlr, aer);
878 	}
879 }
880 
881 static void
882 nvme_ctrlr_configure_int_coalescing(struct nvme_controller *ctrlr)
883 {
884 
885 	ctrlr->int_coal_time = 0;
886 	TUNABLE_INT_FETCH("hw.nvme.int_coal_time",
887 	    &ctrlr->int_coal_time);
888 
889 	ctrlr->int_coal_threshold = 0;
890 	TUNABLE_INT_FETCH("hw.nvme.int_coal_threshold",
891 	    &ctrlr->int_coal_threshold);
892 
893 	nvme_ctrlr_cmd_set_interrupt_coalescing(ctrlr, ctrlr->int_coal_time,
894 	    ctrlr->int_coal_threshold, NULL, NULL);
895 }
896 
897 static void
898 nvme_ctrlr_hmb_free(struct nvme_controller *ctrlr)
899 {
900 	struct nvme_hmb_chunk *hmbc;
901 	int i;
902 
903 	if (ctrlr->hmb_desc_paddr) {
904 		bus_dmamap_unload(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map);
905 		bus_dmamem_free(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_vaddr,
906 		    ctrlr->hmb_desc_map);
907 		ctrlr->hmb_desc_paddr = 0;
908 	}
909 	if (ctrlr->hmb_desc_tag) {
910 		bus_dma_tag_destroy(ctrlr->hmb_desc_tag);
911 		ctrlr->hmb_desc_tag = NULL;
912 	}
913 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
914 		hmbc = &ctrlr->hmb_chunks[i];
915 		bus_dmamap_unload(ctrlr->hmb_tag, hmbc->hmbc_map);
916 		bus_dmamem_free(ctrlr->hmb_tag, hmbc->hmbc_vaddr,
917 		    hmbc->hmbc_map);
918 	}
919 	ctrlr->hmb_nchunks = 0;
920 	if (ctrlr->hmb_tag) {
921 		bus_dma_tag_destroy(ctrlr->hmb_tag);
922 		ctrlr->hmb_tag = NULL;
923 	}
924 	if (ctrlr->hmb_chunks) {
925 		free(ctrlr->hmb_chunks, M_NVME);
926 		ctrlr->hmb_chunks = NULL;
927 	}
928 }
929 
930 static void
931 nvme_ctrlr_hmb_alloc(struct nvme_controller *ctrlr)
932 {
933 	struct nvme_hmb_chunk *hmbc;
934 	size_t pref, min, minc, size;
935 	int err, i;
936 	uint64_t max;
937 
938 	/* Limit HMB to 5% of RAM size per device by default. */
939 	max = (uint64_t)physmem * PAGE_SIZE / 20;
940 	TUNABLE_UINT64_FETCH("hw.nvme.hmb_max", &max);
941 
942 	/*
943 	 * Units of Host Memory Buffer in the Identify info are always in terms
944 	 * of 4k units.
945 	 */
946 	min = (long long unsigned)ctrlr->cdata.hmmin * NVME_HMB_UNITS;
947 	if (max == 0 || max < min)
948 		return;
949 	pref = MIN((long long unsigned)ctrlr->cdata.hmpre * NVME_HMB_UNITS, max);
950 	minc = MAX(ctrlr->cdata.hmminds * NVME_HMB_UNITS, ctrlr->page_size);
951 	if (min > 0 && ctrlr->cdata.hmmaxd > 0)
952 		minc = MAX(minc, min / ctrlr->cdata.hmmaxd);
953 	ctrlr->hmb_chunk = pref;
954 
955 again:
956 	/*
957 	 * However, the chunk sizes, number of chunks, and alignment of chunks
958 	 * are all based on the current MPS (ctrlr->page_size).
959 	 */
960 	ctrlr->hmb_chunk = roundup2(ctrlr->hmb_chunk, ctrlr->page_size);
961 	ctrlr->hmb_nchunks = howmany(pref, ctrlr->hmb_chunk);
962 	if (ctrlr->cdata.hmmaxd > 0 && ctrlr->hmb_nchunks > ctrlr->cdata.hmmaxd)
963 		ctrlr->hmb_nchunks = ctrlr->cdata.hmmaxd;
964 	ctrlr->hmb_chunks = malloc(sizeof(struct nvme_hmb_chunk) *
965 	    ctrlr->hmb_nchunks, M_NVME, M_WAITOK);
966 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
967 	    ctrlr->page_size, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
968 	    ctrlr->hmb_chunk, 1, ctrlr->hmb_chunk, 0, NULL, NULL, &ctrlr->hmb_tag);
969 	if (err != 0) {
970 		nvme_printf(ctrlr, "HMB tag create failed %d\n", err);
971 		nvme_ctrlr_hmb_free(ctrlr);
972 		return;
973 	}
974 
975 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
976 		hmbc = &ctrlr->hmb_chunks[i];
977 		if (bus_dmamem_alloc(ctrlr->hmb_tag,
978 		    (void **)&hmbc->hmbc_vaddr, BUS_DMA_NOWAIT,
979 		    &hmbc->hmbc_map)) {
980 			nvme_printf(ctrlr, "failed to alloc HMB\n");
981 			break;
982 		}
983 		if (bus_dmamap_load(ctrlr->hmb_tag, hmbc->hmbc_map,
984 		    hmbc->hmbc_vaddr, ctrlr->hmb_chunk, nvme_single_map,
985 		    &hmbc->hmbc_paddr, BUS_DMA_NOWAIT) != 0) {
986 			bus_dmamem_free(ctrlr->hmb_tag, hmbc->hmbc_vaddr,
987 			    hmbc->hmbc_map);
988 			nvme_printf(ctrlr, "failed to load HMB\n");
989 			break;
990 		}
991 		bus_dmamap_sync(ctrlr->hmb_tag, hmbc->hmbc_map,
992 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
993 	}
994 
995 	if (i < ctrlr->hmb_nchunks && i * ctrlr->hmb_chunk < min &&
996 	    ctrlr->hmb_chunk / 2 >= minc) {
997 		ctrlr->hmb_nchunks = i;
998 		nvme_ctrlr_hmb_free(ctrlr);
999 		ctrlr->hmb_chunk /= 2;
1000 		goto again;
1001 	}
1002 	ctrlr->hmb_nchunks = i;
1003 	if (ctrlr->hmb_nchunks * ctrlr->hmb_chunk < min) {
1004 		nvme_ctrlr_hmb_free(ctrlr);
1005 		return;
1006 	}
1007 
1008 	size = sizeof(struct nvme_hmb_desc) * ctrlr->hmb_nchunks;
1009 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
1010 	    16, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1011 	    size, 1, size, 0, NULL, NULL, &ctrlr->hmb_desc_tag);
1012 	if (err != 0) {
1013 		nvme_printf(ctrlr, "HMB desc tag create failed %d\n", err);
1014 		nvme_ctrlr_hmb_free(ctrlr);
1015 		return;
1016 	}
1017 	if (bus_dmamem_alloc(ctrlr->hmb_desc_tag,
1018 	    (void **)&ctrlr->hmb_desc_vaddr, BUS_DMA_WAITOK,
1019 	    &ctrlr->hmb_desc_map)) {
1020 		nvme_printf(ctrlr, "failed to alloc HMB desc\n");
1021 		nvme_ctrlr_hmb_free(ctrlr);
1022 		return;
1023 	}
1024 	if (bus_dmamap_load(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map,
1025 	    ctrlr->hmb_desc_vaddr, size, nvme_single_map,
1026 	    &ctrlr->hmb_desc_paddr, BUS_DMA_NOWAIT) != 0) {
1027 		bus_dmamem_free(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_vaddr,
1028 		    ctrlr->hmb_desc_map);
1029 		nvme_printf(ctrlr, "failed to load HMB desc\n");
1030 		nvme_ctrlr_hmb_free(ctrlr);
1031 		return;
1032 	}
1033 
1034 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
1035 		ctrlr->hmb_desc_vaddr[i].addr =
1036 		    htole64(ctrlr->hmb_chunks[i].hmbc_paddr);
1037 		ctrlr->hmb_desc_vaddr[i].size = htole32(ctrlr->hmb_chunk / ctrlr->page_size);
1038 	}
1039 	bus_dmamap_sync(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map,
1040 	    BUS_DMASYNC_PREWRITE);
1041 
1042 	nvme_printf(ctrlr, "Allocated %lluMB host memory buffer\n",
1043 	    (long long unsigned)ctrlr->hmb_nchunks * ctrlr->hmb_chunk
1044 	    / 1024 / 1024);
1045 }
1046 
1047 static void
1048 nvme_ctrlr_hmb_enable(struct nvme_controller *ctrlr, bool enable, bool memret)
1049 {
1050 	struct nvme_completion_poll_status	status;
1051 	uint32_t cdw11;
1052 
1053 	cdw11 = 0;
1054 	if (enable)
1055 		cdw11 |= 1;
1056 	if (memret)
1057 		cdw11 |= 2;
1058 	status.done = 0;
1059 	nvme_ctrlr_cmd_set_feature(ctrlr, NVME_FEAT_HOST_MEMORY_BUFFER, cdw11,
1060 	    ctrlr->hmb_nchunks * ctrlr->hmb_chunk / ctrlr->page_size,
1061 	    ctrlr->hmb_desc_paddr, ctrlr->hmb_desc_paddr >> 32,
1062 	    ctrlr->hmb_nchunks, NULL, 0,
1063 	    nvme_completion_poll_cb, &status);
1064 	nvme_completion_poll(&status);
1065 	if (nvme_completion_is_error(&status.cpl))
1066 		nvme_printf(ctrlr, "nvme_ctrlr_hmb_enable failed!\n");
1067 }
1068 
1069 static void
1070 nvme_ctrlr_start(void *ctrlr_arg, bool resetting)
1071 {
1072 	struct nvme_controller *ctrlr = ctrlr_arg;
1073 	uint32_t old_num_io_queues;
1074 	int i;
1075 
1076 	TSENTER();
1077 
1078 	/*
1079 	 * Only reset adminq here when we are restarting the
1080 	 *  controller after a reset.  During initialization,
1081 	 *  we have already submitted admin commands to get
1082 	 *  the number of I/O queues supported, so cannot reset
1083 	 *  the adminq again here.
1084 	 */
1085 	if (resetting) {
1086 		nvme_qpair_reset(&ctrlr->adminq);
1087 		nvme_admin_qpair_enable(&ctrlr->adminq);
1088 	}
1089 
1090 	if (ctrlr->ioq != NULL) {
1091 		for (i = 0; i < ctrlr->num_io_queues; i++)
1092 			nvme_qpair_reset(&ctrlr->ioq[i]);
1093 	}
1094 
1095 	/*
1096 	 * If it was a reset on initialization command timeout, just
1097 	 * return here, letting initialization code fail gracefully.
1098 	 */
1099 	if (resetting && !ctrlr->is_initialized)
1100 		return;
1101 
1102 	if (resetting && nvme_ctrlr_identify(ctrlr) != 0) {
1103 		nvme_ctrlr_fail(ctrlr);
1104 		return;
1105 	}
1106 
1107 	/*
1108 	 * The number of qpairs are determined during controller initialization,
1109 	 *  including using NVMe SET_FEATURES/NUMBER_OF_QUEUES to determine the
1110 	 *  HW limit.  We call SET_FEATURES again here so that it gets called
1111 	 *  after any reset for controllers that depend on the driver to
1112 	 *  explicit specify how many queues it will use.  This value should
1113 	 *  never change between resets, so panic if somehow that does happen.
1114 	 */
1115 	if (resetting) {
1116 		old_num_io_queues = ctrlr->num_io_queues;
1117 		if (nvme_ctrlr_set_num_qpairs(ctrlr) != 0) {
1118 			nvme_ctrlr_fail(ctrlr);
1119 			return;
1120 		}
1121 
1122 		if (old_num_io_queues != ctrlr->num_io_queues) {
1123 			panic("num_io_queues changed from %u to %u",
1124 			      old_num_io_queues, ctrlr->num_io_queues);
1125 		}
1126 	}
1127 
1128 	if (ctrlr->cdata.hmpre > 0 && ctrlr->hmb_nchunks == 0) {
1129 		nvme_ctrlr_hmb_alloc(ctrlr);
1130 		if (ctrlr->hmb_nchunks > 0)
1131 			nvme_ctrlr_hmb_enable(ctrlr, true, false);
1132 	} else if (ctrlr->hmb_nchunks > 0)
1133 		nvme_ctrlr_hmb_enable(ctrlr, true, true);
1134 
1135 	if (nvme_ctrlr_create_qpairs(ctrlr) != 0) {
1136 		nvme_ctrlr_fail(ctrlr);
1137 		return;
1138 	}
1139 
1140 	if (nvme_ctrlr_construct_namespaces(ctrlr) != 0) {
1141 		nvme_ctrlr_fail(ctrlr);
1142 		return;
1143 	}
1144 
1145 	nvme_ctrlr_configure_aer(ctrlr);
1146 	nvme_ctrlr_configure_int_coalescing(ctrlr);
1147 
1148 	for (i = 0; i < ctrlr->num_io_queues; i++)
1149 		nvme_io_qpair_enable(&ctrlr->ioq[i]);
1150 	TSEXIT();
1151 }
1152 
1153 void
1154 nvme_ctrlr_start_config_hook(void *arg)
1155 {
1156 	struct nvme_controller *ctrlr = arg;
1157 
1158 	TSENTER();
1159 
1160 	if (nvme_ctrlr_hw_reset(ctrlr) != 0) {
1161 fail:
1162 		nvme_ctrlr_fail(ctrlr);
1163 		config_intrhook_disestablish(&ctrlr->config_hook);
1164 		return;
1165 	}
1166 
1167 #ifdef NVME_2X_RESET
1168 	/*
1169 	 * Reset controller twice to ensure we do a transition from cc.en==1 to
1170 	 * cc.en==0.  This is because we don't really know what status the
1171 	 * controller was left in when boot handed off to OS.  Linux doesn't do
1172 	 * this, however, and when the controller is in state cc.en == 0, no
1173 	 * I/O can happen.
1174 	 */
1175 	if (nvme_ctrlr_hw_reset(ctrlr) != 0)
1176 		goto fail;
1177 #endif
1178 
1179 	nvme_qpair_reset(&ctrlr->adminq);
1180 	nvme_admin_qpair_enable(&ctrlr->adminq);
1181 
1182 	if (nvme_ctrlr_identify(ctrlr) == 0 &&
1183 	    nvme_ctrlr_set_num_qpairs(ctrlr) == 0 &&
1184 	    nvme_ctrlr_construct_io_qpairs(ctrlr) == 0)
1185 		nvme_ctrlr_start(ctrlr, false);
1186 	else
1187 		goto fail;
1188 
1189 	nvme_sysctl_initialize_ctrlr(ctrlr);
1190 	config_intrhook_disestablish(&ctrlr->config_hook);
1191 
1192 	ctrlr->is_initialized = 1;
1193 	nvme_notify_new_controller(ctrlr);
1194 	TSEXIT();
1195 }
1196 
1197 static void
1198 nvme_ctrlr_reset_task(void *arg, int pending)
1199 {
1200 	struct nvme_controller	*ctrlr = arg;
1201 	int			status;
1202 
1203 	nvme_ctrlr_devctl_log(ctrlr, "RESET", "resetting controller");
1204 	status = nvme_ctrlr_hw_reset(ctrlr);
1205 	/*
1206 	 * Use pause instead of DELAY, so that we yield to any nvme interrupt
1207 	 *  handlers on this CPU that were blocked on a qpair lock. We want
1208 	 *  all nvme interrupts completed before proceeding with restarting the
1209 	 *  controller.
1210 	 *
1211 	 * XXX - any way to guarantee the interrupt handlers have quiesced?
1212 	 */
1213 	pause("nvmereset", hz / 10);
1214 	if (status == 0)
1215 		nvme_ctrlr_start(ctrlr, true);
1216 	else
1217 		nvme_ctrlr_fail(ctrlr);
1218 
1219 	atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
1220 }
1221 
1222 /*
1223  * Poll all the queues enabled on the device for completion.
1224  */
1225 void
1226 nvme_ctrlr_poll(struct nvme_controller *ctrlr)
1227 {
1228 	int i;
1229 
1230 	nvme_qpair_process_completions(&ctrlr->adminq);
1231 
1232 	for (i = 0; i < ctrlr->num_io_queues; i++)
1233 		if (ctrlr->ioq && ctrlr->ioq[i].cpl)
1234 			nvme_qpair_process_completions(&ctrlr->ioq[i]);
1235 }
1236 
1237 /*
1238  * Poll the single-vector interrupt case: num_io_queues will be 1 and
1239  * there's only a single vector. While we're polling, we mask further
1240  * interrupts in the controller.
1241  */
1242 void
1243 nvme_ctrlr_shared_handler(void *arg)
1244 {
1245 	struct nvme_controller *ctrlr = arg;
1246 
1247 	nvme_mmio_write_4(ctrlr, intms, 1);
1248 	nvme_ctrlr_poll(ctrlr);
1249 	nvme_mmio_write_4(ctrlr, intmc, 1);
1250 }
1251 
1252 static void
1253 nvme_pt_done(void *arg, const struct nvme_completion *cpl)
1254 {
1255 	struct nvme_pt_command *pt = arg;
1256 	struct mtx *mtx = pt->driver_lock;
1257 	uint16_t status;
1258 
1259 	bzero(&pt->cpl, sizeof(pt->cpl));
1260 	pt->cpl.cdw0 = cpl->cdw0;
1261 
1262 	status = cpl->status;
1263 	status &= ~NVME_STATUS_P_MASK;
1264 	pt->cpl.status = status;
1265 
1266 	mtx_lock(mtx);
1267 	pt->driver_lock = NULL;
1268 	wakeup(pt);
1269 	mtx_unlock(mtx);
1270 }
1271 
1272 int
1273 nvme_ctrlr_passthrough_cmd(struct nvme_controller *ctrlr,
1274     struct nvme_pt_command *pt, uint32_t nsid, int is_user_buffer,
1275     int is_admin_cmd)
1276 {
1277 	struct nvme_request	*req;
1278 	struct mtx		*mtx;
1279 	struct buf		*buf = NULL;
1280 	int			ret = 0;
1281 
1282 	if (pt->len > 0) {
1283 		if (pt->len > ctrlr->max_xfer_size) {
1284 			nvme_printf(ctrlr, "pt->len (%d) "
1285 			    "exceeds max_xfer_size (%d)\n", pt->len,
1286 			    ctrlr->max_xfer_size);
1287 			return EIO;
1288 		}
1289 		if (is_user_buffer) {
1290 			/*
1291 			 * Ensure the user buffer is wired for the duration of
1292 			 *  this pass-through command.
1293 			 */
1294 			PHOLD(curproc);
1295 			buf = uma_zalloc(pbuf_zone, M_WAITOK);
1296 			buf->b_iocmd = pt->is_read ? BIO_READ : BIO_WRITE;
1297 			if (vmapbuf(buf, pt->buf, pt->len, 1) < 0) {
1298 				ret = EFAULT;
1299 				goto err;
1300 			}
1301 			req = nvme_allocate_request_vaddr(buf->b_data, pt->len,
1302 			    nvme_pt_done, pt);
1303 		} else
1304 			req = nvme_allocate_request_vaddr(pt->buf, pt->len,
1305 			    nvme_pt_done, pt);
1306 	} else
1307 		req = nvme_allocate_request_null(nvme_pt_done, pt);
1308 
1309 	/* Assume user space already converted to little-endian */
1310 	req->cmd.opc = pt->cmd.opc;
1311 	req->cmd.fuse = pt->cmd.fuse;
1312 	req->cmd.rsvd2 = pt->cmd.rsvd2;
1313 	req->cmd.rsvd3 = pt->cmd.rsvd3;
1314 	req->cmd.cdw10 = pt->cmd.cdw10;
1315 	req->cmd.cdw11 = pt->cmd.cdw11;
1316 	req->cmd.cdw12 = pt->cmd.cdw12;
1317 	req->cmd.cdw13 = pt->cmd.cdw13;
1318 	req->cmd.cdw14 = pt->cmd.cdw14;
1319 	req->cmd.cdw15 = pt->cmd.cdw15;
1320 
1321 	req->cmd.nsid = htole32(nsid);
1322 
1323 	mtx = mtx_pool_find(mtxpool_sleep, pt);
1324 	pt->driver_lock = mtx;
1325 
1326 	if (is_admin_cmd)
1327 		nvme_ctrlr_submit_admin_request(ctrlr, req);
1328 	else
1329 		nvme_ctrlr_submit_io_request(ctrlr, req);
1330 
1331 	mtx_lock(mtx);
1332 	while (pt->driver_lock != NULL)
1333 		mtx_sleep(pt, mtx, PRIBIO, "nvme_pt", 0);
1334 	mtx_unlock(mtx);
1335 
1336 err:
1337 	if (buf != NULL) {
1338 		uma_zfree(pbuf_zone, buf);
1339 		PRELE(curproc);
1340 	}
1341 
1342 	return (ret);
1343 }
1344 
1345 static int
1346 nvme_ctrlr_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int flag,
1347     struct thread *td)
1348 {
1349 	struct nvme_controller			*ctrlr;
1350 	struct nvme_pt_command			*pt;
1351 
1352 	ctrlr = cdev->si_drv1;
1353 
1354 	switch (cmd) {
1355 	case NVME_RESET_CONTROLLER:
1356 		nvme_ctrlr_reset(ctrlr);
1357 		break;
1358 	case NVME_PASSTHROUGH_CMD:
1359 		pt = (struct nvme_pt_command *)arg;
1360 		return (nvme_ctrlr_passthrough_cmd(ctrlr, pt, le32toh(pt->cmd.nsid),
1361 		    1 /* is_user_buffer */, 1 /* is_admin_cmd */));
1362 	case NVME_GET_NSID:
1363 	{
1364 		struct nvme_get_nsid *gnsid = (struct nvme_get_nsid *)arg;
1365 		strncpy(gnsid->cdev, device_get_nameunit(ctrlr->dev),
1366 		    sizeof(gnsid->cdev));
1367 		gnsid->cdev[sizeof(gnsid->cdev) - 1] = '\0';
1368 		gnsid->nsid = 0;
1369 		break;
1370 	}
1371 	case NVME_GET_MAX_XFER_SIZE:
1372 		*(uint64_t *)arg = ctrlr->max_xfer_size;
1373 		break;
1374 	default:
1375 		return (ENOTTY);
1376 	}
1377 
1378 	return (0);
1379 }
1380 
1381 static struct cdevsw nvme_ctrlr_cdevsw = {
1382 	.d_version =	D_VERSION,
1383 	.d_flags =	0,
1384 	.d_ioctl =	nvme_ctrlr_ioctl
1385 };
1386 
1387 int
1388 nvme_ctrlr_construct(struct nvme_controller *ctrlr, device_t dev)
1389 {
1390 	struct make_dev_args	md_args;
1391 	uint32_t	cap_lo;
1392 	uint32_t	cap_hi;
1393 	uint32_t	to, vs, pmrcap;
1394 	int		status, timeout_period;
1395 
1396 	ctrlr->dev = dev;
1397 
1398 	mtx_init(&ctrlr->lock, "nvme ctrlr lock", NULL, MTX_DEF);
1399 	if (bus_get_domain(dev, &ctrlr->domain) != 0)
1400 		ctrlr->domain = 0;
1401 
1402 	ctrlr->cap_lo = cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
1403 	if (bootverbose) {
1404 		device_printf(dev, "CapLo: 0x%08x: MQES %u%s%s%s%s, TO %u\n",
1405 		    cap_lo, NVME_CAP_LO_MQES(cap_lo),
1406 		    NVME_CAP_LO_CQR(cap_lo) ? ", CQR" : "",
1407 		    NVME_CAP_LO_AMS(cap_lo) ? ", AMS" : "",
1408 		    (NVME_CAP_LO_AMS(cap_lo) & 0x1) ? " WRRwUPC" : "",
1409 		    (NVME_CAP_LO_AMS(cap_lo) & 0x2) ? " VS" : "",
1410 		    NVME_CAP_LO_TO(cap_lo));
1411 	}
1412 	ctrlr->cap_hi = cap_hi = nvme_mmio_read_4(ctrlr, cap_hi);
1413 	if (bootverbose) {
1414 		device_printf(dev, "CapHi: 0x%08x: DSTRD %u%s, CSS %x%s, "
1415 		    "MPSMIN %u, MPSMAX %u%s%s\n", cap_hi,
1416 		    NVME_CAP_HI_DSTRD(cap_hi),
1417 		    NVME_CAP_HI_NSSRS(cap_hi) ? ", NSSRS" : "",
1418 		    NVME_CAP_HI_CSS(cap_hi),
1419 		    NVME_CAP_HI_BPS(cap_hi) ? ", BPS" : "",
1420 		    NVME_CAP_HI_MPSMIN(cap_hi),
1421 		    NVME_CAP_HI_MPSMAX(cap_hi),
1422 		    NVME_CAP_HI_PMRS(cap_hi) ? ", PMRS" : "",
1423 		    NVME_CAP_HI_CMBS(cap_hi) ? ", CMBS" : "");
1424 	}
1425 	if (bootverbose) {
1426 		vs = nvme_mmio_read_4(ctrlr, vs);
1427 		device_printf(dev, "Version: 0x%08x: %d.%d\n", vs,
1428 		    NVME_MAJOR(vs), NVME_MINOR(vs));
1429 	}
1430 	if (bootverbose && NVME_CAP_HI_PMRS(cap_hi)) {
1431 		pmrcap = nvme_mmio_read_4(ctrlr, pmrcap);
1432 		device_printf(dev, "PMRCap: 0x%08x: BIR %u%s%s, PMRTU %u, "
1433 		    "PMRWBM %x, PMRTO %u%s\n", pmrcap,
1434 		    NVME_PMRCAP_BIR(pmrcap),
1435 		    NVME_PMRCAP_RDS(pmrcap) ? ", RDS" : "",
1436 		    NVME_PMRCAP_WDS(pmrcap) ? ", WDS" : "",
1437 		    NVME_PMRCAP_PMRTU(pmrcap),
1438 		    NVME_PMRCAP_PMRWBM(pmrcap),
1439 		    NVME_PMRCAP_PMRTO(pmrcap),
1440 		    NVME_PMRCAP_CMSS(pmrcap) ? ", CMSS" : "");
1441 	}
1442 
1443 	ctrlr->dstrd = NVME_CAP_HI_DSTRD(cap_hi) + 2;
1444 
1445 	ctrlr->mps = NVME_CAP_HI_MPSMIN(cap_hi);
1446 	ctrlr->page_size = 1 << (NVME_MPS_SHIFT + ctrlr->mps);
1447 
1448 	/* Get ready timeout value from controller, in units of 500ms. */
1449 	to = NVME_CAP_LO_TO(cap_lo) + 1;
1450 	ctrlr->ready_timeout_in_ms = to * 500;
1451 
1452 	timeout_period = NVME_DEFAULT_TIMEOUT_PERIOD;
1453 	TUNABLE_INT_FETCH("hw.nvme.timeout_period", &timeout_period);
1454 	timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1455 	timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1456 	ctrlr->timeout_period = timeout_period;
1457 
1458 	nvme_retry_count = NVME_DEFAULT_RETRY_COUNT;
1459 	TUNABLE_INT_FETCH("hw.nvme.retry_count", &nvme_retry_count);
1460 
1461 	ctrlr->enable_aborts = 0;
1462 	TUNABLE_INT_FETCH("hw.nvme.enable_aborts", &ctrlr->enable_aborts);
1463 
1464 	/* Cap transfers by the maximum addressable by page-sized PRP (4KB pages -> 2MB). */
1465 	ctrlr->max_xfer_size = MIN(maxphys, (ctrlr->page_size / 8 * ctrlr->page_size));
1466 	if (nvme_ctrlr_construct_admin_qpair(ctrlr) != 0)
1467 		return (ENXIO);
1468 
1469 	/*
1470 	 * Create 2 threads for the taskqueue. The reset thread will block when
1471 	 * it detects that the controller has failed until all I/O has been
1472 	 * failed up the stack. The fail_req task needs to be able to run in
1473 	 * this case to finish the request failure for some cases.
1474 	 *
1475 	 * We could partially solve this race by draining the failed requeust
1476 	 * queue before proceding to free the sim, though nothing would stop
1477 	 * new I/O from coming in after we do that drain, but before we reach
1478 	 * cam_sim_free, so this big hammer is used instead.
1479 	 */
1480 	ctrlr->taskqueue = taskqueue_create("nvme_taskq", M_WAITOK,
1481 	    taskqueue_thread_enqueue, &ctrlr->taskqueue);
1482 	taskqueue_start_threads(&ctrlr->taskqueue, 2, PI_DISK, "nvme taskq");
1483 
1484 	ctrlr->is_resetting = 0;
1485 	ctrlr->is_initialized = 0;
1486 	ctrlr->notification_sent = 0;
1487 	TASK_INIT(&ctrlr->reset_task, 0, nvme_ctrlr_reset_task, ctrlr);
1488 	TASK_INIT(&ctrlr->fail_req_task, 0, nvme_ctrlr_fail_req_task, ctrlr);
1489 	STAILQ_INIT(&ctrlr->fail_req);
1490 	ctrlr->is_failed = false;
1491 
1492 	make_dev_args_init(&md_args);
1493 	md_args.mda_devsw = &nvme_ctrlr_cdevsw;
1494 	md_args.mda_uid = UID_ROOT;
1495 	md_args.mda_gid = GID_WHEEL;
1496 	md_args.mda_mode = 0600;
1497 	md_args.mda_unit = device_get_unit(dev);
1498 	md_args.mda_si_drv1 = (void *)ctrlr;
1499 	status = make_dev_s(&md_args, &ctrlr->cdev, "nvme%d",
1500 	    device_get_unit(dev));
1501 	if (status != 0)
1502 		return (ENXIO);
1503 
1504 	return (0);
1505 }
1506 
1507 void
1508 nvme_ctrlr_destruct(struct nvme_controller *ctrlr, device_t dev)
1509 {
1510 	int	gone, i;
1511 
1512 	ctrlr->is_dying = true;
1513 
1514 	if (ctrlr->resource == NULL)
1515 		goto nores;
1516 	if (!mtx_initialized(&ctrlr->adminq.lock))
1517 		goto noadminq;
1518 
1519 	/*
1520 	 * Check whether it is a hot unplug or a clean driver detach.
1521 	 * If device is not there any more, skip any shutdown commands.
1522 	 */
1523 	gone = (nvme_mmio_read_4(ctrlr, csts) == NVME_GONE);
1524 	if (gone)
1525 		nvme_ctrlr_fail(ctrlr);
1526 	else
1527 		nvme_notify_fail_consumers(ctrlr);
1528 
1529 	for (i = 0; i < NVME_MAX_NAMESPACES; i++)
1530 		nvme_ns_destruct(&ctrlr->ns[i]);
1531 
1532 	if (ctrlr->cdev)
1533 		destroy_dev(ctrlr->cdev);
1534 
1535 	if (ctrlr->is_initialized) {
1536 		if (!gone) {
1537 			if (ctrlr->hmb_nchunks > 0)
1538 				nvme_ctrlr_hmb_enable(ctrlr, false, false);
1539 			nvme_ctrlr_delete_qpairs(ctrlr);
1540 		}
1541 		nvme_ctrlr_hmb_free(ctrlr);
1542 	}
1543 	if (ctrlr->ioq != NULL) {
1544 		for (i = 0; i < ctrlr->num_io_queues; i++)
1545 			nvme_io_qpair_destroy(&ctrlr->ioq[i]);
1546 		free(ctrlr->ioq, M_NVME);
1547 	}
1548 	nvme_admin_qpair_destroy(&ctrlr->adminq);
1549 
1550 	/*
1551 	 *  Notify the controller of a shutdown, even though this is due to
1552 	 *   a driver unload, not a system shutdown (this path is not invoked
1553 	 *   during shutdown).  This ensures the controller receives a
1554 	 *   shutdown notification in case the system is shutdown before
1555 	 *   reloading the driver.
1556 	 */
1557 	if (!gone)
1558 		nvme_ctrlr_shutdown(ctrlr);
1559 
1560 	if (!gone)
1561 		nvme_ctrlr_disable(ctrlr);
1562 
1563 noadminq:
1564 	if (ctrlr->taskqueue)
1565 		taskqueue_free(ctrlr->taskqueue);
1566 
1567 	if (ctrlr->tag)
1568 		bus_teardown_intr(ctrlr->dev, ctrlr->res, ctrlr->tag);
1569 
1570 	if (ctrlr->res)
1571 		bus_release_resource(ctrlr->dev, SYS_RES_IRQ,
1572 		    rman_get_rid(ctrlr->res), ctrlr->res);
1573 
1574 	if (ctrlr->bar4_resource != NULL) {
1575 		bus_release_resource(dev, SYS_RES_MEMORY,
1576 		    ctrlr->bar4_resource_id, ctrlr->bar4_resource);
1577 	}
1578 
1579 	bus_release_resource(dev, SYS_RES_MEMORY,
1580 	    ctrlr->resource_id, ctrlr->resource);
1581 
1582 nores:
1583 	mtx_destroy(&ctrlr->lock);
1584 }
1585 
1586 void
1587 nvme_ctrlr_shutdown(struct nvme_controller *ctrlr)
1588 {
1589 	uint32_t	cc;
1590 	uint32_t	csts;
1591 	int		timeout;
1592 
1593 	cc = nvme_mmio_read_4(ctrlr, cc);
1594 	cc &= ~(NVME_CC_REG_SHN_MASK << NVME_CC_REG_SHN_SHIFT);
1595 	cc |= NVME_SHN_NORMAL << NVME_CC_REG_SHN_SHIFT;
1596 	nvme_mmio_write_4(ctrlr, cc, cc);
1597 
1598 	timeout = ticks + (ctrlr->cdata.rtd3e == 0 ? 5 * hz :
1599 	    ((uint64_t)ctrlr->cdata.rtd3e * hz + 999999) / 1000000);
1600 	while (1) {
1601 		csts = nvme_mmio_read_4(ctrlr, csts);
1602 		if (csts == NVME_GONE)		/* Hot unplug. */
1603 			break;
1604 		if (NVME_CSTS_GET_SHST(csts) == NVME_SHST_COMPLETE)
1605 			break;
1606 		if (timeout - ticks < 0) {
1607 			nvme_printf(ctrlr, "shutdown timeout\n");
1608 			break;
1609 		}
1610 		pause("nvmeshut", 1);
1611 	}
1612 }
1613 
1614 void
1615 nvme_ctrlr_submit_admin_request(struct nvme_controller *ctrlr,
1616     struct nvme_request *req)
1617 {
1618 
1619 	nvme_qpair_submit_request(&ctrlr->adminq, req);
1620 }
1621 
1622 void
1623 nvme_ctrlr_submit_io_request(struct nvme_controller *ctrlr,
1624     struct nvme_request *req)
1625 {
1626 	struct nvme_qpair       *qpair;
1627 
1628 	qpair = &ctrlr->ioq[QP(ctrlr, curcpu)];
1629 	nvme_qpair_submit_request(qpair, req);
1630 }
1631 
1632 device_t
1633 nvme_ctrlr_get_device(struct nvme_controller *ctrlr)
1634 {
1635 
1636 	return (ctrlr->dev);
1637 }
1638 
1639 const struct nvme_controller_data *
1640 nvme_ctrlr_get_data(struct nvme_controller *ctrlr)
1641 {
1642 
1643 	return (&ctrlr->cdata);
1644 }
1645 
1646 int
1647 nvme_ctrlr_suspend(struct nvme_controller *ctrlr)
1648 {
1649 	int to = hz;
1650 
1651 	/*
1652 	 * Can't touch failed controllers, so it's already suspended.
1653 	 */
1654 	if (ctrlr->is_failed)
1655 		return (0);
1656 
1657 	/*
1658 	 * We don't want the reset taskqueue running, since it does similar
1659 	 * things, so prevent it from running after we start. Wait for any reset
1660 	 * that may have been started to complete. The reset process we follow
1661 	 * will ensure that any new I/O will queue and be given to the hardware
1662 	 * after we resume (though there should be none).
1663 	 */
1664 	while (atomic_cmpset_32(&ctrlr->is_resetting, 0, 1) == 0 && to-- > 0)
1665 		pause("nvmesusp", 1);
1666 	if (to <= 0) {
1667 		nvme_printf(ctrlr,
1668 		    "Competing reset task didn't finish. Try again later.\n");
1669 		return (EWOULDBLOCK);
1670 	}
1671 
1672 	if (ctrlr->hmb_nchunks > 0)
1673 		nvme_ctrlr_hmb_enable(ctrlr, false, false);
1674 
1675 	/*
1676 	 * Per Section 7.6.2 of NVMe spec 1.4, to properly suspend, we need to
1677 	 * delete the hardware I/O queues, and then shutdown. This properly
1678 	 * flushes any metadata the drive may have stored so it can survive
1679 	 * having its power removed and prevents the unsafe shutdown count from
1680 	 * incriminating. Once we delete the qpairs, we have to disable them
1681 	 * before shutting down.
1682 	 */
1683 	nvme_ctrlr_delete_qpairs(ctrlr);
1684 	nvme_ctrlr_disable_qpairs(ctrlr);
1685 	nvme_ctrlr_shutdown(ctrlr);
1686 
1687 	return (0);
1688 }
1689 
1690 int
1691 nvme_ctrlr_resume(struct nvme_controller *ctrlr)
1692 {
1693 
1694 	/*
1695 	 * Can't touch failed controllers, so nothing to do to resume.
1696 	 */
1697 	if (ctrlr->is_failed)
1698 		return (0);
1699 
1700 	if (nvme_ctrlr_hw_reset(ctrlr) != 0)
1701 		goto fail;
1702 #ifdef NVME_2X_RESET
1703 	/*
1704 	 * Prior to FreeBSD 13.1, FreeBSD's nvme driver reset the hardware twice
1705 	 * to get it into a known good state. However, the hardware's state is
1706 	 * good and we don't need to do this for proper functioning.
1707 	 */
1708 	if (nvme_ctrlr_hw_reset(ctrlr) != 0)
1709 		goto fail;
1710 #endif
1711 
1712 	/*
1713 	 * Now that we've reset the hardware, we can restart the controller. Any
1714 	 * I/O that was pending is requeued. Any admin commands are aborted with
1715 	 * an error. Once we've restarted, take the controller out of reset.
1716 	 */
1717 	nvme_ctrlr_start(ctrlr, true);
1718 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
1719 
1720 	return (0);
1721 fail:
1722 	/*
1723 	 * Since we can't bring the controller out of reset, announce and fail
1724 	 * the controller. However, we have to return success for the resume
1725 	 * itself, due to questionable APIs.
1726 	 */
1727 	nvme_printf(ctrlr, "Failed to reset on resume, failing.\n");
1728 	nvme_ctrlr_fail(ctrlr);
1729 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
1730 	return (0);
1731 }
1732