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