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