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