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