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