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