xref: /freebsd/sys/dev/nvme/nvme_ctrlr.c (revision ead7e10308947fc5b9c6b96411f09d486d92833d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_cam.h"
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/buf.h>
37 #include <sys/bus.h>
38 #include <sys/conf.h>
39 #include <sys/ioccom.h>
40 #include <sys/proc.h>
41 #include <sys/smp.h>
42 #include <sys/uio.h>
43 #include <sys/sbuf.h>
44 #include <sys/endian.h>
45 #include <machine/stdarg.h>
46 #include <vm/vm.h>
47 
48 #include "nvme_private.h"
49 
50 #define B4_CHK_RDY_DELAY_MS	2300		/* work around controller bug */
51 
52 static void nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
53 						struct nvme_async_event_request *aer);
54 
55 static void
56 nvme_ctrlr_devctl_log(struct nvme_controller *ctrlr, const char *type, const char *msg, ...)
57 {
58 	struct sbuf sb;
59 	va_list ap;
60 	int error;
61 
62 	if (sbuf_new(&sb, NULL, 0, SBUF_AUTOEXTEND | SBUF_NOWAIT) == NULL)
63 		return;
64 	sbuf_printf(&sb, "%s: ", device_get_nameunit(ctrlr->dev));
65 	va_start(ap, msg);
66 	sbuf_vprintf(&sb, msg, ap);
67 	va_end(ap);
68 	error = sbuf_finish(&sb);
69 	if (error == 0)
70 		printf("%s\n", sbuf_data(&sb));
71 
72 	sbuf_clear(&sb);
73 	sbuf_printf(&sb, "name=\"%s\" reason=\"", device_get_nameunit(ctrlr->dev));
74 	va_start(ap, msg);
75 	sbuf_vprintf(&sb, msg, ap);
76 	va_end(ap);
77 	sbuf_printf(&sb, "\"");
78 	error = sbuf_finish(&sb);
79 	if (error == 0)
80 		devctl_notify("nvme", "controller", type, sbuf_data(&sb));
81 	sbuf_delete(&sb);
82 }
83 
84 static int
85 nvme_ctrlr_construct_admin_qpair(struct nvme_controller *ctrlr)
86 {
87 	struct nvme_qpair	*qpair;
88 	uint32_t		num_entries;
89 	int			error;
90 
91 	qpair = &ctrlr->adminq;
92 	qpair->id = 0;
93 	qpair->cpu = CPU_FFS(&cpuset_domain[ctrlr->domain]) - 1;
94 	qpair->domain = ctrlr->domain;
95 
96 	num_entries = NVME_ADMIN_ENTRIES;
97 	TUNABLE_INT_FETCH("hw.nvme.admin_entries", &num_entries);
98 	/*
99 	 * If admin_entries was overridden to an invalid value, revert it
100 	 *  back to our default value.
101 	 */
102 	if (num_entries < NVME_MIN_ADMIN_ENTRIES ||
103 	    num_entries > NVME_MAX_ADMIN_ENTRIES) {
104 		nvme_printf(ctrlr, "invalid hw.nvme.admin_entries=%d "
105 		    "specified\n", num_entries);
106 		num_entries = NVME_ADMIN_ENTRIES;
107 	}
108 
109 	/*
110 	 * The admin queue's max xfer size is treated differently than the
111 	 *  max I/O xfer size.  16KB is sufficient here - maybe even less?
112 	 */
113 	error = nvme_qpair_construct(qpair, num_entries, NVME_ADMIN_TRACKERS,
114 	     ctrlr);
115 	return (error);
116 }
117 
118 #define QP(ctrlr, c)	((c) * (ctrlr)->num_io_queues / mp_ncpus)
119 
120 static int
121 nvme_ctrlr_construct_io_qpairs(struct nvme_controller *ctrlr)
122 {
123 	struct nvme_qpair	*qpair;
124 	uint32_t		cap_lo;
125 	uint16_t		mqes;
126 	int			c, error, i, n;
127 	int			num_entries, num_trackers, max_entries;
128 
129 	/*
130 	 * NVMe spec sets a hard limit of 64K max entries, but devices may
131 	 * specify a smaller limit, so we need to check the MQES field in the
132 	 * capabilities register. We have to cap the number of entries to the
133 	 * current stride allows for in BAR 0/1, otherwise the remainder entries
134 	 * are inaccessable. MQES should reflect this, and this is just a
135 	 * fail-safe.
136 	 */
137 	max_entries =
138 	    (rman_get_size(ctrlr->resource) - nvme_mmio_offsetof(doorbell[0])) /
139 	    (1 << (ctrlr->dstrd + 1));
140 	num_entries = NVME_IO_ENTRIES;
141 	TUNABLE_INT_FETCH("hw.nvme.io_entries", &num_entries);
142 	cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
143 	mqes = NVME_CAP_LO_MQES(cap_lo);
144 	num_entries = min(num_entries, mqes + 1);
145 	num_entries = min(num_entries, max_entries);
146 
147 	num_trackers = NVME_IO_TRACKERS;
148 	TUNABLE_INT_FETCH("hw.nvme.io_trackers", &num_trackers);
149 
150 	num_trackers = max(num_trackers, NVME_MIN_IO_TRACKERS);
151 	num_trackers = min(num_trackers, NVME_MAX_IO_TRACKERS);
152 	/*
153 	 * No need to have more trackers than entries in the submit queue.  Note
154 	 * also that for a queue size of N, we can only have (N-1) commands
155 	 * outstanding, hence the "-1" here.
156 	 */
157 	num_trackers = min(num_trackers, (num_entries-1));
158 
159 	/*
160 	 * Our best estimate for the maximum number of I/Os that we should
161 	 * normally have in flight at one time. This should be viewed as a hint,
162 	 * not a hard limit and will need to be revisited when the upper layers
163 	 * of the storage system grows multi-queue support.
164 	 */
165 	ctrlr->max_hw_pend_io = num_trackers * ctrlr->num_io_queues * 3 / 4;
166 
167 	ctrlr->ioq = malloc(ctrlr->num_io_queues * sizeof(struct nvme_qpair),
168 	    M_NVME, M_ZERO | M_WAITOK);
169 
170 	for (i = c = n = 0; i < ctrlr->num_io_queues; i++, c += n) {
171 		qpair = &ctrlr->ioq[i];
172 
173 		/*
174 		 * Admin queue has ID=0. IO queues start at ID=1 -
175 		 *  hence the 'i+1' here.
176 		 */
177 		qpair->id = i + 1;
178 		if (ctrlr->num_io_queues > 1) {
179 			/* Find number of CPUs served by this queue. */
180 			for (n = 1; QP(ctrlr, c + n) == i; n++)
181 				;
182 			/* Shuffle multiple NVMe devices between CPUs. */
183 			qpair->cpu = c + (device_get_unit(ctrlr->dev)+n/2) % n;
184 			qpair->domain = pcpu_find(qpair->cpu)->pc_domain;
185 		} else {
186 			qpair->cpu = CPU_FFS(&cpuset_domain[ctrlr->domain]) - 1;
187 			qpair->domain = ctrlr->domain;
188 		}
189 
190 		/*
191 		 * For I/O queues, use the controller-wide max_xfer_size
192 		 *  calculated in nvme_attach().
193 		 */
194 		error = nvme_qpair_construct(qpair, num_entries, num_trackers,
195 		    ctrlr);
196 		if (error)
197 			return (error);
198 
199 		/*
200 		 * Do not bother binding interrupts if we only have one I/O
201 		 *  interrupt thread for this controller.
202 		 */
203 		if (ctrlr->num_io_queues > 1)
204 			bus_bind_intr(ctrlr->dev, qpair->res, qpair->cpu);
205 	}
206 
207 	return (0);
208 }
209 
210 static void
211 nvme_ctrlr_fail(struct nvme_controller *ctrlr)
212 {
213 	int i;
214 
215 	ctrlr->is_failed = true;
216 	nvme_admin_qpair_disable(&ctrlr->adminq);
217 	nvme_qpair_fail(&ctrlr->adminq);
218 	if (ctrlr->ioq != NULL) {
219 		for (i = 0; i < ctrlr->num_io_queues; i++) {
220 			nvme_io_qpair_disable(&ctrlr->ioq[i]);
221 			nvme_qpair_fail(&ctrlr->ioq[i]);
222 		}
223 	}
224 	nvme_notify_fail_consumers(ctrlr);
225 }
226 
227 void
228 nvme_ctrlr_post_failed_request(struct nvme_controller *ctrlr,
229     struct nvme_request *req)
230 {
231 
232 	mtx_lock(&ctrlr->lock);
233 	STAILQ_INSERT_TAIL(&ctrlr->fail_req, req, stailq);
234 	mtx_unlock(&ctrlr->lock);
235 	taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->fail_req_task);
236 }
237 
238 static void
239 nvme_ctrlr_fail_req_task(void *arg, int pending)
240 {
241 	struct nvme_controller	*ctrlr = arg;
242 	struct nvme_request	*req;
243 
244 	mtx_lock(&ctrlr->lock);
245 	while ((req = STAILQ_FIRST(&ctrlr->fail_req)) != NULL) {
246 		STAILQ_REMOVE_HEAD(&ctrlr->fail_req, stailq);
247 		mtx_unlock(&ctrlr->lock);
248 		nvme_qpair_manual_complete_request(req->qpair, req,
249 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST);
250 		mtx_lock(&ctrlr->lock);
251 	}
252 	mtx_unlock(&ctrlr->lock);
253 }
254 
255 static int
256 nvme_ctrlr_wait_for_ready(struct nvme_controller *ctrlr, int desired_val)
257 {
258 	int ms_waited;
259 	uint32_t csts;
260 
261 	ms_waited = 0;
262 	while (1) {
263 		csts = nvme_mmio_read_4(ctrlr, csts);
264 		if (csts == 0xffffffff)		/* Hot unplug. */
265 			return (ENXIO);
266 		if (((csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK)
267 		    == desired_val)
268 			break;
269 		if (ms_waited++ > ctrlr->ready_timeout_in_ms) {
270 			nvme_printf(ctrlr, "controller ready did not become %d "
271 			    "within %d ms\n", desired_val, ctrlr->ready_timeout_in_ms);
272 			return (ENXIO);
273 		}
274 		DELAY(1000);
275 	}
276 
277 	return (0);
278 }
279 
280 static int
281 nvme_ctrlr_disable(struct nvme_controller *ctrlr)
282 {
283 	uint32_t cc;
284 	uint32_t csts;
285 	uint8_t  en, rdy;
286 	int err;
287 
288 	cc = nvme_mmio_read_4(ctrlr, cc);
289 	csts = nvme_mmio_read_4(ctrlr, csts);
290 
291 	en = (cc >> NVME_CC_REG_EN_SHIFT) & NVME_CC_REG_EN_MASK;
292 	rdy = (csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK;
293 
294 	/*
295 	 * Per 3.1.5 in NVME 1.3 spec, transitioning CC.EN from 0 to 1
296 	 * when CSTS.RDY is 1 or transitioning CC.EN from 1 to 0 when
297 	 * CSTS.RDY is 0 "has undefined results" So make sure that CSTS.RDY
298 	 * isn't the desired value. Short circuit if we're already disabled.
299 	 */
300 	if (en == 1) {
301 		if (rdy == 0) {
302 			/* EN == 1, wait for  RDY == 1 or fail */
303 			err = nvme_ctrlr_wait_for_ready(ctrlr, 1);
304 			if (err != 0)
305 				return (err);
306 		}
307 	} else {
308 		/* EN == 0 already wait for RDY == 0 */
309 		if (rdy == 0)
310 			return (0);
311 		else
312 			return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
313 	}
314 
315 	cc &= ~NVME_CC_REG_EN_MASK;
316 	nvme_mmio_write_4(ctrlr, cc, cc);
317 	/*
318 	 * Some drives have issues with accessing the mmio after we
319 	 * disable, so delay for a bit after we write the bit to
320 	 * cope with these issues.
321 	 */
322 	if (ctrlr->quirks & QUIRK_DELAY_B4_CHK_RDY)
323 		pause("nvmeR", B4_CHK_RDY_DELAY_MS * hz / 1000);
324 	return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
325 }
326 
327 static int
328 nvme_ctrlr_enable(struct nvme_controller *ctrlr)
329 {
330 	uint32_t	cc;
331 	uint32_t	csts;
332 	uint32_t	aqa;
333 	uint32_t	qsize;
334 	uint8_t		en, rdy;
335 	int		err;
336 
337 	cc = nvme_mmio_read_4(ctrlr, cc);
338 	csts = nvme_mmio_read_4(ctrlr, csts);
339 
340 	en = (cc >> NVME_CC_REG_EN_SHIFT) & NVME_CC_REG_EN_MASK;
341 	rdy = (csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK;
342 
343 	/*
344 	 * See note in nvme_ctrlr_disable. Short circuit if we're already enabled.
345 	 */
346 	if (en == 1) {
347 		if (rdy == 1)
348 			return (0);
349 		else
350 			return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
351 	} else {
352 		/* EN == 0 already wait for RDY == 0 or fail */
353 		err = nvme_ctrlr_wait_for_ready(ctrlr, 0);
354 		if (err != 0)
355 			return (err);
356 	}
357 
358 	nvme_mmio_write_8(ctrlr, asq, ctrlr->adminq.cmd_bus_addr);
359 	DELAY(5000);
360 	nvme_mmio_write_8(ctrlr, acq, ctrlr->adminq.cpl_bus_addr);
361 	DELAY(5000);
362 
363 	/* acqs and asqs are 0-based. */
364 	qsize = ctrlr->adminq.num_entries - 1;
365 
366 	aqa = 0;
367 	aqa = (qsize & NVME_AQA_REG_ACQS_MASK) << NVME_AQA_REG_ACQS_SHIFT;
368 	aqa |= (qsize & NVME_AQA_REG_ASQS_MASK) << NVME_AQA_REG_ASQS_SHIFT;
369 	nvme_mmio_write_4(ctrlr, aqa, aqa);
370 	DELAY(5000);
371 
372 	/* Initialization values for CC */
373 	cc = 0;
374 	cc |= 1 << NVME_CC_REG_EN_SHIFT;
375 	cc |= 0 << NVME_CC_REG_CSS_SHIFT;
376 	cc |= 0 << NVME_CC_REG_AMS_SHIFT;
377 	cc |= 0 << NVME_CC_REG_SHN_SHIFT;
378 	cc |= 6 << NVME_CC_REG_IOSQES_SHIFT; /* SQ entry size == 64 == 2^6 */
379 	cc |= 4 << NVME_CC_REG_IOCQES_SHIFT; /* CQ entry size == 16 == 2^4 */
380 
381 	/* This evaluates to 0, which is according to spec. */
382 	cc |= (PAGE_SIZE >> 13) << NVME_CC_REG_MPS_SHIFT;
383 
384 	nvme_mmio_write_4(ctrlr, cc, cc);
385 
386 	return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
387 }
388 
389 static void
390 nvme_ctrlr_disable_qpairs(struct nvme_controller *ctrlr)
391 {
392 	int i;
393 
394 	nvme_admin_qpair_disable(&ctrlr->adminq);
395 	/*
396 	 * I/O queues are not allocated before the initial HW
397 	 *  reset, so do not try to disable them.  Use is_initialized
398 	 *  to determine if this is the initial HW reset.
399 	 */
400 	if (ctrlr->is_initialized) {
401 		for (i = 0; i < ctrlr->num_io_queues; i++)
402 			nvme_io_qpair_disable(&ctrlr->ioq[i]);
403 	}
404 }
405 
406 int
407 nvme_ctrlr_hw_reset(struct nvme_controller *ctrlr)
408 {
409 	int err;
410 
411 	nvme_ctrlr_disable_qpairs(ctrlr);
412 
413 	DELAY(100*1000);
414 
415 	err = nvme_ctrlr_disable(ctrlr);
416 	if (err != 0)
417 		return err;
418 	return (nvme_ctrlr_enable(ctrlr));
419 }
420 
421 void
422 nvme_ctrlr_reset(struct nvme_controller *ctrlr)
423 {
424 	int cmpset;
425 
426 	cmpset = atomic_cmpset_32(&ctrlr->is_resetting, 0, 1);
427 
428 	if (cmpset == 0 || ctrlr->is_failed)
429 		/*
430 		 * Controller is already resetting or has failed.  Return
431 		 *  immediately since there is no need to kick off another
432 		 *  reset in these cases.
433 		 */
434 		return;
435 
436 	taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->reset_task);
437 }
438 
439 static int
440 nvme_ctrlr_identify(struct nvme_controller *ctrlr)
441 {
442 	struct nvme_completion_poll_status	status;
443 
444 	status.done = 0;
445 	nvme_ctrlr_cmd_identify_controller(ctrlr, &ctrlr->cdata,
446 	    nvme_completion_poll_cb, &status);
447 	nvme_completion_poll(&status);
448 	if (nvme_completion_is_error(&status.cpl)) {
449 		nvme_printf(ctrlr, "nvme_identify_controller failed!\n");
450 		return (ENXIO);
451 	}
452 
453 	/* Convert data to host endian */
454 	nvme_controller_data_swapbytes(&ctrlr->cdata);
455 
456 	/*
457 	 * Use MDTS to ensure our default max_xfer_size doesn't exceed what the
458 	 *  controller supports.
459 	 */
460 	if (ctrlr->cdata.mdts > 0)
461 		ctrlr->max_xfer_size = min(ctrlr->max_xfer_size,
462 		    ctrlr->min_page_size * (1 << (ctrlr->cdata.mdts)));
463 
464 	return (0);
465 }
466 
467 static int
468 nvme_ctrlr_set_num_qpairs(struct nvme_controller *ctrlr)
469 {
470 	struct nvme_completion_poll_status	status;
471 	int					cq_allocated, sq_allocated;
472 
473 	status.done = 0;
474 	nvme_ctrlr_cmd_set_num_queues(ctrlr, ctrlr->num_io_queues,
475 	    nvme_completion_poll_cb, &status);
476 	nvme_completion_poll(&status);
477 	if (nvme_completion_is_error(&status.cpl)) {
478 		nvme_printf(ctrlr, "nvme_ctrlr_set_num_qpairs failed!\n");
479 		return (ENXIO);
480 	}
481 
482 	/*
483 	 * Data in cdw0 is 0-based.
484 	 * Lower 16-bits indicate number of submission queues allocated.
485 	 * Upper 16-bits indicate number of completion queues allocated.
486 	 */
487 	sq_allocated = (status.cpl.cdw0 & 0xFFFF) + 1;
488 	cq_allocated = (status.cpl.cdw0 >> 16) + 1;
489 
490 	/*
491 	 * Controller may allocate more queues than we requested,
492 	 *  so use the minimum of the number requested and what was
493 	 *  actually allocated.
494 	 */
495 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, sq_allocated);
496 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, cq_allocated);
497 	if (ctrlr->num_io_queues > vm_ndomains)
498 		ctrlr->num_io_queues -= ctrlr->num_io_queues % vm_ndomains;
499 
500 	return (0);
501 }
502 
503 static int
504 nvme_ctrlr_create_qpairs(struct nvme_controller *ctrlr)
505 {
506 	struct nvme_completion_poll_status	status;
507 	struct nvme_qpair			*qpair;
508 	int					i;
509 
510 	for (i = 0; i < ctrlr->num_io_queues; i++) {
511 		qpair = &ctrlr->ioq[i];
512 
513 		status.done = 0;
514 		nvme_ctrlr_cmd_create_io_cq(ctrlr, qpair,
515 		    nvme_completion_poll_cb, &status);
516 		nvme_completion_poll(&status);
517 		if (nvme_completion_is_error(&status.cpl)) {
518 			nvme_printf(ctrlr, "nvme_create_io_cq failed!\n");
519 			return (ENXIO);
520 		}
521 
522 		status.done = 0;
523 		nvme_ctrlr_cmd_create_io_sq(ctrlr, qpair,
524 		    nvme_completion_poll_cb, &status);
525 		nvme_completion_poll(&status);
526 		if (nvme_completion_is_error(&status.cpl)) {
527 			nvme_printf(ctrlr, "nvme_create_io_sq failed!\n");
528 			return (ENXIO);
529 		}
530 	}
531 
532 	return (0);
533 }
534 
535 static int
536 nvme_ctrlr_delete_qpairs(struct nvme_controller *ctrlr)
537 {
538 	struct nvme_completion_poll_status	status;
539 	struct nvme_qpair			*qpair;
540 
541 	for (int i = 0; i < ctrlr->num_io_queues; i++) {
542 		qpair = &ctrlr->ioq[i];
543 
544 		status.done = 0;
545 		nvme_ctrlr_cmd_delete_io_sq(ctrlr, qpair,
546 		    nvme_completion_poll_cb, &status);
547 		nvme_completion_poll(&status);
548 		if (nvme_completion_is_error(&status.cpl)) {
549 			nvme_printf(ctrlr, "nvme_destroy_io_sq failed!\n");
550 			return (ENXIO);
551 		}
552 
553 		status.done = 0;
554 		nvme_ctrlr_cmd_delete_io_cq(ctrlr, qpair,
555 		    nvme_completion_poll_cb, &status);
556 		nvme_completion_poll(&status);
557 		if (nvme_completion_is_error(&status.cpl)) {
558 			nvme_printf(ctrlr, "nvme_destroy_io_cq failed!\n");
559 			return (ENXIO);
560 		}
561 	}
562 
563 	return (0);
564 }
565 
566 static int
567 nvme_ctrlr_construct_namespaces(struct nvme_controller *ctrlr)
568 {
569 	struct nvme_namespace	*ns;
570 	uint32_t 		i;
571 
572 	for (i = 0; i < min(ctrlr->cdata.nn, NVME_MAX_NAMESPACES); i++) {
573 		ns = &ctrlr->ns[i];
574 		nvme_ns_construct(ns, i+1, ctrlr);
575 	}
576 
577 	return (0);
578 }
579 
580 static bool
581 is_log_page_id_valid(uint8_t page_id)
582 {
583 
584 	switch (page_id) {
585 	case NVME_LOG_ERROR:
586 	case NVME_LOG_HEALTH_INFORMATION:
587 	case NVME_LOG_FIRMWARE_SLOT:
588 	case NVME_LOG_CHANGED_NAMESPACE:
589 	case NVME_LOG_COMMAND_EFFECT:
590 	case NVME_LOG_RES_NOTIFICATION:
591 	case NVME_LOG_SANITIZE_STATUS:
592 		return (true);
593 	}
594 
595 	return (false);
596 }
597 
598 static uint32_t
599 nvme_ctrlr_get_log_page_size(struct nvme_controller *ctrlr, uint8_t page_id)
600 {
601 	uint32_t	log_page_size;
602 
603 	switch (page_id) {
604 	case NVME_LOG_ERROR:
605 		log_page_size = min(
606 		    sizeof(struct nvme_error_information_entry) *
607 		    (ctrlr->cdata.elpe + 1), NVME_MAX_AER_LOG_SIZE);
608 		break;
609 	case NVME_LOG_HEALTH_INFORMATION:
610 		log_page_size = sizeof(struct nvme_health_information_page);
611 		break;
612 	case NVME_LOG_FIRMWARE_SLOT:
613 		log_page_size = sizeof(struct nvme_firmware_page);
614 		break;
615 	case NVME_LOG_CHANGED_NAMESPACE:
616 		log_page_size = sizeof(struct nvme_ns_list);
617 		break;
618 	case NVME_LOG_COMMAND_EFFECT:
619 		log_page_size = sizeof(struct nvme_command_effects_page);
620 		break;
621 	case NVME_LOG_RES_NOTIFICATION:
622 		log_page_size = sizeof(struct nvme_res_notification_page);
623 		break;
624 	case NVME_LOG_SANITIZE_STATUS:
625 		log_page_size = sizeof(struct nvme_sanitize_status_page);
626 		break;
627 	default:
628 		log_page_size = 0;
629 		break;
630 	}
631 
632 	return (log_page_size);
633 }
634 
635 static void
636 nvme_ctrlr_log_critical_warnings(struct nvme_controller *ctrlr,
637     uint8_t state)
638 {
639 
640 	if (state & NVME_CRIT_WARN_ST_AVAILABLE_SPARE)
641 		nvme_ctrlr_devctl_log(ctrlr, "critical",
642 		    "available spare space below threshold");
643 
644 	if (state & NVME_CRIT_WARN_ST_TEMPERATURE)
645 		nvme_ctrlr_devctl_log(ctrlr, "critical",
646 		    "temperature above threshold");
647 
648 	if (state & NVME_CRIT_WARN_ST_DEVICE_RELIABILITY)
649 		nvme_ctrlr_devctl_log(ctrlr, "critical",
650 		    "device reliability degraded");
651 
652 	if (state & NVME_CRIT_WARN_ST_READ_ONLY)
653 		nvme_ctrlr_devctl_log(ctrlr, "critical",
654 		    "media placed in read only mode");
655 
656 	if (state & NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP)
657 		nvme_ctrlr_devctl_log(ctrlr, "critical",
658 		    "volatile memory backup device failed");
659 
660 	if (state & NVME_CRIT_WARN_ST_RESERVED_MASK)
661 		nvme_ctrlr_devctl_log(ctrlr, "critical",
662 		    "unknown critical warning(s): state = 0x%02x", state);
663 }
664 
665 static void
666 nvme_ctrlr_async_event_log_page_cb(void *arg, const struct nvme_completion *cpl)
667 {
668 	struct nvme_async_event_request		*aer = arg;
669 	struct nvme_health_information_page	*health_info;
670 	struct nvme_ns_list			*nsl;
671 	struct nvme_error_information_entry	*err;
672 	int i;
673 
674 	/*
675 	 * If the log page fetch for some reason completed with an error,
676 	 *  don't pass log page data to the consumers.  In practice, this case
677 	 *  should never happen.
678 	 */
679 	if (nvme_completion_is_error(cpl))
680 		nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
681 		    aer->log_page_id, NULL, 0);
682 	else {
683 		/* Convert data to host endian */
684 		switch (aer->log_page_id) {
685 		case NVME_LOG_ERROR:
686 			err = (struct nvme_error_information_entry *)aer->log_page_buffer;
687 			for (i = 0; i < (aer->ctrlr->cdata.elpe + 1); i++)
688 				nvme_error_information_entry_swapbytes(err++);
689 			break;
690 		case NVME_LOG_HEALTH_INFORMATION:
691 			nvme_health_information_page_swapbytes(
692 			    (struct nvme_health_information_page *)aer->log_page_buffer);
693 			break;
694 		case NVME_LOG_FIRMWARE_SLOT:
695 			nvme_firmware_page_swapbytes(
696 			    (struct nvme_firmware_page *)aer->log_page_buffer);
697 			break;
698 		case NVME_LOG_CHANGED_NAMESPACE:
699 			nvme_ns_list_swapbytes(
700 			    (struct nvme_ns_list *)aer->log_page_buffer);
701 			break;
702 		case NVME_LOG_COMMAND_EFFECT:
703 			nvme_command_effects_page_swapbytes(
704 			    (struct nvme_command_effects_page *)aer->log_page_buffer);
705 			break;
706 		case NVME_LOG_RES_NOTIFICATION:
707 			nvme_res_notification_page_swapbytes(
708 			    (struct nvme_res_notification_page *)aer->log_page_buffer);
709 			break;
710 		case NVME_LOG_SANITIZE_STATUS:
711 			nvme_sanitize_status_page_swapbytes(
712 			    (struct nvme_sanitize_status_page *)aer->log_page_buffer);
713 			break;
714 		case INTEL_LOG_TEMP_STATS:
715 			intel_log_temp_stats_swapbytes(
716 			    (struct intel_log_temp_stats *)aer->log_page_buffer);
717 			break;
718 		default:
719 			break;
720 		}
721 
722 		if (aer->log_page_id == NVME_LOG_HEALTH_INFORMATION) {
723 			health_info = (struct nvme_health_information_page *)
724 			    aer->log_page_buffer;
725 			nvme_ctrlr_log_critical_warnings(aer->ctrlr,
726 			    health_info->critical_warning);
727 			/*
728 			 * Critical warnings reported through the
729 			 *  SMART/health log page are persistent, so
730 			 *  clear the associated bits in the async event
731 			 *  config so that we do not receive repeated
732 			 *  notifications for the same event.
733 			 */
734 			aer->ctrlr->async_event_config &=
735 			    ~health_info->critical_warning;
736 			nvme_ctrlr_cmd_set_async_event_config(aer->ctrlr,
737 			    aer->ctrlr->async_event_config, NULL, NULL);
738 		} else if (aer->log_page_id == NVME_LOG_CHANGED_NAMESPACE &&
739 		    !nvme_use_nvd) {
740 			nsl = (struct nvme_ns_list *)aer->log_page_buffer;
741 			for (i = 0; i < nitems(nsl->ns) && nsl->ns[i] != 0; i++) {
742 				if (nsl->ns[i] > NVME_MAX_NAMESPACES)
743 					break;
744 				nvme_notify_ns(aer->ctrlr, nsl->ns[i]);
745 			}
746 		}
747 
748 
749 		/*
750 		 * Pass the cpl data from the original async event completion,
751 		 *  not the log page fetch.
752 		 */
753 		nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
754 		    aer->log_page_id, aer->log_page_buffer, aer->log_page_size);
755 	}
756 
757 	/*
758 	 * Repost another asynchronous event request to replace the one
759 	 *  that just completed.
760 	 */
761 	nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
762 }
763 
764 static void
765 nvme_ctrlr_async_event_cb(void *arg, const struct nvme_completion *cpl)
766 {
767 	struct nvme_async_event_request	*aer = arg;
768 
769 	if (nvme_completion_is_error(cpl)) {
770 		/*
771 		 *  Do not retry failed async event requests.  This avoids
772 		 *  infinite loops where a new async event request is submitted
773 		 *  to replace the one just failed, only to fail again and
774 		 *  perpetuate the loop.
775 		 */
776 		return;
777 	}
778 
779 	/* Associated log page is in bits 23:16 of completion entry dw0. */
780 	aer->log_page_id = (cpl->cdw0 & 0xFF0000) >> 16;
781 
782 	nvme_printf(aer->ctrlr, "async event occurred (type 0x%x, info 0x%02x,"
783 	    " page 0x%02x)\n", (cpl->cdw0 & 0x07), (cpl->cdw0 & 0xFF00) >> 8,
784 	    aer->log_page_id);
785 
786 	if (is_log_page_id_valid(aer->log_page_id)) {
787 		aer->log_page_size = nvme_ctrlr_get_log_page_size(aer->ctrlr,
788 		    aer->log_page_id);
789 		memcpy(&aer->cpl, cpl, sizeof(*cpl));
790 		nvme_ctrlr_cmd_get_log_page(aer->ctrlr, aer->log_page_id,
791 		    NVME_GLOBAL_NAMESPACE_TAG, aer->log_page_buffer,
792 		    aer->log_page_size, nvme_ctrlr_async_event_log_page_cb,
793 		    aer);
794 		/* Wait to notify consumers until after log page is fetched. */
795 	} else {
796 		nvme_notify_async_consumers(aer->ctrlr, cpl, aer->log_page_id,
797 		    NULL, 0);
798 
799 		/*
800 		 * Repost another asynchronous event request to replace the one
801 		 *  that just completed.
802 		 */
803 		nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
804 	}
805 }
806 
807 static void
808 nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
809     struct nvme_async_event_request *aer)
810 {
811 	struct nvme_request *req;
812 
813 	aer->ctrlr = ctrlr;
814 	req = nvme_allocate_request_null(nvme_ctrlr_async_event_cb, aer);
815 	aer->req = req;
816 
817 	/*
818 	 * Disable timeout here, since asynchronous event requests should by
819 	 *  nature never be timed out.
820 	 */
821 	req->timeout = false;
822 	req->cmd.opc = NVME_OPC_ASYNC_EVENT_REQUEST;
823 	nvme_ctrlr_submit_admin_request(ctrlr, req);
824 }
825 
826 static void
827 nvme_ctrlr_configure_aer(struct nvme_controller *ctrlr)
828 {
829 	struct nvme_completion_poll_status	status;
830 	struct nvme_async_event_request		*aer;
831 	uint32_t				i;
832 
833 	ctrlr->async_event_config = NVME_CRIT_WARN_ST_AVAILABLE_SPARE |
834 	    NVME_CRIT_WARN_ST_DEVICE_RELIABILITY |
835 	    NVME_CRIT_WARN_ST_READ_ONLY |
836 	    NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP;
837 	if (ctrlr->cdata.ver >= NVME_REV(1, 2))
838 		ctrlr->async_event_config |= 0x300;
839 
840 	status.done = 0;
841 	nvme_ctrlr_cmd_get_feature(ctrlr, NVME_FEAT_TEMPERATURE_THRESHOLD,
842 	    0, NULL, 0, nvme_completion_poll_cb, &status);
843 	nvme_completion_poll(&status);
844 	if (nvme_completion_is_error(&status.cpl) ||
845 	    (status.cpl.cdw0 & 0xFFFF) == 0xFFFF ||
846 	    (status.cpl.cdw0 & 0xFFFF) == 0x0000) {
847 		nvme_printf(ctrlr, "temperature threshold not supported\n");
848 	} else
849 		ctrlr->async_event_config |= NVME_CRIT_WARN_ST_TEMPERATURE;
850 
851 	nvme_ctrlr_cmd_set_async_event_config(ctrlr,
852 	    ctrlr->async_event_config, NULL, NULL);
853 
854 	/* aerl is a zero-based value, so we need to add 1 here. */
855 	ctrlr->num_aers = min(NVME_MAX_ASYNC_EVENTS, (ctrlr->cdata.aerl+1));
856 
857 	for (i = 0; i < ctrlr->num_aers; i++) {
858 		aer = &ctrlr->aer[i];
859 		nvme_ctrlr_construct_and_submit_aer(ctrlr, aer);
860 	}
861 }
862 
863 static void
864 nvme_ctrlr_configure_int_coalescing(struct nvme_controller *ctrlr)
865 {
866 
867 	ctrlr->int_coal_time = 0;
868 	TUNABLE_INT_FETCH("hw.nvme.int_coal_time",
869 	    &ctrlr->int_coal_time);
870 
871 	ctrlr->int_coal_threshold = 0;
872 	TUNABLE_INT_FETCH("hw.nvme.int_coal_threshold",
873 	    &ctrlr->int_coal_threshold);
874 
875 	nvme_ctrlr_cmd_set_interrupt_coalescing(ctrlr, ctrlr->int_coal_time,
876 	    ctrlr->int_coal_threshold, NULL, NULL);
877 }
878 
879 static void
880 nvme_ctrlr_hmb_free(struct nvme_controller *ctrlr)
881 {
882 	struct nvme_hmb_chunk *hmbc;
883 	int i;
884 
885 	if (ctrlr->hmb_desc_paddr) {
886 		bus_dmamap_unload(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map);
887 		bus_dmamem_free(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_vaddr,
888 		    ctrlr->hmb_desc_map);
889 		ctrlr->hmb_desc_paddr = 0;
890 	}
891 	if (ctrlr->hmb_desc_tag) {
892 		bus_dma_tag_destroy(ctrlr->hmb_desc_tag);
893 		ctrlr->hmb_desc_tag = NULL;
894 	}
895 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
896 		hmbc = &ctrlr->hmb_chunks[i];
897 		bus_dmamap_unload(ctrlr->hmb_tag, hmbc->hmbc_map);
898 		bus_dmamem_free(ctrlr->hmb_tag, hmbc->hmbc_vaddr,
899 		    hmbc->hmbc_map);
900 	}
901 	ctrlr->hmb_nchunks = 0;
902 	if (ctrlr->hmb_tag) {
903 		bus_dma_tag_destroy(ctrlr->hmb_tag);
904 		ctrlr->hmb_tag = NULL;
905 	}
906 	if (ctrlr->hmb_chunks) {
907 		free(ctrlr->hmb_chunks, M_NVME);
908 		ctrlr->hmb_chunks = NULL;
909 	}
910 }
911 
912 static void
913 nvme_ctrlr_hmb_alloc(struct nvme_controller *ctrlr)
914 {
915 	struct nvme_hmb_chunk *hmbc;
916 	size_t pref, min, minc, size;
917 	int err, i;
918 	uint64_t max;
919 
920 	/* Limit HMB to 5% of RAM size per device by default. */
921 	max = (uint64_t)physmem * PAGE_SIZE / 20;
922 	TUNABLE_UINT64_FETCH("hw.nvme.hmb_max", &max);
923 
924 	min = (long long unsigned)ctrlr->cdata.hmmin * 4096;
925 	if (max == 0 || max < min)
926 		return;
927 	pref = MIN((long long unsigned)ctrlr->cdata.hmpre * 4096, max);
928 	minc = MAX(ctrlr->cdata.hmminds * 4096, PAGE_SIZE);
929 	if (min > 0 && ctrlr->cdata.hmmaxd > 0)
930 		minc = MAX(minc, min / ctrlr->cdata.hmmaxd);
931 	ctrlr->hmb_chunk = pref;
932 
933 again:
934 	ctrlr->hmb_chunk = roundup2(ctrlr->hmb_chunk, PAGE_SIZE);
935 	ctrlr->hmb_nchunks = howmany(pref, ctrlr->hmb_chunk);
936 	if (ctrlr->cdata.hmmaxd > 0 && ctrlr->hmb_nchunks > ctrlr->cdata.hmmaxd)
937 		ctrlr->hmb_nchunks = ctrlr->cdata.hmmaxd;
938 	ctrlr->hmb_chunks = malloc(sizeof(struct nvme_hmb_chunk) *
939 	    ctrlr->hmb_nchunks, M_NVME, M_WAITOK);
940 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
941 	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
942 	    ctrlr->hmb_chunk, 1, ctrlr->hmb_chunk, 0, NULL, NULL, &ctrlr->hmb_tag);
943 	if (err != 0) {
944 		nvme_printf(ctrlr, "HMB tag create failed %d\n", err);
945 		nvme_ctrlr_hmb_free(ctrlr);
946 		return;
947 	}
948 
949 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
950 		hmbc = &ctrlr->hmb_chunks[i];
951 		if (bus_dmamem_alloc(ctrlr->hmb_tag,
952 		    (void **)&hmbc->hmbc_vaddr, BUS_DMA_NOWAIT,
953 		    &hmbc->hmbc_map)) {
954 			nvme_printf(ctrlr, "failed to alloc HMB\n");
955 			break;
956 		}
957 		if (bus_dmamap_load(ctrlr->hmb_tag, hmbc->hmbc_map,
958 		    hmbc->hmbc_vaddr, ctrlr->hmb_chunk, nvme_single_map,
959 		    &hmbc->hmbc_paddr, BUS_DMA_NOWAIT) != 0) {
960 			bus_dmamem_free(ctrlr->hmb_tag, hmbc->hmbc_vaddr,
961 			    hmbc->hmbc_map);
962 			nvme_printf(ctrlr, "failed to load HMB\n");
963 			break;
964 		}
965 		bus_dmamap_sync(ctrlr->hmb_tag, hmbc->hmbc_map,
966 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
967 	}
968 
969 	if (i < ctrlr->hmb_nchunks && i * ctrlr->hmb_chunk < min &&
970 	    ctrlr->hmb_chunk / 2 >= minc) {
971 		ctrlr->hmb_nchunks = i;
972 		nvme_ctrlr_hmb_free(ctrlr);
973 		ctrlr->hmb_chunk /= 2;
974 		goto again;
975 	}
976 	ctrlr->hmb_nchunks = i;
977 	if (ctrlr->hmb_nchunks * ctrlr->hmb_chunk < min) {
978 		nvme_ctrlr_hmb_free(ctrlr);
979 		return;
980 	}
981 
982 	size = sizeof(struct nvme_hmb_desc) * ctrlr->hmb_nchunks;
983 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
984 	    16, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
985 	    size, 1, size, 0, NULL, NULL, &ctrlr->hmb_desc_tag);
986 	if (err != 0) {
987 		nvme_printf(ctrlr, "HMB desc tag create failed %d\n", err);
988 		nvme_ctrlr_hmb_free(ctrlr);
989 		return;
990 	}
991 	if (bus_dmamem_alloc(ctrlr->hmb_desc_tag,
992 	    (void **)&ctrlr->hmb_desc_vaddr, BUS_DMA_WAITOK,
993 	    &ctrlr->hmb_desc_map)) {
994 		nvme_printf(ctrlr, "failed to alloc HMB desc\n");
995 		nvme_ctrlr_hmb_free(ctrlr);
996 		return;
997 	}
998 	if (bus_dmamap_load(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map,
999 	    ctrlr->hmb_desc_vaddr, size, nvme_single_map,
1000 	    &ctrlr->hmb_desc_paddr, BUS_DMA_NOWAIT) != 0) {
1001 		bus_dmamem_free(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_vaddr,
1002 		    ctrlr->hmb_desc_map);
1003 		nvme_printf(ctrlr, "failed to load HMB desc\n");
1004 		nvme_ctrlr_hmb_free(ctrlr);
1005 		return;
1006 	}
1007 
1008 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
1009 		ctrlr->hmb_desc_vaddr[i].addr =
1010 		    htole64(ctrlr->hmb_chunks[i].hmbc_paddr);
1011 		ctrlr->hmb_desc_vaddr[i].size = htole32(ctrlr->hmb_chunk / 4096);
1012 	}
1013 	bus_dmamap_sync(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map,
1014 	    BUS_DMASYNC_PREWRITE);
1015 
1016 	nvme_printf(ctrlr, "Allocated %lluMB host memory buffer\n",
1017 	    (long long unsigned)ctrlr->hmb_nchunks * ctrlr->hmb_chunk
1018 	    / 1024 / 1024);
1019 }
1020 
1021 static void
1022 nvme_ctrlr_hmb_enable(struct nvme_controller *ctrlr, bool enable, bool memret)
1023 {
1024 	struct nvme_completion_poll_status	status;
1025 	uint32_t cdw11;
1026 
1027 	cdw11 = 0;
1028 	if (enable)
1029 		cdw11 |= 1;
1030 	if (memret)
1031 		cdw11 |= 2;
1032 	status.done = 0;
1033 	nvme_ctrlr_cmd_set_feature(ctrlr, NVME_FEAT_HOST_MEMORY_BUFFER, cdw11,
1034 	    ctrlr->hmb_nchunks * ctrlr->hmb_chunk / 4096, ctrlr->hmb_desc_paddr,
1035 	    ctrlr->hmb_desc_paddr >> 32, ctrlr->hmb_nchunks, NULL, 0,
1036 	    nvme_completion_poll_cb, &status);
1037 	nvme_completion_poll(&status);
1038 	if (nvme_completion_is_error(&status.cpl))
1039 		nvme_printf(ctrlr, "nvme_ctrlr_hmb_enable failed!\n");
1040 }
1041 
1042 static void
1043 nvme_ctrlr_start(void *ctrlr_arg, bool resetting)
1044 {
1045 	struct nvme_controller *ctrlr = ctrlr_arg;
1046 	uint32_t old_num_io_queues;
1047 	int i;
1048 
1049 	/*
1050 	 * Only reset adminq here when we are restarting the
1051 	 *  controller after a reset.  During initialization,
1052 	 *  we have already submitted admin commands to get
1053 	 *  the number of I/O queues supported, so cannot reset
1054 	 *  the adminq again here.
1055 	 */
1056 	if (resetting)
1057 		nvme_qpair_reset(&ctrlr->adminq);
1058 
1059 	for (i = 0; i < ctrlr->num_io_queues; i++)
1060 		nvme_qpair_reset(&ctrlr->ioq[i]);
1061 
1062 	nvme_admin_qpair_enable(&ctrlr->adminq);
1063 
1064 	if (nvme_ctrlr_identify(ctrlr) != 0) {
1065 		nvme_ctrlr_fail(ctrlr);
1066 		return;
1067 	}
1068 
1069 	/*
1070 	 * The number of qpairs are determined during controller initialization,
1071 	 *  including using NVMe SET_FEATURES/NUMBER_OF_QUEUES to determine the
1072 	 *  HW limit.  We call SET_FEATURES again here so that it gets called
1073 	 *  after any reset for controllers that depend on the driver to
1074 	 *  explicit specify how many queues it will use.  This value should
1075 	 *  never change between resets, so panic if somehow that does happen.
1076 	 */
1077 	if (resetting) {
1078 		old_num_io_queues = ctrlr->num_io_queues;
1079 		if (nvme_ctrlr_set_num_qpairs(ctrlr) != 0) {
1080 			nvme_ctrlr_fail(ctrlr);
1081 			return;
1082 		}
1083 
1084 		if (old_num_io_queues != ctrlr->num_io_queues) {
1085 			panic("num_io_queues changed from %u to %u",
1086 			      old_num_io_queues, ctrlr->num_io_queues);
1087 		}
1088 	}
1089 
1090 	if (ctrlr->cdata.hmpre > 0 && ctrlr->hmb_nchunks == 0) {
1091 		nvme_ctrlr_hmb_alloc(ctrlr);
1092 		if (ctrlr->hmb_nchunks > 0)
1093 			nvme_ctrlr_hmb_enable(ctrlr, true, false);
1094 	} else if (ctrlr->hmb_nchunks > 0)
1095 		nvme_ctrlr_hmb_enable(ctrlr, true, true);
1096 
1097 	if (nvme_ctrlr_create_qpairs(ctrlr) != 0) {
1098 		nvme_ctrlr_fail(ctrlr);
1099 		return;
1100 	}
1101 
1102 	if (nvme_ctrlr_construct_namespaces(ctrlr) != 0) {
1103 		nvme_ctrlr_fail(ctrlr);
1104 		return;
1105 	}
1106 
1107 	nvme_ctrlr_configure_aer(ctrlr);
1108 	nvme_ctrlr_configure_int_coalescing(ctrlr);
1109 
1110 	for (i = 0; i < ctrlr->num_io_queues; i++)
1111 		nvme_io_qpair_enable(&ctrlr->ioq[i]);
1112 }
1113 
1114 void
1115 nvme_ctrlr_start_config_hook(void *arg)
1116 {
1117 	struct nvme_controller *ctrlr = arg;
1118 	int status;
1119 
1120 	/*
1121 	 * Reset controller twice to ensure we do a transition from cc.en==1 to
1122 	 * cc.en==0.  This is because we don't really know what status the
1123 	 * controller was left in when boot handed off to OS.  Linux doesn't do
1124 	 * this, however. If we adopt that policy, see also nvme_ctrlr_resume().
1125 	 */
1126 	status = nvme_ctrlr_hw_reset(ctrlr);
1127 	if (status != 0) {
1128 		nvme_ctrlr_fail(ctrlr);
1129 		config_intrhook_disestablish(&ctrlr->config_hook);
1130 		return;
1131 	}
1132 
1133 	status = nvme_ctrlr_hw_reset(ctrlr);
1134 	if (status != 0) {
1135 		nvme_ctrlr_fail(ctrlr);
1136 		config_intrhook_disestablish(&ctrlr->config_hook);
1137 		return;
1138 	}
1139 
1140 	nvme_qpair_reset(&ctrlr->adminq);
1141 	nvme_admin_qpair_enable(&ctrlr->adminq);
1142 
1143 	if (nvme_ctrlr_set_num_qpairs(ctrlr) == 0 &&
1144 	    nvme_ctrlr_construct_io_qpairs(ctrlr) == 0)
1145 		nvme_ctrlr_start(ctrlr, false);
1146 	else
1147 		nvme_ctrlr_fail(ctrlr);
1148 
1149 	nvme_sysctl_initialize_ctrlr(ctrlr);
1150 	config_intrhook_disestablish(&ctrlr->config_hook);
1151 
1152 	ctrlr->is_initialized = 1;
1153 	nvme_notify_new_controller(ctrlr);
1154 }
1155 
1156 static void
1157 nvme_ctrlr_reset_task(void *arg, int pending)
1158 {
1159 	struct nvme_controller	*ctrlr = arg;
1160 	int			status;
1161 
1162 	nvme_ctrlr_devctl_log(ctrlr, "RESET", "resetting controller");
1163 	status = nvme_ctrlr_hw_reset(ctrlr);
1164 	/*
1165 	 * Use pause instead of DELAY, so that we yield to any nvme interrupt
1166 	 *  handlers on this CPU that were blocked on a qpair lock. We want
1167 	 *  all nvme interrupts completed before proceeding with restarting the
1168 	 *  controller.
1169 	 *
1170 	 * XXX - any way to guarantee the interrupt handlers have quiesced?
1171 	 */
1172 	pause("nvmereset", hz / 10);
1173 	if (status == 0)
1174 		nvme_ctrlr_start(ctrlr, true);
1175 	else
1176 		nvme_ctrlr_fail(ctrlr);
1177 
1178 	atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
1179 }
1180 
1181 /*
1182  * Poll all the queues enabled on the device for completion.
1183  */
1184 void
1185 nvme_ctrlr_poll(struct nvme_controller *ctrlr)
1186 {
1187 	int i;
1188 
1189 	nvme_qpair_process_completions(&ctrlr->adminq);
1190 
1191 	for (i = 0; i < ctrlr->num_io_queues; i++)
1192 		if (ctrlr->ioq && ctrlr->ioq[i].cpl)
1193 			nvme_qpair_process_completions(&ctrlr->ioq[i]);
1194 }
1195 
1196 /*
1197  * Poll the single-vector interrupt case: num_io_queues will be 1 and
1198  * there's only a single vector. While we're polling, we mask further
1199  * interrupts in the controller.
1200  */
1201 void
1202 nvme_ctrlr_intx_handler(void *arg)
1203 {
1204 	struct nvme_controller *ctrlr = arg;
1205 
1206 	nvme_mmio_write_4(ctrlr, intms, 1);
1207 	nvme_ctrlr_poll(ctrlr);
1208 	nvme_mmio_write_4(ctrlr, intmc, 1);
1209 }
1210 
1211 static void
1212 nvme_pt_done(void *arg, const struct nvme_completion *cpl)
1213 {
1214 	struct nvme_pt_command *pt = arg;
1215 	struct mtx *mtx = pt->driver_lock;
1216 	uint16_t status;
1217 
1218 	bzero(&pt->cpl, sizeof(pt->cpl));
1219 	pt->cpl.cdw0 = cpl->cdw0;
1220 
1221 	status = cpl->status;
1222 	status &= ~NVME_STATUS_P_MASK;
1223 	pt->cpl.status = status;
1224 
1225 	mtx_lock(mtx);
1226 	pt->driver_lock = NULL;
1227 	wakeup(pt);
1228 	mtx_unlock(mtx);
1229 }
1230 
1231 int
1232 nvme_ctrlr_passthrough_cmd(struct nvme_controller *ctrlr,
1233     struct nvme_pt_command *pt, uint32_t nsid, int is_user_buffer,
1234     int is_admin_cmd)
1235 {
1236 	struct nvme_request	*req;
1237 	struct mtx		*mtx;
1238 	struct buf		*buf = NULL;
1239 	int			ret = 0;
1240 	vm_offset_t		addr, end;
1241 
1242 	if (pt->len > 0) {
1243 		/*
1244 		 * vmapbuf calls vm_fault_quick_hold_pages which only maps full
1245 		 * pages. Ensure this request has fewer than MAXPHYS bytes when
1246 		 * extended to full pages.
1247 		 */
1248 		addr = (vm_offset_t)pt->buf;
1249 		end = round_page(addr + pt->len);
1250 		addr = trunc_page(addr);
1251 		if (end - addr > MAXPHYS)
1252 			return EIO;
1253 
1254 		if (pt->len > ctrlr->max_xfer_size) {
1255 			nvme_printf(ctrlr, "pt->len (%d) "
1256 			    "exceeds max_xfer_size (%d)\n", pt->len,
1257 			    ctrlr->max_xfer_size);
1258 			return EIO;
1259 		}
1260 		if (is_user_buffer) {
1261 			/*
1262 			 * Ensure the user buffer is wired for the duration of
1263 			 *  this pass-through command.
1264 			 */
1265 			PHOLD(curproc);
1266 			buf = uma_zalloc(pbuf_zone, M_WAITOK);
1267 			buf->b_data = pt->buf;
1268 			buf->b_bufsize = pt->len;
1269 			buf->b_iocmd = pt->is_read ? BIO_READ : BIO_WRITE;
1270 			if (vmapbuf(buf, 1) < 0) {
1271 				ret = EFAULT;
1272 				goto err;
1273 			}
1274 			req = nvme_allocate_request_vaddr(buf->b_data, pt->len,
1275 			    nvme_pt_done, pt);
1276 		} else
1277 			req = nvme_allocate_request_vaddr(pt->buf, pt->len,
1278 			    nvme_pt_done, pt);
1279 	} else
1280 		req = nvme_allocate_request_null(nvme_pt_done, pt);
1281 
1282 	/* Assume user space already converted to little-endian */
1283 	req->cmd.opc = pt->cmd.opc;
1284 	req->cmd.fuse = pt->cmd.fuse;
1285 	req->cmd.rsvd2 = pt->cmd.rsvd2;
1286 	req->cmd.rsvd3 = pt->cmd.rsvd3;
1287 	req->cmd.cdw10 = pt->cmd.cdw10;
1288 	req->cmd.cdw11 = pt->cmd.cdw11;
1289 	req->cmd.cdw12 = pt->cmd.cdw12;
1290 	req->cmd.cdw13 = pt->cmd.cdw13;
1291 	req->cmd.cdw14 = pt->cmd.cdw14;
1292 	req->cmd.cdw15 = pt->cmd.cdw15;
1293 
1294 	req->cmd.nsid = htole32(nsid);
1295 
1296 	mtx = mtx_pool_find(mtxpool_sleep, pt);
1297 	pt->driver_lock = mtx;
1298 
1299 	if (is_admin_cmd)
1300 		nvme_ctrlr_submit_admin_request(ctrlr, req);
1301 	else
1302 		nvme_ctrlr_submit_io_request(ctrlr, req);
1303 
1304 	mtx_lock(mtx);
1305 	while (pt->driver_lock != NULL)
1306 		mtx_sleep(pt, mtx, PRIBIO, "nvme_pt", 0);
1307 	mtx_unlock(mtx);
1308 
1309 err:
1310 	if (buf != NULL) {
1311 		uma_zfree(pbuf_zone, buf);
1312 		PRELE(curproc);
1313 	}
1314 
1315 	return (ret);
1316 }
1317 
1318 static int
1319 nvme_ctrlr_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int flag,
1320     struct thread *td)
1321 {
1322 	struct nvme_controller			*ctrlr;
1323 	struct nvme_pt_command			*pt;
1324 
1325 	ctrlr = cdev->si_drv1;
1326 
1327 	switch (cmd) {
1328 	case NVME_RESET_CONTROLLER:
1329 		nvme_ctrlr_reset(ctrlr);
1330 		break;
1331 	case NVME_PASSTHROUGH_CMD:
1332 		pt = (struct nvme_pt_command *)arg;
1333 		return (nvme_ctrlr_passthrough_cmd(ctrlr, pt, le32toh(pt->cmd.nsid),
1334 		    1 /* is_user_buffer */, 1 /* is_admin_cmd */));
1335 	case NVME_GET_NSID:
1336 	{
1337 		struct nvme_get_nsid *gnsid = (struct nvme_get_nsid *)arg;
1338 		strncpy(gnsid->cdev, device_get_nameunit(ctrlr->dev),
1339 		    sizeof(gnsid->cdev));
1340 		gnsid->cdev[sizeof(gnsid->cdev) - 1] = '\0';
1341 		gnsid->nsid = 0;
1342 		break;
1343 	}
1344 	default:
1345 		return (ENOTTY);
1346 	}
1347 
1348 	return (0);
1349 }
1350 
1351 static struct cdevsw nvme_ctrlr_cdevsw = {
1352 	.d_version =	D_VERSION,
1353 	.d_flags =	0,
1354 	.d_ioctl =	nvme_ctrlr_ioctl
1355 };
1356 
1357 int
1358 nvme_ctrlr_construct(struct nvme_controller *ctrlr, device_t dev)
1359 {
1360 	struct make_dev_args	md_args;
1361 	uint32_t	cap_lo;
1362 	uint32_t	cap_hi;
1363 	uint32_t	to;
1364 	uint8_t		mpsmin;
1365 	int		status, timeout_period;
1366 
1367 	ctrlr->dev = dev;
1368 
1369 	mtx_init(&ctrlr->lock, "nvme ctrlr lock", NULL, MTX_DEF);
1370 	if (bus_get_domain(dev, &ctrlr->domain) != 0)
1371 		ctrlr->domain = 0;
1372 
1373 	cap_hi = nvme_mmio_read_4(ctrlr, cap_hi);
1374 	ctrlr->dstrd = NVME_CAP_HI_DSTRD(cap_hi) + 2;
1375 
1376 	mpsmin = NVME_CAP_HI_MPSMIN(cap_hi);
1377 	ctrlr->min_page_size = 1 << (12 + mpsmin);
1378 
1379 	/* Get ready timeout value from controller, in units of 500ms. */
1380 	cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
1381 	to = NVME_CAP_LO_TO(cap_lo) + 1;
1382 	ctrlr->ready_timeout_in_ms = to * 500;
1383 
1384 	timeout_period = NVME_DEFAULT_TIMEOUT_PERIOD;
1385 	TUNABLE_INT_FETCH("hw.nvme.timeout_period", &timeout_period);
1386 	timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1387 	timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1388 	ctrlr->timeout_period = timeout_period;
1389 
1390 	nvme_retry_count = NVME_DEFAULT_RETRY_COUNT;
1391 	TUNABLE_INT_FETCH("hw.nvme.retry_count", &nvme_retry_count);
1392 
1393 	ctrlr->enable_aborts = 0;
1394 	TUNABLE_INT_FETCH("hw.nvme.enable_aborts", &ctrlr->enable_aborts);
1395 
1396 	ctrlr->max_xfer_size = NVME_MAX_XFER_SIZE;
1397 	if (nvme_ctrlr_construct_admin_qpair(ctrlr) != 0)
1398 		return (ENXIO);
1399 
1400 	ctrlr->taskqueue = taskqueue_create("nvme_taskq", M_WAITOK,
1401 	    taskqueue_thread_enqueue, &ctrlr->taskqueue);
1402 	taskqueue_start_threads(&ctrlr->taskqueue, 1, PI_DISK, "nvme taskq");
1403 
1404 	ctrlr->is_resetting = 0;
1405 	ctrlr->is_initialized = 0;
1406 	ctrlr->notification_sent = 0;
1407 	TASK_INIT(&ctrlr->reset_task, 0, nvme_ctrlr_reset_task, ctrlr);
1408 	TASK_INIT(&ctrlr->fail_req_task, 0, nvme_ctrlr_fail_req_task, ctrlr);
1409 	STAILQ_INIT(&ctrlr->fail_req);
1410 	ctrlr->is_failed = false;
1411 
1412 	make_dev_args_init(&md_args);
1413 	md_args.mda_devsw = &nvme_ctrlr_cdevsw;
1414 	md_args.mda_uid = UID_ROOT;
1415 	md_args.mda_gid = GID_WHEEL;
1416 	md_args.mda_mode = 0600;
1417 	md_args.mda_unit = device_get_unit(dev);
1418 	md_args.mda_si_drv1 = (void *)ctrlr;
1419 	status = make_dev_s(&md_args, &ctrlr->cdev, "nvme%d",
1420 	    device_get_unit(dev));
1421 	if (status != 0)
1422 		return (ENXIO);
1423 
1424 	return (0);
1425 }
1426 
1427 void
1428 nvme_ctrlr_destruct(struct nvme_controller *ctrlr, device_t dev)
1429 {
1430 	int	gone, i;
1431 
1432 	if (ctrlr->resource == NULL)
1433 		goto nores;
1434 
1435 	/*
1436 	 * Check whether it is a hot unplug or a clean driver detach.
1437 	 * If device is not there any more, skip any shutdown commands.
1438 	 */
1439 	gone = (nvme_mmio_read_4(ctrlr, csts) == 0xffffffff);
1440 	if (gone)
1441 		nvme_ctrlr_fail(ctrlr);
1442 	else
1443 		nvme_notify_fail_consumers(ctrlr);
1444 
1445 	for (i = 0; i < NVME_MAX_NAMESPACES; i++)
1446 		nvme_ns_destruct(&ctrlr->ns[i]);
1447 
1448 	if (ctrlr->cdev)
1449 		destroy_dev(ctrlr->cdev);
1450 
1451 	if (ctrlr->is_initialized) {
1452 		if (!gone) {
1453 			if (ctrlr->hmb_nchunks > 0)
1454 				nvme_ctrlr_hmb_enable(ctrlr, false, false);
1455 			nvme_ctrlr_delete_qpairs(ctrlr);
1456 		}
1457 		for (i = 0; i < ctrlr->num_io_queues; i++)
1458 			nvme_io_qpair_destroy(&ctrlr->ioq[i]);
1459 		free(ctrlr->ioq, M_NVME);
1460 		nvme_ctrlr_hmb_free(ctrlr);
1461 	}
1462 	nvme_admin_qpair_destroy(&ctrlr->adminq);
1463 
1464 	/*
1465 	 *  Notify the controller of a shutdown, even though this is due to
1466 	 *   a driver unload, not a system shutdown (this path is not invoked
1467 	 *   during shutdown).  This ensures the controller receives a
1468 	 *   shutdown notification in case the system is shutdown before
1469 	 *   reloading the driver.
1470 	 */
1471 	if (!gone)
1472 		nvme_ctrlr_shutdown(ctrlr);
1473 
1474 	if (!gone)
1475 		nvme_ctrlr_disable(ctrlr);
1476 
1477 	if (ctrlr->taskqueue)
1478 		taskqueue_free(ctrlr->taskqueue);
1479 
1480 	if (ctrlr->tag)
1481 		bus_teardown_intr(ctrlr->dev, ctrlr->res, ctrlr->tag);
1482 
1483 	if (ctrlr->res)
1484 		bus_release_resource(ctrlr->dev, SYS_RES_IRQ,
1485 		    rman_get_rid(ctrlr->res), ctrlr->res);
1486 
1487 	if (ctrlr->bar4_resource != NULL) {
1488 		bus_release_resource(dev, SYS_RES_MEMORY,
1489 		    ctrlr->bar4_resource_id, ctrlr->bar4_resource);
1490 	}
1491 
1492 	bus_release_resource(dev, SYS_RES_MEMORY,
1493 	    ctrlr->resource_id, ctrlr->resource);
1494 
1495 nores:
1496 	mtx_destroy(&ctrlr->lock);
1497 }
1498 
1499 void
1500 nvme_ctrlr_shutdown(struct nvme_controller *ctrlr)
1501 {
1502 	uint32_t	cc;
1503 	uint32_t	csts;
1504 	int		ticks = 0;
1505 
1506 	cc = nvme_mmio_read_4(ctrlr, cc);
1507 	cc &= ~(NVME_CC_REG_SHN_MASK << NVME_CC_REG_SHN_SHIFT);
1508 	cc |= NVME_SHN_NORMAL << NVME_CC_REG_SHN_SHIFT;
1509 	nvme_mmio_write_4(ctrlr, cc, cc);
1510 
1511 	while (1) {
1512 		csts = nvme_mmio_read_4(ctrlr, csts);
1513 		if (csts == 0xffffffff)		/* Hot unplug. */
1514 			break;
1515 		if (NVME_CSTS_GET_SHST(csts) == NVME_SHST_COMPLETE)
1516 			break;
1517 		if (ticks++ > 5*hz) {
1518 			nvme_printf(ctrlr, "did not complete shutdown within"
1519 			    " 5 seconds of notification\n");
1520 			break;
1521 		}
1522 		pause("nvme shn", 1);
1523 	}
1524 }
1525 
1526 void
1527 nvme_ctrlr_submit_admin_request(struct nvme_controller *ctrlr,
1528     struct nvme_request *req)
1529 {
1530 
1531 	nvme_qpair_submit_request(&ctrlr->adminq, req);
1532 }
1533 
1534 void
1535 nvme_ctrlr_submit_io_request(struct nvme_controller *ctrlr,
1536     struct nvme_request *req)
1537 {
1538 	struct nvme_qpair       *qpair;
1539 
1540 	qpair = &ctrlr->ioq[QP(ctrlr, curcpu)];
1541 	nvme_qpair_submit_request(qpair, req);
1542 }
1543 
1544 device_t
1545 nvme_ctrlr_get_device(struct nvme_controller *ctrlr)
1546 {
1547 
1548 	return (ctrlr->dev);
1549 }
1550 
1551 const struct nvme_controller_data *
1552 nvme_ctrlr_get_data(struct nvme_controller *ctrlr)
1553 {
1554 
1555 	return (&ctrlr->cdata);
1556 }
1557 
1558 int
1559 nvme_ctrlr_suspend(struct nvme_controller *ctrlr)
1560 {
1561 	int to = hz;
1562 
1563 	/*
1564 	 * Can't touch failed controllers, so it's already suspended.
1565 	 */
1566 	if (ctrlr->is_failed)
1567 		return (0);
1568 
1569 	/*
1570 	 * We don't want the reset taskqueue running, since it does similar
1571 	 * things, so prevent it from running after we start. Wait for any reset
1572 	 * that may have been started to complete. The reset process we follow
1573 	 * will ensure that any new I/O will queue and be given to the hardware
1574 	 * after we resume (though there should be none).
1575 	 */
1576 	while (atomic_cmpset_32(&ctrlr->is_resetting, 0, 1) == 0 && to-- > 0)
1577 		pause("nvmesusp", 1);
1578 	if (to <= 0) {
1579 		nvme_printf(ctrlr,
1580 		    "Competing reset task didn't finish. Try again later.\n");
1581 		return (EWOULDBLOCK);
1582 	}
1583 
1584 	if (ctrlr->hmb_nchunks > 0)
1585 		nvme_ctrlr_hmb_enable(ctrlr, false, false);
1586 
1587 	/*
1588 	 * Per Section 7.6.2 of NVMe spec 1.4, to properly suspend, we need to
1589 	 * delete the hardware I/O queues, and then shutdown. This properly
1590 	 * flushes any metadata the drive may have stored so it can survive
1591 	 * having its power removed and prevents the unsafe shutdown count from
1592 	 * incriminating. Once we delete the qpairs, we have to disable them
1593 	 * before shutting down. The delay is out of paranoia in
1594 	 * nvme_ctrlr_hw_reset, and is repeated here (though we should have no
1595 	 * pending I/O that the delay copes with).
1596 	 */
1597 	nvme_ctrlr_delete_qpairs(ctrlr);
1598 	nvme_ctrlr_disable_qpairs(ctrlr);
1599 	DELAY(100*1000);
1600 	nvme_ctrlr_shutdown(ctrlr);
1601 
1602 	return (0);
1603 }
1604 
1605 int
1606 nvme_ctrlr_resume(struct nvme_controller *ctrlr)
1607 {
1608 
1609 	/*
1610 	 * Can't touch failed controllers, so nothing to do to resume.
1611 	 */
1612 	if (ctrlr->is_failed)
1613 		return (0);
1614 
1615 	/*
1616 	 * Have to reset the hardware twice, just like we do on attach. See
1617 	 * nmve_attach() for why.
1618 	 */
1619 	if (nvme_ctrlr_hw_reset(ctrlr) != 0)
1620 		goto fail;
1621 	if (nvme_ctrlr_hw_reset(ctrlr) != 0)
1622 		goto fail;
1623 
1624 	/*
1625 	 * Now that we've reset the hardware, we can restart the controller. Any
1626 	 * I/O that was pending is requeued. Any admin commands are aborted with
1627 	 * an error. Once we've restarted, take the controller out of reset.
1628 	 */
1629 	nvme_ctrlr_start(ctrlr, true);
1630 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
1631 
1632 	return (0);
1633 fail:
1634 	/*
1635 	 * Since we can't bring the controller out of reset, announce and fail
1636 	 * the controller. However, we have to return success for the resume
1637 	 * itself, due to questionable APIs.
1638 	 */
1639 	nvme_printf(ctrlr, "Failed to reset on resume, failing.\n");
1640 	nvme_ctrlr_fail(ctrlr);
1641 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
1642 	return (0);
1643 }
1644