]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/nvme/nvme_ctrlr.c
MFC r343755:
[FreeBSD/FreeBSD.git] / sys / dev / nvme / nvme_ctrlr.c
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
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
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          * noramlly have in flight at one time. This should be viewed as a hint,
122          * not a hard limit and will need to be revisitted 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
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
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
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
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
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
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 int
348 nvme_ctrlr_hw_reset(struct nvme_controller *ctrlr)
349 {
350         int i, err;
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         DELAY(100*1000);
364
365         err = nvme_ctrlr_disable(ctrlr);
366         if (err != 0)
367                 return err;
368         return (nvme_ctrlr_enable(ctrlr));
369 }
370
371 void
372 nvme_ctrlr_reset(struct nvme_controller *ctrlr)
373 {
374         int cmpset;
375
376         cmpset = atomic_cmpset_32(&ctrlr->is_resetting, 0, 1);
377
378         if (cmpset == 0 || ctrlr->is_failed)
379                 /*
380                  * Controller is already resetting or has failed.  Return
381                  *  immediately since there is no need to kick off another
382                  *  reset in these cases.
383                  */
384                 return;
385
386         taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->reset_task);
387 }
388
389 static int
390 nvme_ctrlr_identify(struct nvme_controller *ctrlr)
391 {
392         struct nvme_completion_poll_status      status;
393
394         status.done = 0;
395         nvme_ctrlr_cmd_identify_controller(ctrlr, &ctrlr->cdata,
396             nvme_completion_poll_cb, &status);
397         nvme_completion_poll(&status);
398         if (nvme_completion_is_error(&status.cpl)) {
399                 nvme_printf(ctrlr, "nvme_identify_controller failed!\n");
400                 return (ENXIO);
401         }
402
403         /* Convert data to host endian */
404         nvme_controller_data_swapbytes(&ctrlr->cdata);
405
406         /*
407          * Use MDTS to ensure our default max_xfer_size doesn't exceed what the
408          *  controller supports.
409          */
410         if (ctrlr->cdata.mdts > 0)
411                 ctrlr->max_xfer_size = min(ctrlr->max_xfer_size,
412                     ctrlr->min_page_size * (1 << (ctrlr->cdata.mdts)));
413
414         return (0);
415 }
416
417 static int
418 nvme_ctrlr_set_num_qpairs(struct nvme_controller *ctrlr)
419 {
420         struct nvme_completion_poll_status      status;
421         int                                     cq_allocated, sq_allocated;
422
423         status.done = 0;
424         nvme_ctrlr_cmd_set_num_queues(ctrlr, ctrlr->num_io_queues,
425             nvme_completion_poll_cb, &status);
426         nvme_completion_poll(&status);
427         if (nvme_completion_is_error(&status.cpl)) {
428                 nvme_printf(ctrlr, "nvme_ctrlr_set_num_qpairs failed!\n");
429                 return (ENXIO);
430         }
431
432         /*
433          * Data in cdw0 is 0-based.
434          * Lower 16-bits indicate number of submission queues allocated.
435          * Upper 16-bits indicate number of completion queues allocated.
436          */
437         sq_allocated = (status.cpl.cdw0 & 0xFFFF) + 1;
438         cq_allocated = (status.cpl.cdw0 >> 16) + 1;
439
440         /*
441          * Controller may allocate more queues than we requested,
442          *  so use the minimum of the number requested and what was
443          *  actually allocated.
444          */
445         ctrlr->num_io_queues = min(ctrlr->num_io_queues, sq_allocated);
446         ctrlr->num_io_queues = min(ctrlr->num_io_queues, cq_allocated);
447
448         return (0);
449 }
450
451 static int
452 nvme_ctrlr_create_qpairs(struct nvme_controller *ctrlr)
453 {
454         struct nvme_completion_poll_status      status;
455         struct nvme_qpair                       *qpair;
456         int                                     i;
457
458         for (i = 0; i < ctrlr->num_io_queues; i++) {
459                 qpair = &ctrlr->ioq[i];
460
461                 status.done = 0;
462                 nvme_ctrlr_cmd_create_io_cq(ctrlr, qpair, qpair->vector,
463                     nvme_completion_poll_cb, &status);
464                 nvme_completion_poll(&status);
465                 if (nvme_completion_is_error(&status.cpl)) {
466                         nvme_printf(ctrlr, "nvme_create_io_cq failed!\n");
467                         return (ENXIO);
468                 }
469
470                 status.done = 0;
471                 nvme_ctrlr_cmd_create_io_sq(qpair->ctrlr, qpair,
472                     nvme_completion_poll_cb, &status);
473                 nvme_completion_poll(&status);
474                 if (nvme_completion_is_error(&status.cpl)) {
475                         nvme_printf(ctrlr, "nvme_create_io_sq failed!\n");
476                         return (ENXIO);
477                 }
478         }
479
480         return (0);
481 }
482
483 static int
484 nvme_ctrlr_destroy_qpairs(struct nvme_controller *ctrlr)
485 {
486         struct nvme_completion_poll_status      status;
487         struct nvme_qpair                       *qpair;
488
489         for (int i = 0; i < ctrlr->num_io_queues; i++) {
490                 qpair = &ctrlr->ioq[i];
491
492                 status.done = 0;
493                 nvme_ctrlr_cmd_delete_io_sq(ctrlr, qpair,
494                     nvme_completion_poll_cb, &status);
495                 nvme_completion_poll(&status);
496                 if (nvme_completion_is_error(&status.cpl)) {
497                         nvme_printf(ctrlr, "nvme_destroy_io_sq failed!\n");
498                         return (ENXIO);
499                 }
500
501                 status.done = 0;
502                 nvme_ctrlr_cmd_delete_io_cq(ctrlr, qpair,
503                     nvme_completion_poll_cb, &status);
504                 nvme_completion_poll(&status);
505                 if (nvme_completion_is_error(&status.cpl)) {
506                         nvme_printf(ctrlr, "nvme_destroy_io_cq failed!\n");
507                         return (ENXIO);
508                 }
509         }
510
511         return (0);
512 }
513
514 static int
515 nvme_ctrlr_construct_namespaces(struct nvme_controller *ctrlr)
516 {
517         struct nvme_namespace   *ns;
518         uint32_t                i;
519
520         for (i = 0; i < min(ctrlr->cdata.nn, NVME_MAX_NAMESPACES); i++) {
521                 ns = &ctrlr->ns[i];
522                 nvme_ns_construct(ns, i+1, ctrlr);
523         }
524
525         return (0);
526 }
527
528 static boolean_t
529 is_log_page_id_valid(uint8_t page_id)
530 {
531
532         switch (page_id) {
533         case NVME_LOG_ERROR:
534         case NVME_LOG_HEALTH_INFORMATION:
535         case NVME_LOG_FIRMWARE_SLOT:
536         case NVME_LOG_CHANGED_NAMESPACE:
537         case NVME_LOG_COMMAND_EFFECT:
538         case NVME_LOG_RES_NOTIFICATION:
539         case NVME_LOG_SANITIZE_STATUS:
540                 return (TRUE);
541         }
542
543         return (FALSE);
544 }
545
546 static uint32_t
547 nvme_ctrlr_get_log_page_size(struct nvme_controller *ctrlr, uint8_t page_id)
548 {
549         uint32_t        log_page_size;
550
551         switch (page_id) {
552         case NVME_LOG_ERROR:
553                 log_page_size = min(
554                     sizeof(struct nvme_error_information_entry) *
555                     (ctrlr->cdata.elpe + 1), NVME_MAX_AER_LOG_SIZE);
556                 break;
557         case NVME_LOG_HEALTH_INFORMATION:
558                 log_page_size = sizeof(struct nvme_health_information_page);
559                 break;
560         case NVME_LOG_FIRMWARE_SLOT:
561                 log_page_size = sizeof(struct nvme_firmware_page);
562                 break;
563         case NVME_LOG_CHANGED_NAMESPACE:
564                 log_page_size = sizeof(struct nvme_ns_list);
565                 break;
566         case NVME_LOG_COMMAND_EFFECT:
567                 log_page_size = sizeof(struct nvme_command_effects_page);
568                 break;
569         case NVME_LOG_RES_NOTIFICATION:
570                 log_page_size = sizeof(struct nvme_res_notification_page);
571                 break;
572         case NVME_LOG_SANITIZE_STATUS:
573                 log_page_size = sizeof(struct nvme_sanitize_status_page);
574                 break;
575         default:
576                 log_page_size = 0;
577                 break;
578         }
579
580         return (log_page_size);
581 }
582
583 static void
584 nvme_ctrlr_log_critical_warnings(struct nvme_controller *ctrlr,
585     uint8_t state)
586 {
587
588         if (state & NVME_CRIT_WARN_ST_AVAILABLE_SPARE)
589                 nvme_printf(ctrlr, "available spare space below threshold\n");
590
591         if (state & NVME_CRIT_WARN_ST_TEMPERATURE)
592                 nvme_printf(ctrlr, "temperature above threshold\n");
593
594         if (state & NVME_CRIT_WARN_ST_DEVICE_RELIABILITY)
595                 nvme_printf(ctrlr, "device reliability degraded\n");
596
597         if (state & NVME_CRIT_WARN_ST_READ_ONLY)
598                 nvme_printf(ctrlr, "media placed in read only mode\n");
599
600         if (state & NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP)
601                 nvme_printf(ctrlr, "volatile memory backup device failed\n");
602
603         if (state & NVME_CRIT_WARN_ST_RESERVED_MASK)
604                 nvme_printf(ctrlr,
605                     "unknown critical warning(s): state = 0x%02x\n", state);
606 }
607
608 static void
609 nvme_ctrlr_async_event_log_page_cb(void *arg, const struct nvme_completion *cpl)
610 {
611         struct nvme_async_event_request         *aer = arg;
612         struct nvme_health_information_page     *health_info;
613         struct nvme_ns_list                     *nsl;
614         struct nvme_error_information_entry     *err;
615         int i;
616
617         /*
618          * If the log page fetch for some reason completed with an error,
619          *  don't pass log page data to the consumers.  In practice, this case
620          *  should never happen.
621          */
622         if (nvme_completion_is_error(cpl))
623                 nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
624                     aer->log_page_id, NULL, 0);
625         else {
626                 /* Convert data to host endian */
627                 switch (aer->log_page_id) {
628                 case NVME_LOG_ERROR:
629                         err = (struct nvme_error_information_entry *)aer->log_page_buffer;
630                         for (i = 0; i < (aer->ctrlr->cdata.elpe + 1); i++)
631                                 nvme_error_information_entry_swapbytes(err++);
632                         break;
633                 case NVME_LOG_HEALTH_INFORMATION:
634                         nvme_health_information_page_swapbytes(
635                             (struct nvme_health_information_page *)aer->log_page_buffer);
636                         break;
637                 case NVME_LOG_FIRMWARE_SLOT:
638                         nvme_firmware_page_swapbytes(
639                             (struct nvme_firmware_page *)aer->log_page_buffer);
640                         break;
641                 case NVME_LOG_CHANGED_NAMESPACE:
642                         nvme_ns_list_swapbytes(
643                             (struct nvme_ns_list *)aer->log_page_buffer);
644                         break;
645                 case NVME_LOG_COMMAND_EFFECT:
646                         nvme_command_effects_page_swapbytes(
647                             (struct nvme_command_effects_page *)aer->log_page_buffer);
648                         break;
649                 case NVME_LOG_RES_NOTIFICATION:
650                         nvme_res_notification_page_swapbytes(
651                             (struct nvme_res_notification_page *)aer->log_page_buffer);
652                         break;
653                 case NVME_LOG_SANITIZE_STATUS:
654                         nvme_sanitize_status_page_swapbytes(
655                             (struct nvme_sanitize_status_page *)aer->log_page_buffer);
656                         break;
657                 case INTEL_LOG_TEMP_STATS:
658                         intel_log_temp_stats_swapbytes(
659                             (struct intel_log_temp_stats *)aer->log_page_buffer);
660                         break;
661                 default:
662                         break;
663                 }
664
665                 if (aer->log_page_id == NVME_LOG_HEALTH_INFORMATION) {
666                         health_info = (struct nvme_health_information_page *)
667                             aer->log_page_buffer;
668                         nvme_ctrlr_log_critical_warnings(aer->ctrlr,
669                             health_info->critical_warning);
670                         /*
671                          * Critical warnings reported through the
672                          *  SMART/health log page are persistent, so
673                          *  clear the associated bits in the async event
674                          *  config so that we do not receive repeated
675                          *  notifications for the same event.
676                          */
677                         aer->ctrlr->async_event_config &=
678                             ~health_info->critical_warning;
679                         nvme_ctrlr_cmd_set_async_event_config(aer->ctrlr,
680                             aer->ctrlr->async_event_config, NULL, NULL);
681                 } else if (aer->log_page_id == NVME_LOG_CHANGED_NAMESPACE &&
682                     !nvme_use_nvd) {
683                         nsl = (struct nvme_ns_list *)aer->log_page_buffer;
684                         for (i = 0; i < nitems(nsl->ns) && nsl->ns[i] != 0; i++) {
685                                 if (nsl->ns[i] > NVME_MAX_NAMESPACES)
686                                         break;
687                                 nvme_notify_ns(aer->ctrlr, nsl->ns[i]);
688                         }
689                 }
690
691
692                 /*
693                  * Pass the cpl data from the original async event completion,
694                  *  not the log page fetch.
695                  */
696                 nvme_notify_async_consumers(aer->ctrlr, &aer->cpl,
697                     aer->log_page_id, aer->log_page_buffer, aer->log_page_size);
698         }
699
700         /*
701          * Repost another asynchronous event request to replace the one
702          *  that just completed.
703          */
704         nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
705 }
706
707 static void
708 nvme_ctrlr_async_event_cb(void *arg, const struct nvme_completion *cpl)
709 {
710         struct nvme_async_event_request *aer = arg;
711
712         if (nvme_completion_is_error(cpl)) {
713                 /*
714                  *  Do not retry failed async event requests.  This avoids
715                  *  infinite loops where a new async event request is submitted
716                  *  to replace the one just failed, only to fail again and
717                  *  perpetuate the loop.
718                  */
719                 return;
720         }
721
722         /* Associated log page is in bits 23:16 of completion entry dw0. */
723         aer->log_page_id = (cpl->cdw0 & 0xFF0000) >> 16;
724
725         nvme_printf(aer->ctrlr, "async event occurred (type 0x%x, info 0x%02x,"
726             " page 0x%02x)\n", (cpl->cdw0 & 0x07), (cpl->cdw0 & 0xFF00) >> 8,
727             aer->log_page_id);
728
729         if (is_log_page_id_valid(aer->log_page_id)) {
730                 aer->log_page_size = nvme_ctrlr_get_log_page_size(aer->ctrlr,
731                     aer->log_page_id);
732                 memcpy(&aer->cpl, cpl, sizeof(*cpl));
733                 nvme_ctrlr_cmd_get_log_page(aer->ctrlr, aer->log_page_id,
734                     NVME_GLOBAL_NAMESPACE_TAG, aer->log_page_buffer,
735                     aer->log_page_size, nvme_ctrlr_async_event_log_page_cb,
736                     aer);
737                 /* Wait to notify consumers until after log page is fetched. */
738         } else {
739                 nvme_notify_async_consumers(aer->ctrlr, cpl, aer->log_page_id,
740                     NULL, 0);
741
742                 /*
743                  * Repost another asynchronous event request to replace the one
744                  *  that just completed.
745                  */
746                 nvme_ctrlr_construct_and_submit_aer(aer->ctrlr, aer);
747         }
748 }
749
750 static void
751 nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
752     struct nvme_async_event_request *aer)
753 {
754         struct nvme_request *req;
755
756         aer->ctrlr = ctrlr;
757         req = nvme_allocate_request_null(nvme_ctrlr_async_event_cb, aer);
758         aer->req = req;
759
760         /*
761          * Disable timeout here, since asynchronous event requests should by
762          *  nature never be timed out.
763          */
764         req->timeout = FALSE;
765         req->cmd.opc = NVME_OPC_ASYNC_EVENT_REQUEST;
766         nvme_ctrlr_submit_admin_request(ctrlr, req);
767 }
768
769 static void
770 nvme_ctrlr_configure_aer(struct nvme_controller *ctrlr)
771 {
772         struct nvme_completion_poll_status      status;
773         struct nvme_async_event_request         *aer;
774         uint32_t                                i;
775
776         ctrlr->async_event_config = NVME_CRIT_WARN_ST_AVAILABLE_SPARE |
777             NVME_CRIT_WARN_ST_DEVICE_RELIABILITY |
778             NVME_CRIT_WARN_ST_READ_ONLY |
779             NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP;
780         if (ctrlr->cdata.ver >= NVME_REV(1, 2))
781                 ctrlr->async_event_config |= 0x300;
782
783         status.done = 0;
784         nvme_ctrlr_cmd_get_feature(ctrlr, NVME_FEAT_TEMPERATURE_THRESHOLD,
785             0, NULL, 0, nvme_completion_poll_cb, &status);
786         nvme_completion_poll(&status);
787         if (nvme_completion_is_error(&status.cpl) ||
788             (status.cpl.cdw0 & 0xFFFF) == 0xFFFF ||
789             (status.cpl.cdw0 & 0xFFFF) == 0x0000) {
790                 nvme_printf(ctrlr, "temperature threshold not supported\n");
791         } else
792                 ctrlr->async_event_config |= NVME_CRIT_WARN_ST_TEMPERATURE;
793
794         nvme_ctrlr_cmd_set_async_event_config(ctrlr,
795             ctrlr->async_event_config, NULL, NULL);
796
797         /* aerl is a zero-based value, so we need to add 1 here. */
798         ctrlr->num_aers = min(NVME_MAX_ASYNC_EVENTS, (ctrlr->cdata.aerl+1));
799
800         for (i = 0; i < ctrlr->num_aers; i++) {
801                 aer = &ctrlr->aer[i];
802                 nvme_ctrlr_construct_and_submit_aer(ctrlr, aer);
803         }
804 }
805
806 static void
807 nvme_ctrlr_configure_int_coalescing(struct nvme_controller *ctrlr)
808 {
809
810         ctrlr->int_coal_time = 0;
811         TUNABLE_INT_FETCH("hw.nvme.int_coal_time",
812             &ctrlr->int_coal_time);
813
814         ctrlr->int_coal_threshold = 0;
815         TUNABLE_INT_FETCH("hw.nvme.int_coal_threshold",
816             &ctrlr->int_coal_threshold);
817
818         nvme_ctrlr_cmd_set_interrupt_coalescing(ctrlr, ctrlr->int_coal_time,
819             ctrlr->int_coal_threshold, NULL, NULL);
820 }
821
822 static void
823 nvme_ctrlr_start(void *ctrlr_arg)
824 {
825         struct nvme_controller *ctrlr = ctrlr_arg;
826         uint32_t old_num_io_queues;
827         int i;
828
829         /*
830          * Only reset adminq here when we are restarting the
831          *  controller after a reset.  During initialization,
832          *  we have already submitted admin commands to get
833          *  the number of I/O queues supported, so cannot reset
834          *  the adminq again here.
835          */
836         if (ctrlr->is_resetting)
837                 nvme_qpair_reset(&ctrlr->adminq);
838
839         for (i = 0; i < ctrlr->num_io_queues; i++)
840                 nvme_qpair_reset(&ctrlr->ioq[i]);
841
842         nvme_admin_qpair_enable(&ctrlr->adminq);
843
844         if (nvme_ctrlr_identify(ctrlr) != 0) {
845                 nvme_ctrlr_fail(ctrlr);
846                 return;
847         }
848
849         /*
850          * The number of qpairs are determined during controller initialization,
851          *  including using NVMe SET_FEATURES/NUMBER_OF_QUEUES to determine the
852          *  HW limit.  We call SET_FEATURES again here so that it gets called
853          *  after any reset for controllers that depend on the driver to
854          *  explicit specify how many queues it will use.  This value should
855          *  never change between resets, so panic if somehow that does happen.
856          */
857         if (ctrlr->is_resetting) {
858                 old_num_io_queues = ctrlr->num_io_queues;
859                 if (nvme_ctrlr_set_num_qpairs(ctrlr) != 0) {
860                         nvme_ctrlr_fail(ctrlr);
861                         return;
862                 }
863
864                 if (old_num_io_queues != ctrlr->num_io_queues) {
865                         panic("num_io_queues changed from %u to %u",
866                               old_num_io_queues, ctrlr->num_io_queues);
867                 }
868         }
869
870         if (nvme_ctrlr_create_qpairs(ctrlr) != 0) {
871                 nvme_ctrlr_fail(ctrlr);
872                 return;
873         }
874
875         if (nvme_ctrlr_construct_namespaces(ctrlr) != 0) {
876                 nvme_ctrlr_fail(ctrlr);
877                 return;
878         }
879
880         nvme_ctrlr_configure_aer(ctrlr);
881         nvme_ctrlr_configure_int_coalescing(ctrlr);
882
883         for (i = 0; i < ctrlr->num_io_queues; i++)
884                 nvme_io_qpair_enable(&ctrlr->ioq[i]);
885 }
886
887 void
888 nvme_ctrlr_start_config_hook(void *arg)
889 {
890         struct nvme_controller *ctrlr = arg;
891
892         nvme_qpair_reset(&ctrlr->adminq);
893         nvme_admin_qpair_enable(&ctrlr->adminq);
894
895         if (nvme_ctrlr_set_num_qpairs(ctrlr) == 0 &&
896             nvme_ctrlr_construct_io_qpairs(ctrlr) == 0)
897                 nvme_ctrlr_start(ctrlr);
898         else
899                 nvme_ctrlr_fail(ctrlr);
900
901         nvme_sysctl_initialize_ctrlr(ctrlr);
902         config_intrhook_disestablish(&ctrlr->config_hook);
903
904         ctrlr->is_initialized = 1;
905         nvme_notify_new_controller(ctrlr);
906 }
907
908 static void
909 nvme_ctrlr_reset_task(void *arg, int pending)
910 {
911         struct nvme_controller  *ctrlr = arg;
912         int                     status;
913
914         nvme_printf(ctrlr, "resetting controller\n");
915         status = nvme_ctrlr_hw_reset(ctrlr);
916         /*
917          * Use pause instead of DELAY, so that we yield to any nvme interrupt
918          *  handlers on this CPU that were blocked on a qpair lock. We want
919          *  all nvme interrupts completed before proceeding with restarting the
920          *  controller.
921          *
922          * XXX - any way to guarantee the interrupt handlers have quiesced?
923          */
924         pause("nvmereset", hz / 10);
925         if (status == 0)
926                 nvme_ctrlr_start(ctrlr);
927         else
928                 nvme_ctrlr_fail(ctrlr);
929
930         atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
931 }
932
933 /*
934  * Poll all the queues enabled on the device for completion.
935  */
936 void
937 nvme_ctrlr_poll(struct nvme_controller *ctrlr)
938 {
939         int i;
940
941         nvme_qpair_process_completions(&ctrlr->adminq);
942
943         for (i = 0; i < ctrlr->num_io_queues; i++)
944                 if (ctrlr->ioq && ctrlr->ioq[i].cpl)
945                         nvme_qpair_process_completions(&ctrlr->ioq[i]);
946 }
947
948 /*
949  * Poll the single-vector intertrupt case: num_io_queues will be 1 and
950  * there's only a single vector. While we're polling, we mask further
951  * interrupts in the controller.
952  */
953 void
954 nvme_ctrlr_intx_handler(void *arg)
955 {
956         struct nvme_controller *ctrlr = arg;
957
958         nvme_mmio_write_4(ctrlr, intms, 1);
959         nvme_ctrlr_poll(ctrlr);
960         nvme_mmio_write_4(ctrlr, intmc, 1);
961 }
962
963 static void
964 nvme_pt_done(void *arg, const struct nvme_completion *cpl)
965 {
966         struct nvme_pt_command *pt = arg;
967         struct mtx *mtx = pt->driver_lock;
968         uint16_t status;
969
970         bzero(&pt->cpl, sizeof(pt->cpl));
971         pt->cpl.cdw0 = cpl->cdw0;
972
973         status = cpl->status;
974         status &= ~NVME_STATUS_P_MASK;
975         pt->cpl.status = status;
976
977         mtx_lock(mtx);
978         pt->driver_lock = NULL;
979         wakeup(pt);
980         mtx_unlock(mtx);
981 }
982
983 int
984 nvme_ctrlr_passthrough_cmd(struct nvme_controller *ctrlr,
985     struct nvme_pt_command *pt, uint32_t nsid, int is_user_buffer,
986     int is_admin_cmd)
987 {
988         struct nvme_request     *req;
989         struct mtx              *mtx;
990         struct buf              *buf = NULL;
991         int                     ret = 0;
992         vm_offset_t             addr, end;
993
994         if (pt->len > 0) {
995                 /*
996                  * vmapbuf calls vm_fault_quick_hold_pages which only maps full
997                  * pages. Ensure this request has fewer than MAXPHYS bytes when
998                  * extended to full pages.
999                  */
1000                 addr = (vm_offset_t)pt->buf;
1001                 end = round_page(addr + pt->len);
1002                 addr = trunc_page(addr);
1003                 if (end - addr > MAXPHYS)
1004                         return EIO;
1005
1006                 if (pt->len > ctrlr->max_xfer_size) {
1007                         nvme_printf(ctrlr, "pt->len (%d) "
1008                             "exceeds max_xfer_size (%d)\n", pt->len,
1009                             ctrlr->max_xfer_size);
1010                         return EIO;
1011                 }
1012                 if (is_user_buffer) {
1013                         /*
1014                          * Ensure the user buffer is wired for the duration of
1015                          *  this passthrough command.
1016                          */
1017                         PHOLD(curproc);
1018                         buf = getpbuf(NULL);
1019                         buf->b_data = pt->buf;
1020                         buf->b_bufsize = pt->len;
1021                         buf->b_iocmd = pt->is_read ? BIO_READ : BIO_WRITE;
1022                         if (vmapbuf(buf, 1) < 0) {
1023                                 ret = EFAULT;
1024                                 goto err;
1025                         }
1026                         req = nvme_allocate_request_vaddr(buf->b_data, pt->len, 
1027                             nvme_pt_done, pt);
1028                 } else
1029                         req = nvme_allocate_request_vaddr(pt->buf, pt->len,
1030                             nvme_pt_done, pt);
1031         } else
1032                 req = nvme_allocate_request_null(nvme_pt_done, pt);
1033
1034         /* Assume userspace already converted to little-endian */
1035         req->cmd.opc = pt->cmd.opc;
1036         req->cmd.fuse = pt->cmd.fuse;
1037         req->cmd.rsvd2 = pt->cmd.rsvd2;
1038         req->cmd.rsvd3 = pt->cmd.rsvd3;
1039         req->cmd.cdw10 = pt->cmd.cdw10;
1040         req->cmd.cdw11 = pt->cmd.cdw11;
1041         req->cmd.cdw12 = pt->cmd.cdw12;
1042         req->cmd.cdw13 = pt->cmd.cdw13;
1043         req->cmd.cdw14 = pt->cmd.cdw14;
1044         req->cmd.cdw15 = pt->cmd.cdw15;
1045
1046         req->cmd.nsid = htole32(nsid);
1047
1048         mtx = mtx_pool_find(mtxpool_sleep, pt);
1049         pt->driver_lock = mtx;
1050
1051         if (is_admin_cmd)
1052                 nvme_ctrlr_submit_admin_request(ctrlr, req);
1053         else
1054                 nvme_ctrlr_submit_io_request(ctrlr, req);
1055
1056         mtx_lock(mtx);
1057         while (pt->driver_lock != NULL)
1058                 mtx_sleep(pt, mtx, PRIBIO, "nvme_pt", 0);
1059         mtx_unlock(mtx);
1060
1061 err:
1062         if (buf != NULL) {
1063                 relpbuf(buf, NULL);
1064                 PRELE(curproc);
1065         }
1066
1067         return (ret);
1068 }
1069
1070 static int
1071 nvme_ctrlr_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int flag,
1072     struct thread *td)
1073 {
1074         struct nvme_controller                  *ctrlr;
1075         struct nvme_pt_command                  *pt;
1076
1077         ctrlr = cdev->si_drv1;
1078
1079         switch (cmd) {
1080         case NVME_RESET_CONTROLLER:
1081                 nvme_ctrlr_reset(ctrlr);
1082                 break;
1083         case NVME_PASSTHROUGH_CMD:
1084                 pt = (struct nvme_pt_command *)arg;
1085                 return (nvme_ctrlr_passthrough_cmd(ctrlr, pt, le32toh(pt->cmd.nsid),
1086                     1 /* is_user_buffer */, 1 /* is_admin_cmd */));
1087         case NVME_GET_NSID:
1088         {
1089                 struct nvme_get_nsid *gnsid = (struct nvme_get_nsid *)arg;
1090                 strncpy(gnsid->cdev, device_get_nameunit(ctrlr->dev),
1091                     sizeof(gnsid->cdev));
1092                 gnsid->nsid = 0;
1093                 break;
1094         }
1095         default:
1096                 return (ENOTTY);
1097         }
1098
1099         return (0);
1100 }
1101
1102 static struct cdevsw nvme_ctrlr_cdevsw = {
1103         .d_version =    D_VERSION,
1104         .d_flags =      0,
1105         .d_ioctl =      nvme_ctrlr_ioctl
1106 };
1107
1108 int
1109 nvme_ctrlr_construct(struct nvme_controller *ctrlr, device_t dev)
1110 {
1111         struct make_dev_args    md_args;
1112         uint32_t        cap_lo;
1113         uint32_t        cap_hi;
1114         uint32_t        to;
1115         uint8_t         dstrd;
1116         uint8_t         mpsmin;
1117         int             status, timeout_period;
1118
1119         ctrlr->dev = dev;
1120
1121         mtx_init(&ctrlr->lock, "nvme ctrlr lock", NULL, MTX_DEF);
1122
1123         /*
1124          * Software emulators may set the doorbell stride to something
1125          *  other than zero, but this driver is not set up to handle that.
1126          */
1127         cap_hi = nvme_mmio_read_4(ctrlr, cap_hi);
1128         dstrd = NVME_CAP_HI_DSTRD(cap_hi);
1129         if (dstrd != 0)
1130                 return (ENXIO);
1131
1132         mpsmin = NVME_CAP_HI_MPSMIN(cap_hi);
1133         ctrlr->min_page_size = 1 << (12 + mpsmin);
1134
1135         /* Get ready timeout value from controller, in units of 500ms. */
1136         cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
1137         to = NVME_CAP_LO_TO(cap_lo) + 1;
1138         ctrlr->ready_timeout_in_ms = to * 500;
1139
1140         timeout_period = NVME_DEFAULT_TIMEOUT_PERIOD;
1141         TUNABLE_INT_FETCH("hw.nvme.timeout_period", &timeout_period);
1142         timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1143         timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1144         ctrlr->timeout_period = timeout_period;
1145
1146         nvme_retry_count = NVME_DEFAULT_RETRY_COUNT;
1147         TUNABLE_INT_FETCH("hw.nvme.retry_count", &nvme_retry_count);
1148
1149         ctrlr->enable_aborts = 0;
1150         TUNABLE_INT_FETCH("hw.nvme.enable_aborts", &ctrlr->enable_aborts);
1151
1152         ctrlr->max_xfer_size = NVME_MAX_XFER_SIZE;
1153         if (nvme_ctrlr_construct_admin_qpair(ctrlr) != 0)
1154                 return (ENXIO);
1155
1156         ctrlr->taskqueue = taskqueue_create("nvme_taskq", M_WAITOK,
1157             taskqueue_thread_enqueue, &ctrlr->taskqueue);
1158         taskqueue_start_threads(&ctrlr->taskqueue, 1, PI_DISK, "nvme taskq");
1159
1160         ctrlr->is_resetting = 0;
1161         ctrlr->is_initialized = 0;
1162         ctrlr->notification_sent = 0;
1163         TASK_INIT(&ctrlr->reset_task, 0, nvme_ctrlr_reset_task, ctrlr);
1164         TASK_INIT(&ctrlr->fail_req_task, 0, nvme_ctrlr_fail_req_task, ctrlr);
1165         STAILQ_INIT(&ctrlr->fail_req);
1166         ctrlr->is_failed = FALSE;
1167
1168         make_dev_args_init(&md_args);
1169         md_args.mda_devsw = &nvme_ctrlr_cdevsw;
1170         md_args.mda_uid = UID_ROOT;
1171         md_args.mda_gid = GID_WHEEL;
1172         md_args.mda_mode = 0600;
1173         md_args.mda_unit = device_get_unit(dev);
1174         md_args.mda_si_drv1 = (void *)ctrlr;
1175         status = make_dev_s(&md_args, &ctrlr->cdev, "nvme%d",
1176             device_get_unit(dev));
1177         if (status != 0)
1178                 return (ENXIO);
1179
1180         return (0);
1181 }
1182
1183 void
1184 nvme_ctrlr_destruct(struct nvme_controller *ctrlr, device_t dev)
1185 {
1186         int     gone, i;
1187
1188         if (ctrlr->resource == NULL)
1189                 goto nores;
1190
1191         /*
1192          * Check whether it is a hot unplug or a clean driver detach.
1193          * If device is not there any more, skip any shutdown commands.
1194          */
1195         gone = (nvme_mmio_read_4(ctrlr, csts) == 0xffffffff);
1196         if (gone)
1197                 nvme_ctrlr_fail(ctrlr);
1198         else
1199                 nvme_notify_fail_consumers(ctrlr);
1200
1201         for (i = 0; i < NVME_MAX_NAMESPACES; i++)
1202                 nvme_ns_destruct(&ctrlr->ns[i]);
1203
1204         if (ctrlr->cdev)
1205                 destroy_dev(ctrlr->cdev);
1206
1207         if (ctrlr->is_initialized) {
1208                 if (!gone)
1209                         nvme_ctrlr_destroy_qpairs(ctrlr);
1210                 for (i = 0; i < ctrlr->num_io_queues; i++)
1211                         nvme_io_qpair_destroy(&ctrlr->ioq[i]);
1212                 free(ctrlr->ioq, M_NVME);
1213                 nvme_admin_qpair_destroy(&ctrlr->adminq);
1214         }
1215
1216         /*
1217          *  Notify the controller of a shutdown, even though this is due to
1218          *   a driver unload, not a system shutdown (this path is not invoked
1219          *   during shutdown).  This ensures the controller receives a
1220          *   shutdown notification in case the system is shutdown before
1221          *   reloading the driver.
1222          */
1223         if (!gone)
1224                 nvme_ctrlr_shutdown(ctrlr);
1225
1226         if (!gone)
1227                 nvme_ctrlr_disable(ctrlr);
1228
1229         if (ctrlr->taskqueue)
1230                 taskqueue_free(ctrlr->taskqueue);
1231
1232         if (ctrlr->tag)
1233                 bus_teardown_intr(ctrlr->dev, ctrlr->res, ctrlr->tag);
1234
1235         if (ctrlr->res)
1236                 bus_release_resource(ctrlr->dev, SYS_RES_IRQ,
1237                     rman_get_rid(ctrlr->res), ctrlr->res);
1238
1239         if (ctrlr->bar4_resource != NULL) {
1240                 bus_release_resource(dev, SYS_RES_MEMORY,
1241                     ctrlr->bar4_resource_id, ctrlr->bar4_resource);
1242         }
1243
1244         bus_release_resource(dev, SYS_RES_MEMORY,
1245             ctrlr->resource_id, ctrlr->resource);
1246
1247 nores:
1248         mtx_destroy(&ctrlr->lock);
1249 }
1250
1251 void
1252 nvme_ctrlr_shutdown(struct nvme_controller *ctrlr)
1253 {
1254         uint32_t        cc;
1255         uint32_t        csts;
1256         int             ticks = 0;
1257
1258         cc = nvme_mmio_read_4(ctrlr, cc);
1259         cc &= ~(NVME_CC_REG_SHN_MASK << NVME_CC_REG_SHN_SHIFT);
1260         cc |= NVME_SHN_NORMAL << NVME_CC_REG_SHN_SHIFT;
1261         nvme_mmio_write_4(ctrlr, cc, cc);
1262
1263         while (1) {
1264                 csts = nvme_mmio_read_4(ctrlr, csts);
1265                 if (csts == 0xffffffff)         /* Hot unplug. */
1266                         break;
1267                 if (NVME_CSTS_GET_SHST(csts) == NVME_SHST_COMPLETE)
1268                         break;
1269                 if (ticks++ > 5*hz) {
1270                         nvme_printf(ctrlr, "did not complete shutdown within"
1271                             " 5 seconds of notification\n");
1272                         break;
1273                 }
1274                 pause("nvme shn", 1);
1275         }
1276 }
1277
1278 void
1279 nvme_ctrlr_submit_admin_request(struct nvme_controller *ctrlr,
1280     struct nvme_request *req)
1281 {
1282
1283         nvme_qpair_submit_request(&ctrlr->adminq, req);
1284 }
1285
1286 void
1287 nvme_ctrlr_submit_io_request(struct nvme_controller *ctrlr,
1288     struct nvme_request *req)
1289 {
1290         struct nvme_qpair       *qpair;
1291
1292         qpair = &ctrlr->ioq[curcpu / ctrlr->num_cpus_per_ioq];
1293         nvme_qpair_submit_request(qpair, req);
1294 }
1295
1296 device_t
1297 nvme_ctrlr_get_device(struct nvme_controller *ctrlr)
1298 {
1299
1300         return (ctrlr->dev);
1301 }
1302
1303 const struct nvme_controller_data *
1304 nvme_ctrlr_get_data(struct nvme_controller *ctrlr)
1305 {
1306
1307         return (&ctrlr->cdata);
1308 }