xref: /freebsd/sys/dev/nvme/nvme_ctrlr.c (revision 85fb40bad584e7d8c503e5a99bb81cc2d3cf9fee)
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 (uint32_t i = 0; i < aer->log_page_size / sizeof(*err); 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 	/* INTMS/INTMC are undefined when configured for MSI-X. */
1409 	if (!ctrlr->is_msix)
1410 		nvme_mmio_write_4(ctrlr, intms, 1);
1411 	nvme_ctrlr_poll(ctrlr);
1412 	if (!ctrlr->is_msix)
1413 		nvme_mmio_write_4(ctrlr, intmc, 1);
1414 }
1415 
1416 #define NVME_MAX_PAGES  (int)(1024 / sizeof(vm_page_t))
1417 
1418 static int
1419 nvme_page_count(vm_offset_t start, size_t len)
1420 {
1421 	return atop(round_page(start + len) - trunc_page(start));
1422 }
1423 
1424 static int
1425 nvme_user_ioctl_req(vm_offset_t addr, size_t len, bool is_read,
1426     vm_page_t **upages, int max_pages, int *npagesp, struct nvme_request **req,
1427     nvme_cb_fn_t cb_fn, void *cb_arg)
1428 {
1429 	vm_prot_t prot = VM_PROT_READ;
1430 	int err, npages;
1431 	vm_page_t *upages_us;
1432 
1433 	upages_us = *upages;
1434 	npages = nvme_page_count(addr, len);
1435 	if (npages > atop(maxphys))
1436 		return (EINVAL);
1437 	if (npages > max_pages)
1438 		upages_us = malloc(npages * sizeof(vm_page_t), M_NVME,
1439 		    M_ZERO | M_WAITOK);
1440 
1441 	if (is_read)
1442 		prot |= VM_PROT_WRITE;	/* Device will write to host memory */
1443 	err = vm_fault_hold_pages(&curproc->p_vmspace->vm_map,
1444 	    addr, len, prot, upages_us, npages, npagesp);
1445 	if (err != 0) {
1446 		if (*upages != upages_us)
1447 			free(upages_us, M_NVME);
1448 		return (err);
1449 	}
1450 	*req = nvme_allocate_request_null(M_WAITOK, cb_fn, cb_arg);
1451 	(*req)->payload = memdesc_vmpages(upages_us, len, addr & PAGE_MASK);
1452 	(*req)->payload_valid = true;
1453 	if (*upages != upages_us)
1454 		*upages = upages_us;
1455 	return (0);
1456 }
1457 
1458 static void
1459 nvme_user_ioctl_free(vm_page_t *pages, int npage, bool freeit)
1460 {
1461 	vm_page_unhold_pages(pages, npage);
1462 	if (freeit)
1463 		free(pages, M_NVME);
1464 }
1465 
1466 static void
1467 nvme_pt_done(void *arg, const struct nvme_completion *cpl)
1468 {
1469 	struct nvme_pt_command *pt = arg;
1470 	struct mtx *mtx = pt->driver_lock;
1471 	uint16_t status;
1472 
1473 	bzero(&pt->cpl, sizeof(pt->cpl));
1474 	pt->cpl.cdw0 = cpl->cdw0;
1475 
1476 	status = cpl->status;
1477 	status &= ~NVMEM(NVME_STATUS_P);
1478 	pt->cpl.status = status;
1479 
1480 	mtx_lock(mtx);
1481 	pt->driver_lock = NULL;
1482 	wakeup(pt);
1483 	mtx_unlock(mtx);
1484 }
1485 
1486 int
1487 nvme_ctrlr_passthrough_cmd(struct nvme_controller *ctrlr,
1488     struct nvme_pt_command *pt, uint32_t nsid, int is_user,
1489     int is_admin_cmd)
1490 {
1491 	struct nvme_request *req;
1492 	struct mtx *mtx;
1493 	int ret = 0;
1494 	int npages = 0;
1495 	vm_page_t upages_small[NVME_MAX_PAGES];
1496 	vm_page_t *upages = upages_small;
1497 
1498 	if (pt->len > 0) {
1499 		if (pt->len > ctrlr->max_xfer_size) {
1500 			nvme_printf(ctrlr,
1501 			    "len (%d) exceeds max_xfer_size (%d)\n",
1502 			    pt->len, ctrlr->max_xfer_size);
1503 			return (EIO);
1504 		}
1505 		if (is_user) {
1506 			ret = nvme_user_ioctl_req((vm_offset_t)pt->buf, pt->len,
1507 			    pt->is_read, &upages, nitems(upages_small), &npages, &req,
1508 			    nvme_pt_done, pt);
1509 			if (ret != 0)
1510 				return (ret);
1511 		} else
1512 			req = nvme_allocate_request_vaddr(pt->buf, pt->len,
1513 			    M_WAITOK, nvme_pt_done, pt);
1514 	} else
1515 		req = nvme_allocate_request_null(M_WAITOK, nvme_pt_done, pt);
1516 
1517 	/* Assume user space already converted to little-endian */
1518 	req->cmd.opc = pt->cmd.opc;
1519 	req->cmd.fuse = pt->cmd.fuse;
1520 	req->cmd.rsvd2 = pt->cmd.rsvd2;
1521 	req->cmd.rsvd3 = pt->cmd.rsvd3;
1522 	req->cmd.cdw10 = pt->cmd.cdw10;
1523 	req->cmd.cdw11 = pt->cmd.cdw11;
1524 	req->cmd.cdw12 = pt->cmd.cdw12;
1525 	req->cmd.cdw13 = pt->cmd.cdw13;
1526 	req->cmd.cdw14 = pt->cmd.cdw14;
1527 	req->cmd.cdw15 = pt->cmd.cdw15;
1528 
1529 	req->cmd.nsid = htole32(nsid);
1530 
1531 	mtx = mtx_pool_find(mtxpool_sleep, pt);
1532 	pt->driver_lock = mtx;
1533 
1534 	if (is_admin_cmd)
1535 		nvme_ctrlr_submit_admin_request(ctrlr, req);
1536 	else
1537 		nvme_ctrlr_submit_io_request(ctrlr, req);
1538 
1539 	mtx_lock(mtx);
1540 	while (pt->driver_lock != NULL)
1541 		mtx_sleep(pt, mtx, PRIBIO, "nvme_pt", 0);
1542 	mtx_unlock(mtx);
1543 
1544 	if (npages > 0)
1545 		nvme_user_ioctl_free(upages, npages, upages != upages_small);
1546 
1547 	return (ret);
1548 }
1549 
1550 static void
1551 nvme_npc_done(void *arg, const struct nvme_completion *cpl)
1552 {
1553 	struct nvme_passthru_cmd *npc = arg;
1554 	struct mtx *mtx = (void *)(uintptr_t)npc->metadata;
1555 
1556 	npc->result = cpl->cdw0;	/* cpl in host order by now */
1557 	mtx_lock(mtx);
1558 	npc->metadata = 0;
1559 	wakeup(npc);
1560 	mtx_unlock(mtx);
1561 }
1562 
1563 /* XXX refactor? */
1564 
1565 int
1566 nvme_ctrlr_linux_passthru_cmd(struct nvme_controller *ctrlr,
1567     struct nvme_passthru_cmd *npc, uint32_t nsid, bool is_user, bool is_admin)
1568 {
1569 	struct nvme_request	*req;
1570 	struct mtx		*mtx;
1571 	int			ret = 0;
1572 	int			npages = 0;
1573 	vm_page_t		upages_small[NVME_MAX_PAGES];
1574 	vm_page_t		*upages = upages_small;
1575 
1576 	/*
1577 	 * We don't support metadata.
1578 	 */
1579 	if (npc->metadata != 0 || npc->metadata_len != 0)
1580 		return (EIO);
1581 
1582 	if (npc->data_len > 0 && npc->addr != 0) {
1583 		if (npc->data_len > ctrlr->max_xfer_size) {
1584 			nvme_printf(ctrlr,
1585 			    "data_len (%d) exceeds max_xfer_size (%d)\n",
1586 			    npc->data_len, ctrlr->max_xfer_size);
1587 			return (EIO);
1588 		}
1589 		if (is_user) {
1590 			ret = nvme_user_ioctl_req(npc->addr, npc->data_len,
1591 			    npc->opcode & 0x1, &upages, nitems(upages_small),
1592 			    &npages, &req, nvme_npc_done, npc);
1593 			if (ret != 0)
1594 				return (ret);
1595 		} else
1596 			req = nvme_allocate_request_vaddr(
1597 			    (void *)(uintptr_t)npc->addr, npc->data_len,
1598 			    M_WAITOK, nvme_npc_done, npc);
1599 	} else
1600 		req = nvme_allocate_request_null(M_WAITOK, nvme_npc_done, npc);
1601 
1602 	req->cmd.opc = npc->opcode;
1603 	req->cmd.fuse = npc->flags;
1604 	req->cmd.rsvd2 = htole32(npc->cdw2);
1605 	req->cmd.rsvd3 = htole32(npc->cdw3);
1606 	req->cmd.cdw10 = htole32(npc->cdw10);
1607 	req->cmd.cdw11 = htole32(npc->cdw11);
1608 	req->cmd.cdw12 = htole32(npc->cdw12);
1609 	req->cmd.cdw13 = htole32(npc->cdw13);
1610 	req->cmd.cdw14 = htole32(npc->cdw14);
1611 	req->cmd.cdw15 = htole32(npc->cdw15);
1612 
1613 	req->cmd.nsid = htole32(nsid);
1614 
1615 	mtx = mtx_pool_find(mtxpool_sleep, npc);
1616 	npc->metadata = (uintptr_t) mtx;
1617 
1618 	/* XXX no timeout passed down */
1619 	if (is_admin)
1620 		nvme_ctrlr_submit_admin_request(ctrlr, req);
1621 	else
1622 		nvme_ctrlr_submit_io_request(ctrlr, req);
1623 
1624 	mtx_lock(mtx);
1625 	while (npc->metadata != 0)
1626 		mtx_sleep(npc, mtx, PRIBIO, "nvme_npc", 0);
1627 	mtx_unlock(mtx);
1628 
1629 	if (npages > 0)
1630 		nvme_user_ioctl_free(upages, npages, upages != upages_small);
1631 
1632 	return (ret);
1633 }
1634 
1635 static int
1636 nvme_ctrlr_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int flag,
1637     struct thread *td)
1638 {
1639 	struct nvme_controller			*ctrlr;
1640 	struct nvme_pt_command			*pt;
1641 
1642 	ctrlr = cdev->si_drv1;
1643 
1644 	switch (cmd) {
1645 	case NVME_IOCTL_RESET: /* Linux compat */
1646 	case NVME_RESET_CONTROLLER:
1647 		nvme_ctrlr_reset(ctrlr);
1648 		break;
1649 	case NVME_PASSTHROUGH_CMD:
1650 		pt = (struct nvme_pt_command *)arg;
1651 		return (nvme_ctrlr_passthrough_cmd(ctrlr, pt, le32toh(pt->cmd.nsid),
1652 		    1 /* is_user_buffer */, 1 /* is_admin_cmd */));
1653 	case NVME_GET_NSID:
1654 	{
1655 		struct nvme_get_nsid *gnsid = (struct nvme_get_nsid *)arg;
1656 		strlcpy(gnsid->cdev, device_get_nameunit(ctrlr->dev),
1657 		    sizeof(gnsid->cdev));
1658 		gnsid->nsid = 0;
1659 		break;
1660 	}
1661 	case NVME_GET_MAX_XFER_SIZE:
1662 		*(uint64_t *)arg = ctrlr->max_xfer_size;
1663 		break;
1664 	case NVME_GET_CONTROLLER_DATA:
1665 		memcpy(arg, &ctrlr->cdata, sizeof(ctrlr->cdata));
1666 		break;
1667 	case DIOCGIDENT: {
1668 		uint8_t *sn = arg;
1669 		nvme_cdata_get_disk_ident(&ctrlr->cdata, sn);
1670 		break;
1671 	}
1672 	/* Linux Compatible (see nvme_linux.h) */
1673 	case NVME_IOCTL_ID:
1674 		td->td_retval[0] = 0xfffffffful;
1675 		return (0);
1676 
1677 	case NVME_IOCTL_ADMIN_CMD:
1678 	case NVME_IOCTL_IO_CMD: {
1679 		struct nvme_passthru_cmd *npc = (struct nvme_passthru_cmd *)arg;
1680 
1681 		return (nvme_ctrlr_linux_passthru_cmd(ctrlr, npc, npc->nsid, true,
1682 		    cmd == NVME_IOCTL_ADMIN_CMD));
1683 	}
1684 
1685 	default:
1686 		return (ENOTTY);
1687 	}
1688 
1689 	return (0);
1690 }
1691 
1692 static struct cdevsw nvme_ctrlr_cdevsw = {
1693 	.d_version =	D_VERSION,
1694 	.d_flags =	0,
1695 	.d_ioctl =	nvme_ctrlr_ioctl
1696 };
1697 
1698 int
1699 nvme_ctrlr_construct(struct nvme_controller *ctrlr, device_t dev)
1700 {
1701 	struct make_dev_args	md_args;
1702 	uint32_t	cap_lo;
1703 	uint32_t	cap_hi;
1704 	uint32_t	to, vs, pmrcap;
1705 	int		status, timeout_period;
1706 
1707 	ctrlr->dev = dev;
1708 	ctrlr->io_sqes =
1709 	    (ctrlr->quirks & QUIRK_APPLE_128_BYTE_SQES) != 0 ?
1710 	    NVME_IOSQES_128 : NVME_IOSQES_64;
1711 
1712 	mtx_init(&ctrlr->lock, "nvme ctrlr lock", NULL, MTX_DEF);
1713 	if (bus_get_domain(dev, &ctrlr->domain) != 0)
1714 		ctrlr->domain = 0;
1715 
1716 	ctrlr->cap_lo = cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
1717 	if (bootverbose) {
1718 		device_printf(dev, "CapLo: 0x%08x: MQES %u%s%s%s%s, TO %u\n",
1719 		    cap_lo, NVME_CAP_LO_MQES(cap_lo),
1720 		    NVME_CAP_LO_CQR(cap_lo) ? ", CQR" : "",
1721 		    NVME_CAP_LO_AMS(cap_lo) ? ", AMS" : "",
1722 		    (NVME_CAP_LO_AMS(cap_lo) & 0x1) ? " WRRwUPC" : "",
1723 		    (NVME_CAP_LO_AMS(cap_lo) & 0x2) ? " VS" : "",
1724 		    NVME_CAP_LO_TO(cap_lo));
1725 	}
1726 	ctrlr->cap_hi = cap_hi = nvme_mmio_read_4(ctrlr, cap_hi);
1727 	if (bootverbose) {
1728 		device_printf(dev, "CapHi: 0x%08x: DSTRD %u%s, CSS %x%s, "
1729 		    "CPS %x, MPSMIN %u, MPSMAX %u%s%s%s%s%s\n", cap_hi,
1730 		    NVME_CAP_HI_DSTRD(cap_hi),
1731 		    NVME_CAP_HI_NSSRS(cap_hi) ? ", NSSRS" : "",
1732 		    NVME_CAP_HI_CSS(cap_hi),
1733 		    NVME_CAP_HI_BPS(cap_hi) ? ", BPS" : "",
1734 		    NVME_CAP_HI_CPS(cap_hi),
1735 		    NVME_CAP_HI_MPSMIN(cap_hi),
1736 		    NVME_CAP_HI_MPSMAX(cap_hi),
1737 		    NVME_CAP_HI_PMRS(cap_hi) ? ", PMRS" : "",
1738 		    NVME_CAP_HI_CMBS(cap_hi) ? ", CMBS" : "",
1739 		    NVME_CAP_HI_NSSS(cap_hi) ? ", NSSS" : "",
1740 		    NVME_CAP_HI_CRWMS(cap_hi) ? ", CRWMS" : "",
1741 		    NVME_CAP_HI_CRIMS(cap_hi) ? ", CRIMS" : "");
1742 	}
1743 	if (bootverbose) {
1744 		vs = nvme_mmio_read_4(ctrlr, vs);
1745 		device_printf(dev, "Version: 0x%08x: %d.%d\n", vs,
1746 		    NVME_MAJOR(vs), NVME_MINOR(vs));
1747 	}
1748 	if (bootverbose && NVME_CAP_HI_PMRS(cap_hi)) {
1749 		pmrcap = nvme_mmio_read_4(ctrlr, pmrcap);
1750 		device_printf(dev, "PMRCap: 0x%08x: BIR %u%s%s, PMRTU %u, "
1751 		    "PMRWBM %x, PMRTO %u%s\n", pmrcap,
1752 		    NVME_PMRCAP_BIR(pmrcap),
1753 		    NVME_PMRCAP_RDS(pmrcap) ? ", RDS" : "",
1754 		    NVME_PMRCAP_WDS(pmrcap) ? ", WDS" : "",
1755 		    NVME_PMRCAP_PMRTU(pmrcap),
1756 		    NVME_PMRCAP_PMRWBM(pmrcap),
1757 		    NVME_PMRCAP_PMRTO(pmrcap),
1758 		    NVME_PMRCAP_CMSS(pmrcap) ? ", CMSS" : "");
1759 	}
1760 
1761 	ctrlr->dstrd = NVME_CAP_HI_DSTRD(cap_hi) + 2;
1762 
1763 	ctrlr->mps = NVME_CAP_HI_MPSMIN(cap_hi);
1764 	ctrlr->page_size = 1 << (NVME_MPS_SHIFT + ctrlr->mps);
1765 
1766 	/* Get ready timeout value from controller, in units of 500ms. */
1767 	to = NVME_CAP_LO_TO(cap_lo) + 1;
1768 	ctrlr->ready_timeout_in_ms = to * 500;
1769 
1770 	timeout_period = NVME_ADMIN_TIMEOUT_PERIOD;
1771 	TUNABLE_INT_FETCH("hw.nvme.admin_timeout_period", &timeout_period);
1772 	timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1773 	timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1774 	ctrlr->admin_timeout_period = timeout_period;
1775 
1776 	timeout_period = NVME_DEFAULT_TIMEOUT_PERIOD;
1777 	TUNABLE_INT_FETCH("hw.nvme.timeout_period", &timeout_period);
1778 	timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1779 	timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1780 	ctrlr->timeout_period = timeout_period;
1781 
1782 	nvme_retry_count = NVME_DEFAULT_RETRY_COUNT;
1783 	TUNABLE_INT_FETCH("hw.nvme.retry_count", &nvme_retry_count);
1784 
1785 	ctrlr->enable_aborts = 0;
1786 	TUNABLE_INT_FETCH("hw.nvme.enable_aborts", &ctrlr->enable_aborts);
1787 
1788 	ctrlr->alignment_splits = counter_u64_alloc(M_WAITOK);
1789 
1790 	/* Cap transfers by the maximum addressable by page-sized PRP (4KB pages -> 2MB). */
1791 	ctrlr->max_xfer_size = MIN(maxphys, (ctrlr->page_size / 8 * ctrlr->page_size));
1792 	if (nvme_ctrlr_construct_admin_qpair(ctrlr) != 0)
1793 		return (ENXIO);
1794 
1795 	/*
1796 	 * Create 2 threads for the taskqueue. The reset thread will block when
1797 	 * it detects that the controller has failed until all I/O has been
1798 	 * failed up the stack. The second thread is used for AER events, which
1799 	 * can block, but only briefly for memory and log page fetching.
1800 	 */
1801 	ctrlr->taskqueue = taskqueue_create("nvme_taskq", M_WAITOK,
1802 	    taskqueue_thread_enqueue, &ctrlr->taskqueue);
1803 	taskqueue_start_threads(&ctrlr->taskqueue, 2, PI_DISK, "nvme taskq");
1804 
1805 	ctrlr->is_resetting = 0;
1806 	ctrlr->is_initialized = false;
1807 	TASK_INIT(&ctrlr->reset_task, 0, nvme_ctrlr_reset_task, ctrlr);
1808 	for (int i = 0; i < NVME_MAX_ASYNC_EVENTS; i++) {
1809 		struct nvme_async_event_request *aer = &ctrlr->aer[i];
1810 
1811 		TASK_INIT(&aer->task, 0, nvme_ctrlr_aer_task, aer);
1812 		mtx_init(&aer->mtx, "AER mutex", NULL, MTX_DEF);
1813 	}
1814 	ctrlr->is_failed = false;
1815 
1816 	make_dev_args_init(&md_args);
1817 	md_args.mda_devsw = &nvme_ctrlr_cdevsw;
1818 	md_args.mda_uid = UID_ROOT;
1819 	md_args.mda_gid = GID_WHEEL;
1820 	md_args.mda_mode = 0600;
1821 	md_args.mda_unit = device_get_unit(dev);
1822 	md_args.mda_si_drv1 = (void *)ctrlr;
1823 	status = make_dev_s(&md_args, &ctrlr->cdev, "%s",
1824 	    device_get_nameunit(dev));
1825 	if (status != 0)
1826 		return (ENXIO);
1827 
1828 	return (0);
1829 }
1830 
1831 /*
1832  * Called on detach, or on error on attach. The nvme_controller won't be used
1833  * again once we return, so we have to tear everything down (so nothing
1834  * references this, no callbacks, etc), but don't need to reset all the state
1835  * since nvme_controller will be freed soon.
1836  */
1837 void
1838 nvme_ctrlr_destruct(struct nvme_controller *ctrlr, device_t dev)
1839 {
1840 	int	i;
1841 	bool	gone;
1842 
1843 	ctrlr->is_dying = true;
1844 
1845 	if (ctrlr->resource == NULL)
1846 		goto nores;
1847 	if (!mtx_initialized(&ctrlr->adminq.lock))
1848 		goto noadminq;
1849 
1850 	/*
1851 	 * Check whether it is a hot unplug or a clean driver detach.  If device
1852 	 * is not there any more, skip any shutdown commands.  Some hotplug
1853 	 * bridges will return zeros instead of ff's when the device is
1854 	 * departing, so ask the bridge if the device is gone. Some systems can
1855 	 * remove the drive w/o the bridge knowing its gone (they don't really
1856 	 * do hotplug), so failsafe with detecting all ff's (impossible with
1857 	 * this hardware) as the device being gone.
1858 	 */
1859 	gone = bus_child_present(dev) == 0 ||
1860 	    (nvme_mmio_read_4(ctrlr, csts) == NVME_GONE);
1861 	if (gone)
1862 		nvme_ctrlr_fail(ctrlr, true);
1863 	else
1864 		nvme_notify_fail(ctrlr);
1865 
1866 	for (i = 0; i < NVME_MAX_NAMESPACES; i++)
1867 		nvme_ns_destruct(&ctrlr->ns[i]);
1868 
1869 	if (ctrlr->cdev)
1870 		destroy_dev(ctrlr->cdev);
1871 
1872 	if (ctrlr->is_initialized) {
1873 		if (!gone) {
1874 			if (ctrlr->hmb_nchunks > 0)
1875 				nvme_ctrlr_hmb_enable(ctrlr, false, false);
1876 			nvme_ctrlr_delete_qpairs(ctrlr);
1877 		}
1878 		nvme_ctrlr_hmb_free(ctrlr);
1879 	}
1880 	if (ctrlr->ioq != NULL) {
1881 		for (i = 0; i < ctrlr->num_io_queues; i++)
1882 			nvme_io_qpair_destroy(&ctrlr->ioq[i]);
1883 		free(ctrlr->ioq, M_NVME);
1884 	}
1885 	nvme_admin_qpair_destroy(&ctrlr->adminq);
1886 
1887 	/*
1888 	 * Notify the controller of a shutdown, even though this is due to a
1889 	 * driver unload, not a system shutdown (this path is not invoked uring
1890 	 * shutdown).  This ensures the controller receives a shutdown
1891 	 * notification in case the system is shutdown before reloading the
1892 	 * driver. Some NVMe drives need this to flush their cache to stable
1893 	 * media and consider it a safe shutdown in SMART stats.
1894 	 */
1895 	if (!gone) {
1896 		nvme_ctrlr_shutdown(ctrlr);
1897 		nvme_ctrlr_disable(ctrlr);
1898 	}
1899 
1900 noadminq:
1901 	if (ctrlr->taskqueue) {
1902 		taskqueue_free(ctrlr->taskqueue);
1903 		for (int i = 0; i < NVME_MAX_ASYNC_EVENTS; i++) {
1904 			struct nvme_async_event_request *aer = &ctrlr->aer[i];
1905 
1906 			mtx_destroy(&aer->mtx);
1907 		}
1908 	}
1909 
1910 	if (ctrlr->tag)
1911 		bus_teardown_intr(ctrlr->dev, ctrlr->res, ctrlr->tag);
1912 
1913 	if (ctrlr->res)
1914 		bus_release_resource(ctrlr->dev, SYS_RES_IRQ,
1915 		    rman_get_rid(ctrlr->res), ctrlr->res);
1916 
1917 	if (ctrlr->msix_table_resource != NULL) {
1918 		bus_release_resource(dev, SYS_RES_MEMORY,
1919 		    ctrlr->msix_table_resource_id, ctrlr->msix_table_resource);
1920 	}
1921 
1922 	if (ctrlr->msix_pba_resource != NULL) {
1923 		bus_release_resource(dev, SYS_RES_MEMORY,
1924 		    ctrlr->msix_pba_resource_id, ctrlr->msix_pba_resource);
1925 	}
1926 
1927 	bus_release_resource(dev, SYS_RES_MEMORY,
1928 	    ctrlr->resource_id, ctrlr->resource);
1929 
1930 nores:
1931 	if (ctrlr->alignment_splits)
1932 		counter_u64_free(ctrlr->alignment_splits);
1933 
1934 	mtx_destroy(&ctrlr->lock);
1935 }
1936 
1937 void
1938 nvme_ctrlr_shutdown(struct nvme_controller *ctrlr)
1939 {
1940 	uint32_t	cc;
1941 	uint32_t	csts;
1942 	int		timeout;
1943 
1944 	cc = nvme_mmio_read_4(ctrlr, cc);
1945 	cc &= ~NVMEM(NVME_CC_REG_SHN);
1946 	cc |= NVMEF(NVME_CC_REG_SHN, NVME_SHN_NORMAL);
1947 	nvme_mmio_write_4(ctrlr, cc, cc);
1948 
1949 	timeout = ticks + (ctrlr->cdata.rtd3e == 0 ? 5 * hz :
1950 	    ((uint64_t)ctrlr->cdata.rtd3e * hz + 999999) / 1000000);
1951 	while (1) {
1952 		csts = nvme_mmio_read_4(ctrlr, csts);
1953 		if (csts == NVME_GONE)		/* Hot unplug. */
1954 			break;
1955 		if (NVME_CSTS_GET_SHST(csts) == NVME_SHST_COMPLETE)
1956 			break;
1957 		if (timeout - ticks < 0) {
1958 			nvme_printf(ctrlr, "shutdown timeout\n");
1959 			break;
1960 		}
1961 		pause("nvmeshut", 1);
1962 	}
1963 }
1964 
1965 void
1966 nvme_ctrlr_submit_admin_request(struct nvme_controller *ctrlr,
1967     struct nvme_request *req)
1968 {
1969 	nvme_qpair_submit_request(&ctrlr->adminq, req);
1970 }
1971 
1972 void
1973 nvme_ctrlr_submit_io_request(struct nvme_controller *ctrlr,
1974     struct nvme_request *req)
1975 {
1976 	struct nvme_qpair       *qpair;
1977 	int32_t			ioq;
1978 
1979 	ioq = req->ioq == NVME_IOQ_DEFAULT ? QP(ctrlr, curcpu) : req->ioq;
1980 	qpair = &ctrlr->ioq[ioq];
1981 	nvme_qpair_submit_request(qpair, req);
1982 }
1983 
1984 device_t
1985 nvme_ctrlr_get_device(struct nvme_controller *ctrlr)
1986 {
1987 	return (ctrlr->dev);
1988 }
1989 
1990 const struct nvme_controller_data *
1991 nvme_ctrlr_get_data(struct nvme_controller *ctrlr)
1992 {
1993 	return (&ctrlr->cdata);
1994 }
1995 
1996 int
1997 nvme_ctrlr_suspend(struct nvme_controller *ctrlr)
1998 {
1999 	int to = hz;
2000 
2001 	/*
2002 	 * Can't touch failed controllers, so it's already suspended. User will
2003 	 * need to do an explicit reset to bring it back, if that's even
2004 	 * possible.
2005 	 */
2006 	if (ctrlr->is_failed)
2007 		return (0);
2008 
2009 	/*
2010 	 * We don't want the reset taskqueue running, since it does similar
2011 	 * things, so prevent it from running after we start. Wait for any reset
2012 	 * that may have been started to complete. The reset process we follow
2013 	 * will ensure that any new I/O will queue and be given to the hardware
2014 	 * after we resume (though there should be none).
2015 	 */
2016 	while (atomic_cmpset_32(&ctrlr->is_resetting, 0, 1) == 0 && to-- > 0)
2017 		pause("nvmesusp", 1);
2018 	if (to <= 0) {
2019 		nvme_printf(ctrlr,
2020 		    "Competing reset task didn't finish. Try again later.\n");
2021 		return (EWOULDBLOCK);
2022 	}
2023 
2024 	if (ctrlr->hmb_nchunks > 0)
2025 		nvme_ctrlr_hmb_enable(ctrlr, false, false);
2026 
2027 	/*
2028 	 * Per Section 7.6.2 of NVMe spec 1.4, to properly suspend, we need to
2029 	 * delete the hardware I/O queues, and then shutdown. This properly
2030 	 * flushes any metadata the drive may have stored so it can survive
2031 	 * having its power removed and prevents the unsafe shutdown count from
2032 	 * incriminating. Once we delete the qpairs, we have to disable them
2033 	 * before shutting down.
2034 	 */
2035 	nvme_ctrlr_delete_qpairs(ctrlr);
2036 	nvme_ctrlr_disable_qpairs(ctrlr);
2037 	nvme_ctrlr_shutdown(ctrlr);
2038 
2039 	return (0);
2040 }
2041 
2042 int
2043 nvme_ctrlr_resume(struct nvme_controller *ctrlr)
2044 {
2045 	/*
2046 	 * Can't touch failed controllers, so nothing to do to resume.
2047 	 */
2048 	if (ctrlr->is_failed)
2049 		return (0);
2050 
2051 	if (nvme_ctrlr_hw_reset(ctrlr) != 0)
2052 		goto fail;
2053 
2054 	/*
2055 	 * Now that we've reset the hardware, we can restart the controller. Any
2056 	 * I/O that was pending is requeued. Any admin commands are aborted with
2057 	 * an error. Once we've restarted, stop flagging the controller as being
2058 	 * in the reset phase.
2059 	 */
2060 	nvme_ctrlr_start(ctrlr, true);
2061 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
2062 
2063 	return (0);
2064 fail:
2065 	/*
2066 	 * Since we can't bring the controller out of reset, announce and fail
2067 	 * the controller. However, we have to return success for the resume
2068 	 * itself, due to questionable APIs.
2069 	 */
2070 	nvme_printf(ctrlr, "Failed to reset on resume, failing.\n");
2071 	nvme_ctrlr_fail(ctrlr, true);
2072 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
2073 	return (0);
2074 }
2075