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