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