xref: /freebsd-13.1/sys/dev/nvme/nvme_ctrlr.c (revision 052d3c12)
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/endian.h>
44 
45 #include <dev/pci/pcireg.h>
46 #include <dev/pci/pcivar.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 static void nvme_ctrlr_setup_interrupts(struct nvme_controller *ctrlr);
55 
56 static int
57 nvme_ctrlr_allocate_bar(struct nvme_controller *ctrlr)
58 {
59 
60 	ctrlr->resource_id = PCIR_BAR(0);
61 
62 	ctrlr->resource = bus_alloc_resource_any(ctrlr->dev, SYS_RES_MEMORY,
63 	    &ctrlr->resource_id, RF_ACTIVE);
64 
65 	if(ctrlr->resource == NULL) {
66 		nvme_printf(ctrlr, "unable to allocate pci resource\n");
67 		return (ENOMEM);
68 	}
69 
70 	ctrlr->bus_tag = rman_get_bustag(ctrlr->resource);
71 	ctrlr->bus_handle = rman_get_bushandle(ctrlr->resource);
72 	ctrlr->regs = (struct nvme_registers *)ctrlr->bus_handle;
73 
74 	/*
75 	 * The NVMe spec allows for the MSI-X table to be placed behind
76 	 *  BAR 4/5, separate from the control/doorbell registers.  Always
77 	 *  try to map this bar, because it must be mapped prior to calling
78 	 *  pci_alloc_msix().  If the table isn't behind BAR 4/5,
79 	 *  bus_alloc_resource() will just return NULL which is OK.
80 	 */
81 	ctrlr->bar4_resource_id = PCIR_BAR(4);
82 	ctrlr->bar4_resource = bus_alloc_resource_any(ctrlr->dev, SYS_RES_MEMORY,
83 	    &ctrlr->bar4_resource_id, RF_ACTIVE);
84 
85 	return (0);
86 }
87 
88 static int
89 nvme_ctrlr_construct_admin_qpair(struct nvme_controller *ctrlr)
90 {
91 	struct nvme_qpair	*qpair;
92 	uint32_t		num_entries;
93 	int			error;
94 
95 	qpair = &ctrlr->adminq;
96 
97 	num_entries = NVME_ADMIN_ENTRIES;
98 	TUNABLE_INT_FETCH("hw.nvme.admin_entries", &num_entries);
99 	/*
100 	 * If admin_entries was overridden to an invalid value, revert it
101 	 *  back to our default value.
102 	 */
103 	if (num_entries < NVME_MIN_ADMIN_ENTRIES ||
104 	    num_entries > NVME_MAX_ADMIN_ENTRIES) {
105 		nvme_printf(ctrlr, "invalid hw.nvme.admin_entries=%d "
106 		    "specified\n", num_entries);
107 		num_entries = NVME_ADMIN_ENTRIES;
108 	}
109 
110 	/*
111 	 * The admin queue's max xfer size is treated differently than the
112 	 *  max I/O xfer size.  16KB is sufficient here - maybe even less?
113 	 */
114 	error = nvme_qpair_construct(qpair,
115 				     0, /* qpair ID */
116 				     0, /* vector */
117 				     num_entries,
118 				     NVME_ADMIN_TRACKERS,
119 				     ctrlr);
120 	return (error);
121 }
122 
123 static int
124 nvme_ctrlr_construct_io_qpairs(struct nvme_controller *ctrlr)
125 {
126 	struct nvme_qpair	*qpair;
127 	uint32_t		cap_lo;
128 	uint16_t		mqes;
129 	int			i, error, num_entries, num_trackers;
130 
131 	num_entries = NVME_IO_ENTRIES;
132 	TUNABLE_INT_FETCH("hw.nvme.io_entries", &num_entries);
133 
134 	/*
135 	 * NVMe spec sets a hard limit of 64K max entries, but
136 	 *  devices may specify a smaller limit, so we need to check
137 	 *  the MQES field in the capabilities register.
138 	 */
139 	cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
140 	mqes = (cap_lo >> NVME_CAP_LO_REG_MQES_SHIFT) & NVME_CAP_LO_REG_MQES_MASK;
141 	num_entries = min(num_entries, mqes + 1);
142 
143 	num_trackers = NVME_IO_TRACKERS;
144 	TUNABLE_INT_FETCH("hw.nvme.io_trackers", &num_trackers);
145 
146 	num_trackers = max(num_trackers, NVME_MIN_IO_TRACKERS);
147 	num_trackers = min(num_trackers, NVME_MAX_IO_TRACKERS);
148 	/*
149 	 * No need to have more trackers than entries in the submit queue.
150 	 *  Note also that for a queue size of N, we can only have (N-1)
151 	 *  commands outstanding, hence the "-1" here.
152 	 */
153 	num_trackers = min(num_trackers, (num_entries-1));
154 
155 	/*
156 	 * Our best estimate for the maximum number of I/Os that we should
157 	 * noramlly have in flight at one time. This should be viewed as a hint,
158 	 * not a hard limit and will need to be revisitted when the upper layers
159 	 * of the storage system grows multi-queue support.
160 	 */
161 	ctrlr->max_hw_pend_io = num_trackers * ctrlr->num_io_queues * 3 / 4;
162 
163 	/*
164 	 * This was calculated previously when setting up interrupts, but
165 	 *  a controller could theoretically support fewer I/O queues than
166 	 *  MSI-X vectors.  So calculate again here just to be safe.
167 	 */
168 	ctrlr->num_cpus_per_ioq = howmany(mp_ncpus, ctrlr->num_io_queues);
169 
170 	ctrlr->ioq = malloc(ctrlr->num_io_queues * sizeof(struct nvme_qpair),
171 	    M_NVME, M_ZERO | M_WAITOK);
172 
173 	for (i = 0; i < ctrlr->num_io_queues; i++) {
174 		qpair = &ctrlr->ioq[i];
175 
176 		/*
177 		 * Admin queue has ID=0. IO queues start at ID=1 -
178 		 *  hence the 'i+1' here.
179 		 *
180 		 * For I/O queues, use the controller-wide max_xfer_size
181 		 *  calculated in nvme_attach().
182 		 */
183 		error = nvme_qpair_construct(qpair,
184 				     i+1, /* qpair ID */
185 				     ctrlr->msix_enabled ? i+1 : 0, /* vector */
186 				     num_entries,
187 				     num_trackers,
188 				     ctrlr);
189 		if (error)
190 			return (error);
191 
192 		/*
193 		 * Do not bother binding interrupts if we only have one I/O
194 		 *  interrupt thread for this controller.
195 		 */
196 		if (ctrlr->num_io_queues > 1)
197 			bus_bind_intr(ctrlr->dev, qpair->res,
198 			    i * ctrlr->num_cpus_per_ioq);
199 	}
200 
201 	return (0);
202 }
203 
204 static void
205 nvme_ctrlr_fail(struct nvme_controller *ctrlr)
206 {
207 	int i;
208 
209 	ctrlr->is_failed = TRUE;
210 	nvme_qpair_fail(&ctrlr->adminq);
211 	if (ctrlr->ioq != NULL) {
212 		for (i = 0; i < ctrlr->num_io_queues; i++)
213 			nvme_qpair_fail(&ctrlr->ioq[i]);
214 	}
215 	nvme_notify_fail_consumers(ctrlr);
216 }
217 
218 void
219 nvme_ctrlr_post_failed_request(struct nvme_controller *ctrlr,
220     struct nvme_request *req)
221 {
222 
223 	mtx_lock(&ctrlr->lock);
224 	STAILQ_INSERT_TAIL(&ctrlr->fail_req, req, stailq);
225 	mtx_unlock(&ctrlr->lock);
226 	taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->fail_req_task);
227 }
228 
229 static void
230 nvme_ctrlr_fail_req_task(void *arg, int pending)
231 {
232 	struct nvme_controller	*ctrlr = arg;
233 	struct nvme_request	*req;
234 
235 	mtx_lock(&ctrlr->lock);
236 	while (!STAILQ_EMPTY(&ctrlr->fail_req)) {
237 		req = STAILQ_FIRST(&ctrlr->fail_req);
238 		STAILQ_REMOVE_HEAD(&ctrlr->fail_req, stailq);
239 		nvme_qpair_manual_complete_request(req->qpair, req,
240 		    NVME_SCT_GENERIC, NVME_SC_ABORTED_BY_REQUEST, TRUE);
241 	}
242 	mtx_unlock(&ctrlr->lock);
243 }
244 
245 static int
246 nvme_ctrlr_wait_for_ready(struct nvme_controller *ctrlr, int desired_val)
247 {
248 	int ms_waited;
249 	uint32_t csts;
250 
251 	csts = nvme_mmio_read_4(ctrlr, csts);
252 
253 	ms_waited = 0;
254 	while (((csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK) != desired_val) {
255 		if (ms_waited++ > ctrlr->ready_timeout_in_ms) {
256 			nvme_printf(ctrlr, "controller ready did not become %d "
257 			    "within %d ms\n", desired_val, ctrlr->ready_timeout_in_ms);
258 			return (ENXIO);
259 		}
260 		DELAY(1000);
261 		csts = nvme_mmio_read_4(ctrlr, csts);
262 	}
263 
264 	return (0);
265 }
266 
267 static int
268 nvme_ctrlr_disable(struct nvme_controller *ctrlr)
269 {
270 	uint32_t cc;
271 	uint32_t csts;
272 	uint8_t  en, rdy;
273 	int err;
274 
275 	cc = nvme_mmio_read_4(ctrlr, cc);
276 	csts = nvme_mmio_read_4(ctrlr, csts);
277 
278 	en = (cc >> NVME_CC_REG_EN_SHIFT) & NVME_CC_REG_EN_MASK;
279 	rdy = (csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK;
280 
281 	/*
282 	 * Per 3.1.5 in NVME 1.3 spec, transitioning CC.EN from 0 to 1
283 	 * when CSTS.RDY is 1 or transitioning CC.EN from 1 to 0 when
284 	 * CSTS.RDY is 0 "has undefined results" So make sure that CSTS.RDY
285 	 * isn't the desired value. Short circuit if we're already disabled.
286 	 */
287 	if (en == 1) {
288 		if (rdy == 0) {
289 			/* EN == 1, wait for  RDY == 1 or fail */
290 			err = nvme_ctrlr_wait_for_ready(ctrlr, 1);
291 			if (err != 0)
292 				return (err);
293 		}
294 	} else {
295 		/* EN == 0 already wait for RDY == 0 */
296 		if (rdy == 0)
297 			return (0);
298 		else
299 			return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
300 	}
301 
302 	cc &= ~NVME_CC_REG_EN_MASK;
303 	nvme_mmio_write_4(ctrlr, cc, cc);
304 	/*
305 	 * Some drives have issues with accessing the mmio after we
306 	 * disable, so delay for a bit after we write the bit to
307 	 * cope with these issues.
308 	 */
309 	if (ctrlr->quirks & QUIRK_DELAY_B4_CHK_RDY)
310 		pause("nvmeR", B4_CHK_RDY_DELAY_MS * hz / 1000);
311 	return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
312 }
313 
314 static int
315 nvme_ctrlr_enable(struct nvme_controller *ctrlr)
316 {
317 	uint32_t	cc;
318 	uint32_t	csts;
319 	uint32_t	aqa;
320 	uint32_t	qsize;
321 	uint8_t		en, rdy;
322 	int		err;
323 
324 	cc = nvme_mmio_read_4(ctrlr, cc);
325 	csts = nvme_mmio_read_4(ctrlr, csts);
326 
327 	en = (cc >> NVME_CC_REG_EN_SHIFT) & NVME_CC_REG_EN_MASK;
328 	rdy = (csts >> NVME_CSTS_REG_RDY_SHIFT) & NVME_CSTS_REG_RDY_MASK;
329 
330 	/*
331 	 * See note in nvme_ctrlr_disable. Short circuit if we're already enabled.
332 	 */
333 	if (en == 1) {
334 		if (rdy == 1)
335 			return (0);
336 		else
337 			return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
338 	} else {
339 		/* EN == 0 already wait for RDY == 0 or fail */
340 		err = nvme_ctrlr_wait_for_ready(ctrlr, 0);
341 		if (err != 0)
342 			return (err);
343 	}
344 
345 	nvme_mmio_write_8(ctrlr, asq, ctrlr->adminq.cmd_bus_addr);
346 	DELAY(5000);
347 	nvme_mmio_write_8(ctrlr, acq, ctrlr->adminq.cpl_bus_addr);
348 	DELAY(5000);
349 
350 	/* acqs and asqs are 0-based. */
351 	qsize = ctrlr->adminq.num_entries - 1;
352 
353 	aqa = 0;
354 	aqa = (qsize & NVME_AQA_REG_ACQS_MASK) << NVME_AQA_REG_ACQS_SHIFT;
355 	aqa |= (qsize & NVME_AQA_REG_ASQS_MASK) << NVME_AQA_REG_ASQS_SHIFT;
356 	nvme_mmio_write_4(ctrlr, aqa, aqa);
357 	DELAY(5000);
358 
359 	/* Initialization values for CC */
360 	cc = 0;
361 	cc |= 1 << NVME_CC_REG_EN_SHIFT;
362 	cc |= 0 << NVME_CC_REG_CSS_SHIFT;
363 	cc |= 0 << NVME_CC_REG_AMS_SHIFT;
364 	cc |= 0 << NVME_CC_REG_SHN_SHIFT;
365 	cc |= 6 << NVME_CC_REG_IOSQES_SHIFT; /* SQ entry size == 64 == 2^6 */
366 	cc |= 4 << NVME_CC_REG_IOCQES_SHIFT; /* CQ entry size == 16 == 2^4 */
367 
368 	/* This evaluates to 0, which is according to spec. */
369 	cc |= (PAGE_SIZE >> 13) << NVME_CC_REG_MPS_SHIFT;
370 
371 	nvme_mmio_write_4(ctrlr, cc, cc);
372 
373 	return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
374 }
375 
376 int
377 nvme_ctrlr_hw_reset(struct nvme_controller *ctrlr)
378 {
379 	int i, err;
380 
381 	nvme_admin_qpair_disable(&ctrlr->adminq);
382 	/*
383 	 * I/O queues are not allocated before the initial HW
384 	 *  reset, so do not try to disable them.  Use is_initialized
385 	 *  to determine if this is the initial HW reset.
386 	 */
387 	if (ctrlr->is_initialized) {
388 		for (i = 0; i < ctrlr->num_io_queues; i++)
389 			nvme_io_qpair_disable(&ctrlr->ioq[i]);
390 	}
391 
392 	DELAY(100*1000);
393 
394 	err = nvme_ctrlr_disable(ctrlr);
395 	if (err != 0)
396 		return err;
397 	return (nvme_ctrlr_enable(ctrlr));
398 }
399 
400 void
401 nvme_ctrlr_reset(struct nvme_controller *ctrlr)
402 {
403 	int cmpset;
404 
405 	cmpset = atomic_cmpset_32(&ctrlr->is_resetting, 0, 1);
406 
407 	if (cmpset == 0 || ctrlr->is_failed)
408 		/*
409 		 * Controller is already resetting or has failed.  Return
410 		 *  immediately since there is no need to kick off another
411 		 *  reset in these cases.
412 		 */
413 		return;
414 
415 	taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->reset_task);
416 }
417 
418 static int
419 nvme_ctrlr_identify(struct nvme_controller *ctrlr)
420 {
421 	struct nvme_completion_poll_status	status;
422 
423 	status.done = 0;
424 	nvme_ctrlr_cmd_identify_controller(ctrlr, &ctrlr->cdata,
425 	    nvme_completion_poll_cb, &status);
426 	while (!atomic_load_acq_int(&status.done))
427 		pause("nvme", 1);
428 	if (nvme_completion_is_error(&status.cpl)) {
429 		nvme_printf(ctrlr, "nvme_identify_controller failed!\n");
430 		return (ENXIO);
431 	}
432 
433 	/* Convert data to host endian */
434 	nvme_controller_data_swapbytes(&ctrlr->cdata);
435 
436 	/*
437 	 * Use MDTS to ensure our default max_xfer_size doesn't exceed what the
438 	 *  controller supports.
439 	 */
440 	if (ctrlr->cdata.mdts > 0)
441 		ctrlr->max_xfer_size = min(ctrlr->max_xfer_size,
442 		    ctrlr->min_page_size * (1 << (ctrlr->cdata.mdts)));
443 
444 	return (0);
445 }
446 
447 static int
448 nvme_ctrlr_set_num_qpairs(struct nvme_controller *ctrlr)
449 {
450 	struct nvme_completion_poll_status	status;
451 	int					cq_allocated, sq_allocated;
452 
453 	status.done = 0;
454 	nvme_ctrlr_cmd_set_num_queues(ctrlr, ctrlr->num_io_queues,
455 	    nvme_completion_poll_cb, &status);
456 	while (!atomic_load_acq_int(&status.done))
457 		pause("nvme", 1);
458 	if (nvme_completion_is_error(&status.cpl)) {
459 		nvme_printf(ctrlr, "nvme_ctrlr_set_num_qpairs failed!\n");
460 		return (ENXIO);
461 	}
462 
463 	/*
464 	 * Data in cdw0 is 0-based.
465 	 * Lower 16-bits indicate number of submission queues allocated.
466 	 * Upper 16-bits indicate number of completion queues allocated.
467 	 */
468 	sq_allocated = (status.cpl.cdw0 & 0xFFFF) + 1;
469 	cq_allocated = (status.cpl.cdw0 >> 16) + 1;
470 
471 	/*
472 	 * Controller may allocate more queues than we requested,
473 	 *  so use the minimum of the number requested and what was
474 	 *  actually allocated.
475 	 */
476 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, sq_allocated);
477 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, cq_allocated);
478 
479 	return (0);
480 }
481 
482 static int
483 nvme_ctrlr_create_qpairs(struct nvme_controller *ctrlr)
484 {
485 	struct nvme_completion_poll_status	status;
486 	struct nvme_qpair			*qpair;
487 	int					i;
488 
489 	for (i = 0; i < ctrlr->num_io_queues; i++) {
490 		qpair = &ctrlr->ioq[i];
491 
492 		status.done = 0;
493 		nvme_ctrlr_cmd_create_io_cq(ctrlr, qpair, qpair->vector,
494 		    nvme_completion_poll_cb, &status);
495 		while (!atomic_load_acq_int(&status.done))
496 			pause("nvme", 1);
497 		if (nvme_completion_is_error(&status.cpl)) {
498 			nvme_printf(ctrlr, "nvme_create_io_cq failed!\n");
499 			return (ENXIO);
500 		}
501 
502 		status.done = 0;
503 		nvme_ctrlr_cmd_create_io_sq(qpair->ctrlr, qpair,
504 		    nvme_completion_poll_cb, &status);
505 		while (!atomic_load_acq_int(&status.done))
506 			pause("nvme", 1);
507 		if (nvme_completion_is_error(&status.cpl)) {
508 			nvme_printf(ctrlr, "nvme_create_io_sq failed!\n");
509 			return (ENXIO);
510 		}
511 	}
512 
513 	return (0);
514 }
515 
516 static int
517 nvme_ctrlr_construct_namespaces(struct nvme_controller *ctrlr)
518 {
519 	struct nvme_namespace	*ns;
520 	uint32_t 		i;
521 
522 	for (i = 0; i < min(ctrlr->cdata.nn, NVME_MAX_NAMESPACES); i++) {
523 		ns = &ctrlr->ns[i];
524 		nvme_ns_construct(ns, i+1, ctrlr);
525 	}
526 
527 	return (0);
528 }
529 
530 static boolean_t
531 is_log_page_id_valid(uint8_t page_id)
532 {
533 
534 	switch (page_id) {
535 	case NVME_LOG_ERROR:
536 	case NVME_LOG_HEALTH_INFORMATION:
537 	case NVME_LOG_FIRMWARE_SLOT:
538 		return (TRUE);
539 	}
540 
541 	return (FALSE);
542 }
543 
544 static uint32_t
545 nvme_ctrlr_get_log_page_size(struct nvme_controller *ctrlr, uint8_t page_id)
546 {
547 	uint32_t	log_page_size;
548 
549 	switch (page_id) {
550 	case NVME_LOG_ERROR:
551 		log_page_size = min(
552 		    sizeof(struct nvme_error_information_entry) *
553 		    (ctrlr->cdata.elpe + 1), NVME_MAX_AER_LOG_SIZE);
554 		break;
555 	case NVME_LOG_HEALTH_INFORMATION:
556 		log_page_size = sizeof(struct nvme_health_information_page);
557 		break;
558 	case NVME_LOG_FIRMWARE_SLOT:
559 		log_page_size = sizeof(struct nvme_firmware_page);
560 		break;
561 	default:
562 		log_page_size = 0;
563 		break;
564 	}
565 
566 	return (log_page_size);
567 }
568 
569 static void
570 nvme_ctrlr_log_critical_warnings(struct nvme_controller *ctrlr,
571     uint8_t state)
572 {
573 
574 	if (state & NVME_CRIT_WARN_ST_AVAILABLE_SPARE)
575 		nvme_printf(ctrlr, "available spare space below threshold\n");
576 
577 	if (state & NVME_CRIT_WARN_ST_TEMPERATURE)
578 		nvme_printf(ctrlr, "temperature above threshold\n");
579 
580 	if (state & NVME_CRIT_WARN_ST_DEVICE_RELIABILITY)
581 		nvme_printf(ctrlr, "device reliability degraded\n");
582 
583 	if (state & NVME_CRIT_WARN_ST_READ_ONLY)
584 		nvme_printf(ctrlr, "media placed in read only mode\n");
585 
586 	if (state & NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP)
587 		nvme_printf(ctrlr, "volatile memory backup device failed\n");
588 
589 	if (state & NVME_CRIT_WARN_ST_RESERVED_MASK)
590 		nvme_printf(ctrlr,
591 		    "unknown critical warning(s): state = 0x%02x\n", state);
592 }
593 
594 static void
595 nvme_ctrlr_async_event_log_page_cb(void *arg, const struct nvme_completion *cpl)
596 {
597 	struct nvme_async_event_request		*aer = arg;
598 	struct nvme_health_information_page	*health_info;
599 	struct nvme_error_information_entry	*err;
600 	int i;
601 
602 	/*
603 	 * If the log page fetch for some reason completed with an error,
604 	 *  don't pass log page data to the consumers.  In practice, this case
605 	 *  should never happen.
606 	 */
607 	if (nvme_completion_is_error(cpl))
608 		nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
609 		    aer->log_page_id, NULL, 0);
610 	else {
611 		/* Convert data to host endian */
612 		switch (aer->log_page_id) {
613 		case NVME_LOG_ERROR:
614 			err = (struct nvme_error_information_entry *)aer->log_page_buffer;
615 			for (i = 0; i < (aer->ctrlr->cdata.elpe + 1); i++)
616 				nvme_error_information_entry_swapbytes(err++);
617 			break;
618 		case NVME_LOG_HEALTH_INFORMATION:
619 			nvme_health_information_page_swapbytes(
620 			    (struct nvme_health_information_page *)aer->log_page_buffer);
621 			break;
622 		case NVME_LOG_FIRMWARE_SLOT:
623 			nvme_firmware_page_swapbytes(
624 			    (struct nvme_firmware_page *)aer->log_page_buffer);
625 			break;
626 		case INTEL_LOG_TEMP_STATS:
627 			intel_log_temp_stats_swapbytes(
628 			    (struct intel_log_temp_stats *)aer->log_page_buffer);
629 			break;
630 		default:
631 			break;
632 		}
633 
634 		if (aer->log_page_id == NVME_LOG_HEALTH_INFORMATION) {
635 			health_info = (struct nvme_health_information_page *)
636 			    aer->log_page_buffer;
637 			nvme_ctrlr_log_critical_warnings(aer->ctrlr,
638 			    health_info->critical_warning);
639 			/*
640 			 * Critical warnings reported through the
641 			 *  SMART/health log page are persistent, so
642 			 *  clear the associated bits in the async event
643 			 *  config so that we do not receive repeated
644 			 *  notifications for the same event.
645 			 */
646 			aer->ctrlr->async_event_config &=
647 			    ~health_info->critical_warning;
648 			nvme_ctrlr_cmd_set_async_event_config(aer->ctrlr,
649 			    aer->ctrlr->async_event_config, NULL, NULL);
650 		}
651 
652 
653 		/*
654 		 * Pass the cpl data from the original async event completion,
655 		 *  not the log page fetch.
656 		 */
657 		nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
658 		    aer->log_page_id, aer->log_page_buffer, aer->log_page_size);
659 	}
660 
661 	/*
662 	 * Repost another asynchronous event request to replace the one
663 	 *  that just completed.
664 	 */
665 	nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
666 }
667 
668 static void
669 nvme_ctrlr_async_event_cb(void *arg, const struct nvme_completion *cpl)
670 {
671 	struct nvme_async_event_request	*aer = arg;
672 
673 	if (nvme_completion_is_error(cpl)) {
674 		/*
675 		 *  Do not retry failed async event requests.  This avoids
676 		 *  infinite loops where a new async event request is submitted
677 		 *  to replace the one just failed, only to fail again and
678 		 *  perpetuate the loop.
679 		 */
680 		return;
681 	}
682 
683 	/* Associated log page is in bits 23:16 of completion entry dw0. */
684 	aer->log_page_id = (cpl->cdw0 & 0xFF0000) >> 16;
685 
686 	nvme_printf(aer->ctrlr, "async event occurred (log page id=0x%x)\n",
687 	    aer->log_page_id);
688 
689 	if (is_log_page_id_valid(aer->log_page_id)) {
690 		aer->log_page_size = nvme_ctrlr_get_log_page_size(aer->ctrlr,
691 		    aer->log_page_id);
692 		memcpy(&aer->cpl, cpl, sizeof(*cpl));
693 		nvme_ctrlr_cmd_get_log_page(aer->ctrlr, aer->log_page_id,
694 		    NVME_GLOBAL_NAMESPACE_TAG, aer->log_page_buffer,
695 		    aer->log_page_size, nvme_ctrlr_async_event_log_page_cb,
696 		    aer);
697 		/* Wait to notify consumers until after log page is fetched. */
698 	} else {
699 		nvme_notify_async_consumers(aer->ctrlr, cpl, aer->log_page_id,
700 		    NULL, 0);
701 
702 		/*
703 		 * Repost another asynchronous event request to replace the one
704 		 *  that just completed.
705 		 */
706 		nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
707 	}
708 }
709 
710 static void
711 nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
712     struct nvme_async_event_request *aer)
713 {
714 	struct nvme_request *req;
715 
716 	aer->ctrlr = ctrlr;
717 	req = nvme_allocate_request_null(nvme_ctrlr_async_event_cb, aer);
718 	aer->req = req;
719 
720 	/*
721 	 * Disable timeout here, since asynchronous event requests should by
722 	 *  nature never be timed out.
723 	 */
724 	req->timeout = FALSE;
725 	req->cmd.opc_fuse = NVME_CMD_SET_OPC(NVME_OPC_ASYNC_EVENT_REQUEST);
726 	nvme_ctrlr_submit_admin_request(ctrlr, req);
727 }
728 
729 static void
730 nvme_ctrlr_configure_aer(struct nvme_controller *ctrlr)
731 {
732 	struct nvme_completion_poll_status	status;
733 	struct nvme_async_event_request		*aer;
734 	uint32_t				i;
735 
736 	ctrlr->async_event_config = 0xFF;
737 	ctrlr->async_event_config &= ~NVME_CRIT_WARN_ST_RESERVED_MASK;
738 
739 	status.done = 0;
740 	nvme_ctrlr_cmd_get_feature(ctrlr, NVME_FEAT_TEMPERATURE_THRESHOLD,
741 	    0, NULL, 0, nvme_completion_poll_cb, &status);
742 	while (!atomic_load_acq_int(&status.done))
743 		pause("nvme", 1);
744 	if (nvme_completion_is_error(&status.cpl) ||
745 	    (status.cpl.cdw0 & 0xFFFF) == 0xFFFF ||
746 	    (status.cpl.cdw0 & 0xFFFF) == 0x0000) {
747 		nvme_printf(ctrlr, "temperature threshold not supported\n");
748 		ctrlr->async_event_config &= ~NVME_CRIT_WARN_ST_TEMPERATURE;
749 	}
750 
751 	nvme_ctrlr_cmd_set_async_event_config(ctrlr,
752 	    ctrlr->async_event_config, NULL, NULL);
753 
754 	/* aerl is a zero-based value, so we need to add 1 here. */
755 	ctrlr->num_aers = min(NVME_MAX_ASYNC_EVENTS, (ctrlr->cdata.aerl+1));
756 
757 	for (i = 0; i < ctrlr->num_aers; i++) {
758 		aer = &ctrlr->aer[i];
759 		nvme_ctrlr_construct_and_submit_aer(ctrlr, aer);
760 	}
761 }
762 
763 static void
764 nvme_ctrlr_configure_int_coalescing(struct nvme_controller *ctrlr)
765 {
766 
767 	ctrlr->int_coal_time = 0;
768 	TUNABLE_INT_FETCH("hw.nvme.int_coal_time",
769 	    &ctrlr->int_coal_time);
770 
771 	ctrlr->int_coal_threshold = 0;
772 	TUNABLE_INT_FETCH("hw.nvme.int_coal_threshold",
773 	    &ctrlr->int_coal_threshold);
774 
775 	nvme_ctrlr_cmd_set_interrupt_coalescing(ctrlr, ctrlr->int_coal_time,
776 	    ctrlr->int_coal_threshold, NULL, NULL);
777 }
778 
779 static void
780 nvme_ctrlr_start(void *ctrlr_arg)
781 {
782 	struct nvme_controller *ctrlr = ctrlr_arg;
783 	uint32_t old_num_io_queues;
784 	int i;
785 
786 	/*
787 	 * Only reset adminq here when we are restarting the
788 	 *  controller after a reset.  During initialization,
789 	 *  we have already submitted admin commands to get
790 	 *  the number of I/O queues supported, so cannot reset
791 	 *  the adminq again here.
792 	 */
793 	if (ctrlr->is_resetting) {
794 		nvme_qpair_reset(&ctrlr->adminq);
795 	}
796 
797 	for (i = 0; i < ctrlr->num_io_queues; i++)
798 		nvme_qpair_reset(&ctrlr->ioq[i]);
799 
800 	nvme_admin_qpair_enable(&ctrlr->adminq);
801 
802 	if (nvme_ctrlr_identify(ctrlr) != 0) {
803 		nvme_ctrlr_fail(ctrlr);
804 		return;
805 	}
806 
807 	/*
808 	 * The number of qpairs are determined during controller initialization,
809 	 *  including using NVMe SET_FEATURES/NUMBER_OF_QUEUES to determine the
810 	 *  HW limit.  We call SET_FEATURES again here so that it gets called
811 	 *  after any reset for controllers that depend on the driver to
812 	 *  explicit specify how many queues it will use.  This value should
813 	 *  never change between resets, so panic if somehow that does happen.
814 	 */
815 	if (ctrlr->is_resetting) {
816 		old_num_io_queues = ctrlr->num_io_queues;
817 		if (nvme_ctrlr_set_num_qpairs(ctrlr) != 0) {
818 			nvme_ctrlr_fail(ctrlr);
819 			return;
820 		}
821 
822 		if (old_num_io_queues != ctrlr->num_io_queues) {
823 			panic("num_io_queues changed from %u to %u",
824 			      old_num_io_queues, ctrlr->num_io_queues);
825 		}
826 	}
827 
828 	if (nvme_ctrlr_create_qpairs(ctrlr) != 0) {
829 		nvme_ctrlr_fail(ctrlr);
830 		return;
831 	}
832 
833 	if (nvme_ctrlr_construct_namespaces(ctrlr) != 0) {
834 		nvme_ctrlr_fail(ctrlr);
835 		return;
836 	}
837 
838 	nvme_ctrlr_configure_aer(ctrlr);
839 	nvme_ctrlr_configure_int_coalescing(ctrlr);
840 
841 	for (i = 0; i < ctrlr->num_io_queues; i++)
842 		nvme_io_qpair_enable(&ctrlr->ioq[i]);
843 }
844 
845 void
846 nvme_ctrlr_start_config_hook(void *arg)
847 {
848 	struct nvme_controller *ctrlr = arg;
849 
850 	nvme_qpair_reset(&ctrlr->adminq);
851 	nvme_admin_qpair_enable(&ctrlr->adminq);
852 
853 	if (nvme_ctrlr_set_num_qpairs(ctrlr) == 0 &&
854 	    nvme_ctrlr_construct_io_qpairs(ctrlr) == 0)
855 		nvme_ctrlr_start(ctrlr);
856 	else
857 		nvme_ctrlr_fail(ctrlr);
858 
859 	nvme_sysctl_initialize_ctrlr(ctrlr);
860 	config_intrhook_disestablish(&ctrlr->config_hook);
861 
862 	ctrlr->is_initialized = 1;
863 	nvme_notify_new_controller(ctrlr);
864 }
865 
866 static void
867 nvme_ctrlr_reset_task(void *arg, int pending)
868 {
869 	struct nvme_controller	*ctrlr = arg;
870 	int			status;
871 
872 	nvme_printf(ctrlr, "resetting controller\n");
873 	status = nvme_ctrlr_hw_reset(ctrlr);
874 	/*
875 	 * Use pause instead of DELAY, so that we yield to any nvme interrupt
876 	 *  handlers on this CPU that were blocked on a qpair lock. We want
877 	 *  all nvme interrupts completed before proceeding with restarting the
878 	 *  controller.
879 	 *
880 	 * XXX - any way to guarantee the interrupt handlers have quiesced?
881 	 */
882 	pause("nvmereset", hz / 10);
883 	if (status == 0)
884 		nvme_ctrlr_start(ctrlr);
885 	else
886 		nvme_ctrlr_fail(ctrlr);
887 
888 	atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
889 }
890 
891 /*
892  * Poll all the queues enabled on the device for completion.
893  */
894 void
895 nvme_ctrlr_poll(struct nvme_controller *ctrlr)
896 {
897 	int i;
898 
899 	nvme_qpair_process_completions(&ctrlr->adminq);
900 
901 	for (i = 0; i < ctrlr->num_io_queues; i++)
902 		if (ctrlr->ioq && ctrlr->ioq[i].cpl)
903 			nvme_qpair_process_completions(&ctrlr->ioq[i]);
904 }
905 
906 /*
907  * Poll the single-vector intertrupt case: num_io_queues will be 1 and
908  * there's only a single vector. While we're polling, we mask further
909  * interrupts in the controller.
910  */
911 void
912 nvme_ctrlr_intx_handler(void *arg)
913 {
914 	struct nvme_controller *ctrlr = arg;
915 
916 	nvme_mmio_write_4(ctrlr, intms, 1);
917 	nvme_ctrlr_poll(ctrlr);
918 	nvme_mmio_write_4(ctrlr, intmc, 1);
919 }
920 
921 static int
922 nvme_ctrlr_configure_intx(struct nvme_controller *ctrlr)
923 {
924 
925 	ctrlr->msix_enabled = 0;
926 	ctrlr->num_io_queues = 1;
927 	ctrlr->num_cpus_per_ioq = mp_ncpus;
928 	ctrlr->rid = 0;
929 	ctrlr->res = bus_alloc_resource_any(ctrlr->dev, SYS_RES_IRQ,
930 	    &ctrlr->rid, RF_SHAREABLE | RF_ACTIVE);
931 
932 	if (ctrlr->res == NULL) {
933 		nvme_printf(ctrlr, "unable to allocate shared IRQ\n");
934 		return (ENOMEM);
935 	}
936 
937 	bus_setup_intr(ctrlr->dev, ctrlr->res,
938 	    INTR_TYPE_MISC | INTR_MPSAFE, NULL, nvme_ctrlr_intx_handler,
939 	    ctrlr, &ctrlr->tag);
940 
941 	if (ctrlr->tag == NULL) {
942 		nvme_printf(ctrlr, "unable to setup intx handler\n");
943 		return (ENOMEM);
944 	}
945 
946 	return (0);
947 }
948 
949 static void
950 nvme_pt_done(void *arg, const struct nvme_completion *cpl)
951 {
952 	struct nvme_pt_command *pt = arg;
953 	uint16_t status;
954 
955 	bzero(&pt->cpl, sizeof(pt->cpl));
956 	pt->cpl.cdw0 = cpl->cdw0;
957 
958 	status = cpl->status;
959 	status &= ~NVME_STATUS_P_MASK;
960 	pt->cpl.status = status;
961 
962 	mtx_lock(pt->driver_lock);
963 	wakeup(pt);
964 	mtx_unlock(pt->driver_lock);
965 }
966 
967 int
968 nvme_ctrlr_passthrough_cmd(struct nvme_controller *ctrlr,
969     struct nvme_pt_command *pt, uint32_t nsid, int is_user_buffer,
970     int is_admin_cmd)
971 {
972 	struct nvme_request	*req;
973 	struct mtx		*mtx;
974 	struct buf		*buf = NULL;
975 	int			ret = 0;
976 	vm_offset_t		addr, end;
977 
978 	if (pt->len > 0) {
979 		/*
980 		 * vmapbuf calls vm_fault_quick_hold_pages which only maps full
981 		 * pages. Ensure this request has fewer than MAXPHYS bytes when
982 		 * extended to full pages.
983 		 */
984 		addr = (vm_offset_t)pt->buf;
985 		end = round_page(addr + pt->len);
986 		addr = trunc_page(addr);
987 		if (end - addr > MAXPHYS)
988 			return EIO;
989 
990 		if (pt->len > ctrlr->max_xfer_size) {
991 			nvme_printf(ctrlr, "pt->len (%d) "
992 			    "exceeds max_xfer_size (%d)\n", pt->len,
993 			    ctrlr->max_xfer_size);
994 			return EIO;
995 		}
996 		if (is_user_buffer) {
997 			/*
998 			 * Ensure the user buffer is wired for the duration of
999 			 *  this passthrough command.
1000 			 */
1001 			PHOLD(curproc);
1002 			buf = getpbuf(NULL);
1003 			buf->b_data = pt->buf;
1004 			buf->b_bufsize = pt->len;
1005 			buf->b_iocmd = pt->is_read ? BIO_READ : BIO_WRITE;
1006 #ifdef NVME_UNMAPPED_BIO_SUPPORT
1007 			if (vmapbuf(buf, 1) < 0) {
1008 #else
1009 			if (vmapbuf(buf) < 0) {
1010 #endif
1011 				ret = EFAULT;
1012 				goto err;
1013 			}
1014 			req = nvme_allocate_request_vaddr(buf->b_data, pt->len,
1015 			    nvme_pt_done, pt);
1016 		} else
1017 			req = nvme_allocate_request_vaddr(pt->buf, pt->len,
1018 			    nvme_pt_done, pt);
1019 	} else
1020 		req = nvme_allocate_request_null(nvme_pt_done, pt);
1021 
1022 	/* Assume userspace already converted to little-endian */
1023 	req->cmd.opc_fuse = pt->cmd.opc_fuse;
1024 	req->cmd.cdw10 = pt->cmd.cdw10;
1025 	req->cmd.cdw11 = pt->cmd.cdw11;
1026 	req->cmd.cdw12 = pt->cmd.cdw12;
1027 	req->cmd.cdw13 = pt->cmd.cdw13;
1028 	req->cmd.cdw14 = pt->cmd.cdw14;
1029 	req->cmd.cdw15 = pt->cmd.cdw15;
1030 
1031 	req->cmd.nsid = htole32(nsid);
1032 
1033 	if (is_admin_cmd)
1034 		mtx = &ctrlr->lock;
1035 	else {
1036 		KASSERT((nsid-1) >= 0 && (nsid-1) < NVME_MAX_NAMESPACES,
1037 		    ("%s: invalid namespace ID %d\n", __func__, nsid));
1038 		mtx = &ctrlr->ns[nsid-1].lock;
1039 	}
1040 
1041 	mtx_lock(mtx);
1042 	pt->driver_lock = mtx;
1043 
1044 	if (is_admin_cmd)
1045 		nvme_ctrlr_submit_admin_request(ctrlr, req);
1046 	else
1047 		nvme_ctrlr_submit_io_request(ctrlr, req);
1048 
1049 	mtx_sleep(pt, mtx, PRIBIO, "nvme_pt", 0);
1050 	mtx_unlock(mtx);
1051 
1052 	pt->driver_lock = NULL;
1053 
1054 err:
1055 	if (buf != NULL) {
1056 		relpbuf(buf, NULL);
1057 		PRELE(curproc);
1058 	}
1059 
1060 	return (ret);
1061 }
1062 
1063 static int
1064 nvme_ctrlr_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int flag,
1065     struct thread *td)
1066 {
1067 	struct nvme_controller			*ctrlr;
1068 	struct nvme_pt_command			*pt;
1069 
1070 	ctrlr = cdev->si_drv1;
1071 
1072 	switch (cmd) {
1073 	case NVME_RESET_CONTROLLER:
1074 		nvme_ctrlr_reset(ctrlr);
1075 		break;
1076 	case NVME_PASSTHROUGH_CMD:
1077 		pt = (struct nvme_pt_command *)arg;
1078 		return (nvme_ctrlr_passthrough_cmd(ctrlr, pt, le32toh(pt->cmd.nsid),
1079 		    1 /* is_user_buffer */, 1 /* is_admin_cmd */));
1080 	default:
1081 		return (ENOTTY);
1082 	}
1083 
1084 	return (0);
1085 }
1086 
1087 static struct cdevsw nvme_ctrlr_cdevsw = {
1088 	.d_version =	D_VERSION,
1089 	.d_flags =	0,
1090 	.d_ioctl =	nvme_ctrlr_ioctl
1091 };
1092 
1093 static void
1094 nvme_ctrlr_setup_interrupts(struct nvme_controller *ctrlr)
1095 {
1096 	device_t	dev;
1097 	int		per_cpu_io_queues;
1098 	int		min_cpus_per_ioq;
1099 	int		num_vectors_requested, num_vectors_allocated;
1100 	int		num_vectors_available;
1101 
1102 	dev = ctrlr->dev;
1103 	min_cpus_per_ioq = 1;
1104 	TUNABLE_INT_FETCH("hw.nvme.min_cpus_per_ioq", &min_cpus_per_ioq);
1105 
1106 	if (min_cpus_per_ioq < 1) {
1107 		min_cpus_per_ioq = 1;
1108 	} else if (min_cpus_per_ioq > mp_ncpus) {
1109 		min_cpus_per_ioq = mp_ncpus;
1110 	}
1111 
1112 	per_cpu_io_queues = 1;
1113 	TUNABLE_INT_FETCH("hw.nvme.per_cpu_io_queues", &per_cpu_io_queues);
1114 
1115 	if (per_cpu_io_queues == 0) {
1116 		min_cpus_per_ioq = mp_ncpus;
1117 	}
1118 
1119 	ctrlr->force_intx = 0;
1120 	TUNABLE_INT_FETCH("hw.nvme.force_intx", &ctrlr->force_intx);
1121 
1122 	/*
1123 	 * FreeBSD currently cannot allocate more than about 190 vectors at
1124 	 *  boot, meaning that systems with high core count and many devices
1125 	 *  requesting per-CPU interrupt vectors will not get their full
1126 	 *  allotment.  So first, try to allocate as many as we may need to
1127 	 *  understand what is available, then immediately release them.
1128 	 *  Then figure out how many of those we will actually use, based on
1129 	 *  assigning an equal number of cores to each I/O queue.
1130 	 */
1131 
1132 	/* One vector for per core I/O queue, plus one vector for admin queue. */
1133 	num_vectors_available = min(pci_msix_count(dev), mp_ncpus + 1);
1134 	if (pci_alloc_msix(dev, &num_vectors_available) != 0) {
1135 		num_vectors_available = 0;
1136 	}
1137 	pci_release_msi(dev);
1138 
1139 	if (ctrlr->force_intx || num_vectors_available < 2) {
1140 		nvme_ctrlr_configure_intx(ctrlr);
1141 		return;
1142 	}
1143 
1144 	/*
1145 	 * Do not use all vectors for I/O queues - one must be saved for the
1146 	 *  admin queue.
1147 	 */
1148 	ctrlr->num_cpus_per_ioq = max(min_cpus_per_ioq,
1149 	    howmany(mp_ncpus, num_vectors_available - 1));
1150 
1151 	ctrlr->num_io_queues = howmany(mp_ncpus, ctrlr->num_cpus_per_ioq);
1152 	num_vectors_requested = ctrlr->num_io_queues + 1;
1153 	num_vectors_allocated = num_vectors_requested;
1154 
1155 	/*
1156 	 * Now just allocate the number of vectors we need.  This should
1157 	 *  succeed, since we previously called pci_alloc_msix()
1158 	 *  successfully returning at least this many vectors, but just to
1159 	 *  be safe, if something goes wrong just revert to INTx.
1160 	 */
1161 	if (pci_alloc_msix(dev, &num_vectors_allocated) != 0) {
1162 		nvme_ctrlr_configure_intx(ctrlr);
1163 		return;
1164 	}
1165 
1166 	if (num_vectors_allocated < num_vectors_requested) {
1167 		pci_release_msi(dev);
1168 		nvme_ctrlr_configure_intx(ctrlr);
1169 		return;
1170 	}
1171 
1172 	ctrlr->msix_enabled = 1;
1173 }
1174 
1175 int
1176 nvme_ctrlr_construct(struct nvme_controller *ctrlr, device_t dev)
1177 {
1178 	uint32_t	cap_lo;
1179 	uint32_t	cap_hi;
1180 	uint8_t		to;
1181 	uint8_t		dstrd;
1182 	uint8_t		mpsmin;
1183 	int		status, timeout_period;
1184 
1185 	ctrlr->dev = dev;
1186 
1187 	mtx_init(&ctrlr->lock, "nvme ctrlr lock", NULL, MTX_DEF);
1188 
1189 	status = nvme_ctrlr_allocate_bar(ctrlr);
1190 
1191 	if (status != 0)
1192 		return (status);
1193 
1194 	/*
1195 	 * Software emulators may set the doorbell stride to something
1196 	 *  other than zero, but this driver is not set up to handle that.
1197 	 */
1198 	cap_hi = nvme_mmio_read_4(ctrlr, cap_hi);
1199 	dstrd = (cap_hi >> NVME_CAP_HI_REG_DSTRD_SHIFT) & NVME_CAP_HI_REG_DSTRD_MASK;
1200 	if (dstrd != 0)
1201 		return (ENXIO);
1202 
1203 	mpsmin = (cap_hi >> NVME_CAP_HI_REG_MPSMIN_SHIFT) & NVME_CAP_HI_REG_MPSMIN_MASK;
1204 	ctrlr->min_page_size = 1 << (12 + mpsmin);
1205 
1206 	/* Get ready timeout value from controller, in units of 500ms. */
1207 	cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
1208 	to = (cap_lo >> NVME_CAP_LO_REG_TO_SHIFT) & NVME_CAP_LO_REG_TO_MASK;
1209 	ctrlr->ready_timeout_in_ms = to * 500;
1210 
1211 	timeout_period = NVME_DEFAULT_TIMEOUT_PERIOD;
1212 	TUNABLE_INT_FETCH("hw.nvme.timeout_period", &timeout_period);
1213 	timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1214 	timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1215 	ctrlr->timeout_period = timeout_period;
1216 
1217 	nvme_retry_count = NVME_DEFAULT_RETRY_COUNT;
1218 	TUNABLE_INT_FETCH("hw.nvme.retry_count", &nvme_retry_count);
1219 
1220 	ctrlr->enable_aborts = 0;
1221 	TUNABLE_INT_FETCH("hw.nvme.enable_aborts", &ctrlr->enable_aborts);
1222 
1223 	nvme_ctrlr_setup_interrupts(ctrlr);
1224 
1225 	ctrlr->max_xfer_size = NVME_MAX_XFER_SIZE;
1226 	if (nvme_ctrlr_construct_admin_qpair(ctrlr) != 0)
1227 		return (ENXIO);
1228 
1229 	ctrlr->cdev = make_dev(&nvme_ctrlr_cdevsw, device_get_unit(dev),
1230 	    UID_ROOT, GID_WHEEL, 0600, "nvme%d", device_get_unit(dev));
1231 
1232 	if (ctrlr->cdev == NULL)
1233 		return (ENXIO);
1234 
1235 	ctrlr->cdev->si_drv1 = (void *)ctrlr;
1236 
1237 	ctrlr->taskqueue = taskqueue_create("nvme_taskq", M_WAITOK,
1238 	    taskqueue_thread_enqueue, &ctrlr->taskqueue);
1239 	taskqueue_start_threads(&ctrlr->taskqueue, 1, PI_DISK, "nvme taskq");
1240 
1241 	ctrlr->is_resetting = 0;
1242 	ctrlr->is_initialized = 0;
1243 	ctrlr->notification_sent = 0;
1244 	TASK_INIT(&ctrlr->reset_task, 0, nvme_ctrlr_reset_task, ctrlr);
1245 
1246 	TASK_INIT(&ctrlr->fail_req_task, 0, nvme_ctrlr_fail_req_task, ctrlr);
1247 	STAILQ_INIT(&ctrlr->fail_req);
1248 	ctrlr->is_failed = FALSE;
1249 
1250 	return (0);
1251 }
1252 
1253 void
1254 nvme_ctrlr_destruct(struct nvme_controller *ctrlr, device_t dev)
1255 {
1256 	int				i;
1257 
1258 	/*
1259 	 *  Notify the controller of a shutdown, even though this is due to
1260 	 *   a driver unload, not a system shutdown (this path is not invoked
1261 	 *   during shutdown).  This ensures the controller receives a
1262 	 *   shutdown notification in case the system is shutdown before
1263 	 *   reloading the driver.
1264 	 */
1265 	nvme_ctrlr_shutdown(ctrlr);
1266 
1267 	nvme_ctrlr_disable(ctrlr);
1268 	taskqueue_free(ctrlr->taskqueue);
1269 
1270 	for (i = 0; i < NVME_MAX_NAMESPACES; i++)
1271 		nvme_ns_destruct(&ctrlr->ns[i]);
1272 
1273 	if (ctrlr->cdev)
1274 		destroy_dev(ctrlr->cdev);
1275 
1276 	for (i = 0; i < ctrlr->num_io_queues; i++) {
1277 		nvme_io_qpair_destroy(&ctrlr->ioq[i]);
1278 	}
1279 
1280 	free(ctrlr->ioq, M_NVME);
1281 
1282 	nvme_admin_qpair_destroy(&ctrlr->adminq);
1283 
1284 	if (ctrlr->resource != NULL) {
1285 		bus_release_resource(dev, SYS_RES_MEMORY,
1286 		    ctrlr->resource_id, ctrlr->resource);
1287 	}
1288 
1289 	if (ctrlr->bar4_resource != NULL) {
1290 		bus_release_resource(dev, SYS_RES_MEMORY,
1291 		    ctrlr->bar4_resource_id, ctrlr->bar4_resource);
1292 	}
1293 
1294 	if (ctrlr->tag)
1295 		bus_teardown_intr(ctrlr->dev, ctrlr->res, ctrlr->tag);
1296 
1297 	if (ctrlr->res)
1298 		bus_release_resource(ctrlr->dev, SYS_RES_IRQ,
1299 		    rman_get_rid(ctrlr->res), ctrlr->res);
1300 
1301 	if (ctrlr->msix_enabled)
1302 		pci_release_msi(dev);
1303 }
1304 
1305 void
1306 nvme_ctrlr_shutdown(struct nvme_controller *ctrlr)
1307 {
1308 	uint32_t	cc;
1309 	uint32_t	csts;
1310 	int		ticks = 0;
1311 
1312 	cc = nvme_mmio_read_4(ctrlr, cc);
1313 	cc &= ~(NVME_CC_REG_SHN_MASK << NVME_CC_REG_SHN_SHIFT);
1314 	cc |= NVME_SHN_NORMAL << NVME_CC_REG_SHN_SHIFT;
1315 	nvme_mmio_write_4(ctrlr, cc, cc);
1316 
1317 	csts = nvme_mmio_read_4(ctrlr, csts);
1318 	while ((NVME_CSTS_GET_SHST(csts) != NVME_SHST_COMPLETE) && (ticks++ < 5*hz)) {
1319 		pause("nvme shn", 1);
1320 		csts = nvme_mmio_read_4(ctrlr, csts);
1321 	}
1322 	if (NVME_CSTS_GET_SHST(csts) != NVME_SHST_COMPLETE)
1323 		nvme_printf(ctrlr, "did not complete shutdown within 5 seconds "
1324 		    "of notification\n");
1325 }
1326 
1327 void
1328 nvme_ctrlr_submit_admin_request(struct nvme_controller *ctrlr,
1329     struct nvme_request *req)
1330 {
1331 
1332 	nvme_qpair_submit_request(&ctrlr->adminq, req);
1333 }
1334 
1335 void
1336 nvme_ctrlr_submit_io_request(struct nvme_controller *ctrlr,
1337     struct nvme_request *req)
1338 {
1339 	struct nvme_qpair       *qpair;
1340 
1341 	qpair = &ctrlr->ioq[curcpu / ctrlr->num_cpus_per_ioq];
1342 	nvme_qpair_submit_request(qpair, req);
1343 }
1344 
1345 device_t
1346 nvme_ctrlr_get_device(struct nvme_controller *ctrlr)
1347 {
1348 
1349 	return (ctrlr->dev);
1350 }
1351 
1352 const struct nvme_controller_data *
1353 nvme_ctrlr_get_data(struct nvme_controller *ctrlr)
1354 {
1355 
1356 	return (&ctrlr->cdata);
1357 }
1358