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