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