xref: /titanic_50/usr/src/uts/common/io/nvme/nvme.c (revision 17f58fc8e7eafc21acc31b0f92ad04c7a275c400)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
14  */
15 
16 /*
17  * blkdev driver for NVMe compliant storage devices
18  *
19  * This driver was written to conform to version 1.0e of the NVMe specification.
20  * It may work with newer versions, but that is completely untested and disabled
21  * by default.
22  *
23  * The driver has only been tested on x86 systems and will not work on big-
24  * endian systems without changes to the code accessing registers and data
25  * structures used by the hardware.
26  *
27  *
28  * Interrupt Usage:
29  *
30  * The driver will use a FIXED interrupt while configuring the device as the
31  * specification requires. Later in the attach process it will switch to MSI-X
32  * or MSI if supported. The driver wants to have one interrupt vector per CPU,
33  * but it will work correctly if less are available. Interrupts can be shared
34  * by queues, the interrupt handler will iterate through the I/O queue array by
35  * steps of n_intr_cnt. Usually only the admin queue will share an interrupt
36  * with one I/O queue. The interrupt handler will retrieve completed commands
37  * from all queues sharing an interrupt vector and will post them to a taskq
38  * for completion processing.
39  *
40  *
41  * Command Processing:
42  *
43  * NVMe devices can have up to 65536 I/O queue pairs, with each queue holding up
44  * to 65536 I/O commands. The driver will configure one I/O queue pair per
45  * available interrupt vector, with the queue length usually much smaller than
46  * the maximum of 65536. If the hardware doesn't provide enough queues, fewer
47  * interrupt vectors will be used.
48  *
49  * Additionally the hardware provides a single special admin queue pair that can
50  * hold up to 4096 admin commands.
51  *
52  * From the hardware perspective both queues of a queue pair are independent,
53  * but they share some driver state: the command array (holding pointers to
54  * commands currently being processed by the hardware) and the active command
55  * counter. Access to the submission side of a queue pair and the shared state
56  * is protected by nq_mutex. The completion side of a queue pair does not need
57  * that protection apart from its access to the shared state; it is called only
58  * in the interrupt handler which does not run concurrently for the same
59  * interrupt vector.
60  *
61  * When a command is submitted to a queue pair the active command counter is
62  * incremented and a pointer to the command is stored in the command array. The
63  * array index is used as command identifier (CID) in the submission queue
64  * entry. Some commands may take a very long time to complete, and if the queue
65  * wraps around in that time a submission may find the next array slot to still
66  * be used by a long-running command. In this case the array is sequentially
67  * searched for the next free slot. The length of the command array is the same
68  * as the configured queue length.
69  *
70  *
71  * Namespace Support:
72  *
73  * NVMe devices can have multiple namespaces, each being a independent data
74  * store. The driver supports multiple namespaces and creates a blkdev interface
75  * for each namespace found. Namespaces can have various attributes to support
76  * thin provisioning, extended LBAs, and protection information. This driver
77  * does not support any of this and ignores namespaces that have these
78  * attributes.
79  *
80  *
81  * Blkdev Interface:
82  *
83  * This driver uses blkdev to do all the heavy lifting involved with presenting
84  * a disk device to the system. As a result, the processing of I/O requests is
85  * relatively simple as blkdev takes care of partitioning, boundary checks, DMA
86  * setup, and splitting of transfers into manageable chunks.
87  *
88  * I/O requests coming in from blkdev are turned into NVM commands and posted to
89  * an I/O queue. The queue is selected by taking the CPU id modulo the number of
90  * queues. There is currently no timeout handling of I/O commands.
91  *
92  * Blkdev also supports querying device/media information and generating a
93  * devid. The driver reports the best block size as determined by the namespace
94  * format back to blkdev as physical block size to support partition and block
95  * alignment. The devid is composed using the device vendor ID, model number,
96  * serial number, and the namespace ID.
97  *
98  *
99  * Error Handling:
100  *
101  * Error handling is currently limited to detecting fatal hardware errors,
102  * either by asynchronous events, or synchronously through command status or
103  * admin command timeouts. In case of severe errors the device is fenced off,
104  * all further requests will return EIO. FMA is then called to fault the device.
105  *
106  * The hardware has a limit for outstanding asynchronous event requests. Before
107  * this limit is known the driver assumes it is at least 1 and posts a single
108  * asynchronous request. Later when the limit is known more asynchronous event
109  * requests are posted to allow quicker reception of error information. When an
110  * asynchronous event is posted by the hardware the driver will parse the error
111  * status fields and log information or fault the device, depending on the
112  * severity of the asynchronous event. The asynchronous event request is then
113  * reused and posted to the admin queue again.
114  *
115  * On command completion the command status is checked for errors. In case of
116  * errors indicating a driver bug the driver panics. Almost all other error
117  * status values just cause EIO to be returned.
118  *
119  * Command timeouts are currently detected for all admin commands except
120  * asynchronous event requests. If a command times out and the hardware appears
121  * to be healthy the driver attempts to abort the command. If this fails the
122  * driver assumes the device to be dead, fences it off, and calls FMA to retire
123  * it. In general admin commands are issued at attach time only. No timeout
124  * handling of normal I/O commands is presently done.
125  *
126  * In some cases it may be possible that the ABORT command times out, too. In
127  * that case the device is also declared dead and fenced off.
128  *
129  *
130  * Quiesce / Fast Reboot:
131  *
132  * The driver currently does not support fast reboot. A quiesce(9E) entry point
133  * is still provided which is used to send a shutdown notification to the
134  * device.
135  *
136  *
137  * Driver Configuration:
138  *
139  * The following driver properties can be changed to control some aspects of the
140  * drivers operation:
141  * - strict-version: can be set to 0 to allow devices conforming to newer
142  *   versions to be used
143  * - ignore-unknown-vendor-status: can be set to 1 to not handle any vendor
144  *   specific command status as a fatal error leading device faulting
145  * - admin-queue-len: the maximum length of the admin queue (16-4096)
146  * - io-queue-len: the maximum length of the I/O queues (16-65536)
147  * - async-event-limit: the maximum number of asynchronous event requests to be
148  *   posted by the driver
149  *
150  *
151  * TODO:
152  * - figure out sane default for I/O queue depth reported to blkdev
153  * - polled I/O support to support kernel core dumping
154  * - FMA handling of media errors
155  * - support for the Volatile Write Cache
156  * - support for devices supporting very large I/O requests using chained PRPs
157  * - support for querying log pages from user space
158  * - support for configuring hardware parameters like interrupt coalescing
159  * - support for media formatting and hard partitioning into namespaces
160  * - support for big-endian systems
161  * - support for fast reboot
162  */
163 
164 #include <sys/byteorder.h>
165 #ifdef _BIG_ENDIAN
166 #error nvme driver needs porting for big-endian platforms
167 #endif
168 
169 #include <sys/modctl.h>
170 #include <sys/conf.h>
171 #include <sys/devops.h>
172 #include <sys/ddi.h>
173 #include <sys/sunddi.h>
174 #include <sys/bitmap.h>
175 #include <sys/sysmacros.h>
176 #include <sys/param.h>
177 #include <sys/varargs.h>
178 #include <sys/cpuvar.h>
179 #include <sys/disp.h>
180 #include <sys/blkdev.h>
181 #include <sys/atomic.h>
182 #include <sys/archsystm.h>
183 #include <sys/sata/sata_hba.h>
184 
185 #include "nvme_reg.h"
186 #include "nvme_var.h"
187 
188 
189 /* NVMe spec version supported */
190 static const int nvme_version_major = 1;
191 static const int nvme_version_minor = 0;
192 
193 static int nvme_attach(dev_info_t *, ddi_attach_cmd_t);
194 static int nvme_detach(dev_info_t *, ddi_detach_cmd_t);
195 static int nvme_quiesce(dev_info_t *);
196 static int nvme_fm_errcb(dev_info_t *, ddi_fm_error_t *, const void *);
197 static void nvme_disable_interrupts(nvme_t *);
198 static int nvme_enable_interrupts(nvme_t *);
199 static int nvme_setup_interrupts(nvme_t *, int, int);
200 static void nvme_release_interrupts(nvme_t *);
201 static uint_t nvme_intr(caddr_t, caddr_t);
202 
203 static void nvme_shutdown(nvme_t *, int, boolean_t);
204 static boolean_t nvme_reset(nvme_t *, boolean_t);
205 static int nvme_init(nvme_t *);
206 static nvme_cmd_t *nvme_alloc_cmd(nvme_t *, int);
207 static void nvme_free_cmd(nvme_cmd_t *);
208 static nvme_cmd_t *nvme_create_nvm_cmd(nvme_namespace_t *, uint8_t,
209     bd_xfer_t *);
210 static int nvme_admin_cmd(nvme_cmd_t *, int);
211 static int nvme_submit_cmd(nvme_qpair_t *, nvme_cmd_t *);
212 static nvme_cmd_t *nvme_retrieve_cmd(nvme_t *, nvme_qpair_t *);
213 static boolean_t nvme_wait_cmd(nvme_cmd_t *, uint_t);
214 static void nvme_wakeup_cmd(void *);
215 static void nvme_async_event_task(void *);
216 
217 static int nvme_check_unknown_cmd_status(nvme_cmd_t *);
218 static int nvme_check_vendor_cmd_status(nvme_cmd_t *);
219 static int nvme_check_integrity_cmd_status(nvme_cmd_t *);
220 static int nvme_check_specific_cmd_status(nvme_cmd_t *);
221 static int nvme_check_generic_cmd_status(nvme_cmd_t *);
222 static inline int nvme_check_cmd_status(nvme_cmd_t *);
223 
224 static void nvme_abort_cmd(nvme_cmd_t *);
225 static int nvme_async_event(nvme_t *);
226 static void *nvme_get_logpage(nvme_t *, uint8_t, ...);
227 static void *nvme_identify(nvme_t *, uint32_t);
228 static int nvme_set_nqueues(nvme_t *, uint16_t);
229 
230 static void nvme_free_dma(nvme_dma_t *);
231 static int nvme_zalloc_dma(nvme_t *, size_t, uint_t, ddi_dma_attr_t *,
232     nvme_dma_t **);
233 static int nvme_zalloc_queue_dma(nvme_t *, uint32_t, uint16_t, uint_t,
234     nvme_dma_t **);
235 static void nvme_free_qpair(nvme_qpair_t *);
236 static int nvme_alloc_qpair(nvme_t *, uint32_t, nvme_qpair_t **, int);
237 static int nvme_create_io_qpair(nvme_t *, nvme_qpair_t *, uint16_t);
238 
239 static inline void nvme_put64(nvme_t *, uintptr_t, uint64_t);
240 static inline void nvme_put32(nvme_t *, uintptr_t, uint32_t);
241 static inline uint64_t nvme_get64(nvme_t *, uintptr_t);
242 static inline uint32_t nvme_get32(nvme_t *, uintptr_t);
243 
244 static boolean_t nvme_check_regs_hdl(nvme_t *);
245 static boolean_t nvme_check_dma_hdl(nvme_dma_t *);
246 
247 static int nvme_fill_prp(nvme_cmd_t *, bd_xfer_t *);
248 
249 static void nvme_bd_xfer_done(void *);
250 static void nvme_bd_driveinfo(void *, bd_drive_t *);
251 static int nvme_bd_mediainfo(void *, bd_media_t *);
252 static int nvme_bd_cmd(nvme_namespace_t *, bd_xfer_t *, uint8_t);
253 static int nvme_bd_read(void *, bd_xfer_t *);
254 static int nvme_bd_write(void *, bd_xfer_t *);
255 static int nvme_bd_sync(void *, bd_xfer_t *);
256 static int nvme_bd_devid(void *, dev_info_t *, ddi_devid_t *);
257 
258 static void nvme_prepare_devid(nvme_t *, uint32_t);
259 
260 static void *nvme_state;
261 static kmem_cache_t *nvme_cmd_cache;
262 
263 /*
264  * DMA attributes for queue DMA memory
265  *
266  * Queue DMA memory must be page aligned. The maximum length of a queue is
267  * 65536 entries, and an entry can be 64 bytes long.
268  */
269 static ddi_dma_attr_t nvme_queue_dma_attr = {
270 	.dma_attr_version	= DMA_ATTR_V0,
271 	.dma_attr_addr_lo	= 0,
272 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
273 	.dma_attr_count_max	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t),
274 	.dma_attr_align		= 0x1000,
275 	.dma_attr_burstsizes	= 0x7ff,
276 	.dma_attr_minxfer	= 0x1000,
277 	.dma_attr_maxxfer	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t),
278 	.dma_attr_seg		= 0xffffffffffffffffULL,
279 	.dma_attr_sgllen	= 1,
280 	.dma_attr_granular	= 1,
281 	.dma_attr_flags		= 0,
282 };
283 
284 /*
285  * DMA attributes for transfers using Physical Region Page (PRP) entries
286  *
287  * A PRP entry describes one page of DMA memory using the page size specified
288  * in the controller configuration's memory page size register (CC.MPS). It uses
289  * a 64bit base address aligned to this page size. There is no limitation on
290  * chaining PRPs together for arbitrarily large DMA transfers.
291  */
292 static ddi_dma_attr_t nvme_prp_dma_attr = {
293 	.dma_attr_version	= DMA_ATTR_V0,
294 	.dma_attr_addr_lo	= 0,
295 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
296 	.dma_attr_count_max	= 0xfff,
297 	.dma_attr_align		= 0x1000,
298 	.dma_attr_burstsizes	= 0x7ff,
299 	.dma_attr_minxfer	= 0x1000,
300 	.dma_attr_maxxfer	= 0x1000,
301 	.dma_attr_seg		= 0xffffffffffffffffULL,
302 	.dma_attr_sgllen	= -1,
303 	.dma_attr_granular	= 1,
304 	.dma_attr_flags		= 0,
305 };
306 
307 /*
308  * DMA attributes for transfers using scatter/gather lists
309  *
310  * A SGL entry describes a chunk of DMA memory using a 64bit base address and a
311  * 32bit length field. SGL Segment and SGL Last Segment entries require the
312  * length to be a multiple of 16 bytes.
313  */
314 static ddi_dma_attr_t nvme_sgl_dma_attr = {
315 	.dma_attr_version	= DMA_ATTR_V0,
316 	.dma_attr_addr_lo	= 0,
317 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
318 	.dma_attr_count_max	= 0xffffffffUL,
319 	.dma_attr_align		= 1,
320 	.dma_attr_burstsizes	= 0x7ff,
321 	.dma_attr_minxfer	= 0x10,
322 	.dma_attr_maxxfer	= 0xfffffffffULL,
323 	.dma_attr_seg		= 0xffffffffffffffffULL,
324 	.dma_attr_sgllen	= -1,
325 	.dma_attr_granular	= 0x10,
326 	.dma_attr_flags		= 0
327 };
328 
329 static ddi_device_acc_attr_t nvme_reg_acc_attr = {
330 	.devacc_attr_version	= DDI_DEVICE_ATTR_V0,
331 	.devacc_attr_endian_flags = DDI_STRUCTURE_LE_ACC,
332 	.devacc_attr_dataorder	= DDI_STRICTORDER_ACC
333 };
334 
335 static struct dev_ops nvme_dev_ops = {
336 	.devo_rev	= DEVO_REV,
337 	.devo_refcnt	= 0,
338 	.devo_getinfo	= ddi_no_info,
339 	.devo_identify	= nulldev,
340 	.devo_probe	= nulldev,
341 	.devo_attach	= nvme_attach,
342 	.devo_detach	= nvme_detach,
343 	.devo_reset	= nodev,
344 	.devo_cb_ops	= NULL,
345 	.devo_bus_ops	= NULL,
346 	.devo_power	= NULL,
347 	.devo_quiesce	= nvme_quiesce,
348 };
349 
350 static struct modldrv nvme_modldrv = {
351 	.drv_modops	= &mod_driverops,
352 	.drv_linkinfo	= "NVMe v1.0e",
353 	.drv_dev_ops	= &nvme_dev_ops
354 };
355 
356 static struct modlinkage nvme_modlinkage = {
357 	.ml_rev		= MODREV_1,
358 	.ml_linkage	= { &nvme_modldrv, NULL }
359 };
360 
361 static bd_ops_t nvme_bd_ops = {
362 	.o_version	= BD_OPS_VERSION_0,
363 	.o_drive_info	= nvme_bd_driveinfo,
364 	.o_media_info	= nvme_bd_mediainfo,
365 	.o_devid_init	= nvme_bd_devid,
366 	.o_sync_cache	= nvme_bd_sync,
367 	.o_read		= nvme_bd_read,
368 	.o_write	= nvme_bd_write,
369 };
370 
371 int
372 _init(void)
373 {
374 	int error;
375 
376 	error = ddi_soft_state_init(&nvme_state, sizeof (nvme_t), 1);
377 	if (error != DDI_SUCCESS)
378 		return (error);
379 
380 	nvme_cmd_cache = kmem_cache_create("nvme_cmd_cache",
381 	    sizeof (nvme_cmd_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
382 
383 	bd_mod_init(&nvme_dev_ops);
384 
385 	error = mod_install(&nvme_modlinkage);
386 	if (error != DDI_SUCCESS) {
387 		ddi_soft_state_fini(&nvme_state);
388 		bd_mod_fini(&nvme_dev_ops);
389 	}
390 
391 	return (error);
392 }
393 
394 int
395 _fini(void)
396 {
397 	int error;
398 
399 	error = mod_remove(&nvme_modlinkage);
400 	if (error == DDI_SUCCESS) {
401 		ddi_soft_state_fini(&nvme_state);
402 		kmem_cache_destroy(nvme_cmd_cache);
403 		bd_mod_fini(&nvme_dev_ops);
404 	}
405 
406 	return (error);
407 }
408 
409 int
410 _info(struct modinfo *modinfop)
411 {
412 	return (mod_info(&nvme_modlinkage, modinfop));
413 }
414 
415 static inline void
416 nvme_put64(nvme_t *nvme, uintptr_t reg, uint64_t val)
417 {
418 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
419 
420 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
421 	ddi_put64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg), val);
422 }
423 
424 static inline void
425 nvme_put32(nvme_t *nvme, uintptr_t reg, uint32_t val)
426 {
427 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
428 
429 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
430 	ddi_put32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg), val);
431 }
432 
433 static inline uint64_t
434 nvme_get64(nvme_t *nvme, uintptr_t reg)
435 {
436 	uint64_t val;
437 
438 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
439 
440 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
441 	val = ddi_get64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg));
442 
443 	return (val);
444 }
445 
446 static inline uint32_t
447 nvme_get32(nvme_t *nvme, uintptr_t reg)
448 {
449 	uint32_t val;
450 
451 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
452 
453 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
454 	val = ddi_get32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg));
455 
456 	return (val);
457 }
458 
459 static boolean_t
460 nvme_check_regs_hdl(nvme_t *nvme)
461 {
462 	ddi_fm_error_t error;
463 
464 	ddi_fm_acc_err_get(nvme->n_regh, &error, DDI_FME_VERSION);
465 
466 	if (error.fme_status != DDI_FM_OK)
467 		return (B_TRUE);
468 
469 	return (B_FALSE);
470 }
471 
472 static boolean_t
473 nvme_check_dma_hdl(nvme_dma_t *dma)
474 {
475 	ddi_fm_error_t error;
476 
477 	if (dma == NULL)
478 		return (B_FALSE);
479 
480 	ddi_fm_dma_err_get(dma->nd_dmah, &error, DDI_FME_VERSION);
481 
482 	if (error.fme_status != DDI_FM_OK)
483 		return (B_TRUE);
484 
485 	return (B_FALSE);
486 }
487 
488 static void
489 nvme_free_dma(nvme_dma_t *dma)
490 {
491 	if (dma->nd_dmah != NULL)
492 		(void) ddi_dma_unbind_handle(dma->nd_dmah);
493 	if (dma->nd_acch != NULL)
494 		ddi_dma_mem_free(&dma->nd_acch);
495 	if (dma->nd_dmah != NULL)
496 		ddi_dma_free_handle(&dma->nd_dmah);
497 	kmem_free(dma, sizeof (nvme_dma_t));
498 }
499 
500 static int
501 nvme_zalloc_dma(nvme_t *nvme, size_t len, uint_t flags,
502     ddi_dma_attr_t *dma_attr, nvme_dma_t **ret)
503 {
504 	nvme_dma_t *dma = kmem_zalloc(sizeof (nvme_dma_t), KM_SLEEP);
505 
506 	if (ddi_dma_alloc_handle(nvme->n_dip, dma_attr, DDI_DMA_SLEEP, NULL,
507 	    &dma->nd_dmah) != DDI_SUCCESS) {
508 		/*
509 		 * Due to DDI_DMA_SLEEP this can't be DDI_DMA_NORESOURCES, and
510 		 * the only other possible error is DDI_DMA_BADATTR which
511 		 * indicates a driver bug which should cause a panic.
512 		 */
513 		dev_err(nvme->n_dip, CE_PANIC,
514 		    "!failed to get DMA handle, check DMA attributes");
515 		return (DDI_FAILURE);
516 	}
517 
518 	/*
519 	 * ddi_dma_mem_alloc() can only fail when DDI_DMA_NOSLEEP is specified
520 	 * or the flags are conflicting, which isn't the case here.
521 	 */
522 	(void) ddi_dma_mem_alloc(dma->nd_dmah, len, &nvme->n_reg_acc_attr,
523 	    DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, &dma->nd_memp,
524 	    &dma->nd_len, &dma->nd_acch);
525 
526 	if (ddi_dma_addr_bind_handle(dma->nd_dmah, NULL, dma->nd_memp,
527 	    dma->nd_len, flags | DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL,
528 	    &dma->nd_cookie, &dma->nd_ncookie) != DDI_DMA_MAPPED) {
529 		dev_err(nvme->n_dip, CE_WARN,
530 		    "!failed to bind DMA memory");
531 		atomic_inc_32(&nvme->n_dma_bind_err);
532 		*ret = NULL;
533 		nvme_free_dma(dma);
534 		return (DDI_FAILURE);
535 	}
536 
537 	bzero(dma->nd_memp, dma->nd_len);
538 
539 	*ret = dma;
540 	return (DDI_SUCCESS);
541 }
542 
543 static int
544 nvme_zalloc_queue_dma(nvme_t *nvme, uint32_t nentry, uint16_t qe_len,
545     uint_t flags, nvme_dma_t **dma)
546 {
547 	uint32_t len = nentry * qe_len;
548 	ddi_dma_attr_t q_dma_attr = nvme->n_queue_dma_attr;
549 
550 	len = roundup(len, nvme->n_pagesize);
551 
552 	q_dma_attr.dma_attr_minxfer = len;
553 
554 	if (nvme_zalloc_dma(nvme, len, flags, &q_dma_attr, dma)
555 	    != DDI_SUCCESS) {
556 		dev_err(nvme->n_dip, CE_WARN,
557 		    "!failed to get DMA memory for queue");
558 		goto fail;
559 	}
560 
561 	if ((*dma)->nd_ncookie != 1) {
562 		dev_err(nvme->n_dip, CE_WARN,
563 		    "!got too many cookies for queue DMA");
564 		goto fail;
565 	}
566 
567 	return (DDI_SUCCESS);
568 
569 fail:
570 	if (*dma) {
571 		nvme_free_dma(*dma);
572 		*dma = NULL;
573 	}
574 
575 	return (DDI_FAILURE);
576 }
577 
578 static void
579 nvme_free_qpair(nvme_qpair_t *qp)
580 {
581 	int i;
582 
583 	mutex_destroy(&qp->nq_mutex);
584 
585 	if (qp->nq_sqdma != NULL)
586 		nvme_free_dma(qp->nq_sqdma);
587 	if (qp->nq_cqdma != NULL)
588 		nvme_free_dma(qp->nq_cqdma);
589 
590 	if (qp->nq_active_cmds > 0)
591 		for (i = 0; i != qp->nq_nentry; i++)
592 			if (qp->nq_cmd[i] != NULL)
593 				nvme_free_cmd(qp->nq_cmd[i]);
594 
595 	if (qp->nq_cmd != NULL)
596 		kmem_free(qp->nq_cmd, sizeof (nvme_cmd_t *) * qp->nq_nentry);
597 
598 	kmem_free(qp, sizeof (nvme_qpair_t));
599 }
600 
601 static int
602 nvme_alloc_qpair(nvme_t *nvme, uint32_t nentry, nvme_qpair_t **nqp,
603     int idx)
604 {
605 	nvme_qpair_t *qp = kmem_zalloc(sizeof (*qp), KM_SLEEP);
606 
607 	mutex_init(&qp->nq_mutex, NULL, MUTEX_DRIVER,
608 	    DDI_INTR_PRI(nvme->n_intr_pri));
609 
610 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_sqe_t),
611 	    DDI_DMA_WRITE, &qp->nq_sqdma) != DDI_SUCCESS)
612 		goto fail;
613 
614 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_cqe_t),
615 	    DDI_DMA_READ, &qp->nq_cqdma) != DDI_SUCCESS)
616 		goto fail;
617 
618 	qp->nq_sq = (nvme_sqe_t *)qp->nq_sqdma->nd_memp;
619 	qp->nq_cq = (nvme_cqe_t *)qp->nq_cqdma->nd_memp;
620 	qp->nq_nentry = nentry;
621 
622 	qp->nq_sqtdbl = NVME_REG_SQTDBL(nvme, idx);
623 	qp->nq_cqhdbl = NVME_REG_CQHDBL(nvme, idx);
624 
625 	qp->nq_cmd = kmem_zalloc(sizeof (nvme_cmd_t *) * nentry, KM_SLEEP);
626 	qp->nq_next_cmd = 0;
627 
628 	*nqp = qp;
629 	return (DDI_SUCCESS);
630 
631 fail:
632 	nvme_free_qpair(qp);
633 	*nqp = NULL;
634 
635 	return (DDI_FAILURE);
636 }
637 
638 static nvme_cmd_t *
639 nvme_alloc_cmd(nvme_t *nvme, int kmflag)
640 {
641 	nvme_cmd_t *cmd = kmem_cache_alloc(nvme_cmd_cache, kmflag);
642 
643 	if (cmd == NULL)
644 		return (cmd);
645 
646 	bzero(cmd, sizeof (nvme_cmd_t));
647 
648 	cmd->nc_nvme = nvme;
649 
650 	mutex_init(&cmd->nc_mutex, NULL, MUTEX_DRIVER,
651 	    DDI_INTR_PRI(nvme->n_intr_pri));
652 	cv_init(&cmd->nc_cv, NULL, CV_DRIVER, NULL);
653 
654 	return (cmd);
655 }
656 
657 static void
658 nvme_free_cmd(nvme_cmd_t *cmd)
659 {
660 	if (cmd->nc_dma) {
661 		nvme_free_dma(cmd->nc_dma);
662 		cmd->nc_dma = NULL;
663 	}
664 
665 	cv_destroy(&cmd->nc_cv);
666 	mutex_destroy(&cmd->nc_mutex);
667 
668 	kmem_cache_free(nvme_cmd_cache, cmd);
669 }
670 
671 static int
672 nvme_submit_cmd(nvme_qpair_t *qp, nvme_cmd_t *cmd)
673 {
674 	nvme_reg_sqtdbl_t tail = { 0 };
675 
676 	mutex_enter(&qp->nq_mutex);
677 
678 	if (qp->nq_active_cmds == qp->nq_nentry) {
679 		mutex_exit(&qp->nq_mutex);
680 		return (DDI_FAILURE);
681 	}
682 
683 	cmd->nc_completed = B_FALSE;
684 
685 	/*
686 	 * Try to insert the cmd into the active cmd array at the nq_next_cmd
687 	 * slot. If the slot is already occupied advance to the next slot and
688 	 * try again. This can happen for long running commands like async event
689 	 * requests.
690 	 */
691 	while (qp->nq_cmd[qp->nq_next_cmd] != NULL)
692 		qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
693 	qp->nq_cmd[qp->nq_next_cmd] = cmd;
694 
695 	qp->nq_active_cmds++;
696 
697 	cmd->nc_sqe.sqe_cid = qp->nq_next_cmd;
698 	bcopy(&cmd->nc_sqe, &qp->nq_sq[qp->nq_sqtail], sizeof (nvme_sqe_t));
699 	(void) ddi_dma_sync(qp->nq_sqdma->nd_dmah,
700 	    sizeof (nvme_sqe_t) * qp->nq_sqtail,
701 	    sizeof (nvme_sqe_t), DDI_DMA_SYNC_FORDEV);
702 	qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
703 
704 	tail.b.sqtdbl_sqt = qp->nq_sqtail = (qp->nq_sqtail + 1) % qp->nq_nentry;
705 	nvme_put32(cmd->nc_nvme, qp->nq_sqtdbl, tail.r);
706 
707 	mutex_exit(&qp->nq_mutex);
708 	return (DDI_SUCCESS);
709 }
710 
711 static nvme_cmd_t *
712 nvme_retrieve_cmd(nvme_t *nvme, nvme_qpair_t *qp)
713 {
714 	nvme_reg_cqhdbl_t head = { 0 };
715 
716 	nvme_cqe_t *cqe;
717 	nvme_cmd_t *cmd;
718 
719 	(void) ddi_dma_sync(qp->nq_cqdma->nd_dmah, 0,
720 	    sizeof (nvme_cqe_t) * qp->nq_nentry, DDI_DMA_SYNC_FORKERNEL);
721 
722 	cqe = &qp->nq_cq[qp->nq_cqhead];
723 
724 	/* Check phase tag of CQE. Hardware inverts it for new entries. */
725 	if (cqe->cqe_sf.sf_p == qp->nq_phase)
726 		return (NULL);
727 
728 	ASSERT(nvme->n_ioq[cqe->cqe_sqid] == qp);
729 	ASSERT(cqe->cqe_cid < qp->nq_nentry);
730 
731 	mutex_enter(&qp->nq_mutex);
732 	cmd = qp->nq_cmd[cqe->cqe_cid];
733 	qp->nq_cmd[cqe->cqe_cid] = NULL;
734 	qp->nq_active_cmds--;
735 	mutex_exit(&qp->nq_mutex);
736 
737 	ASSERT(cmd != NULL);
738 	ASSERT(cmd->nc_nvme == nvme);
739 	ASSERT(cmd->nc_sqid == cqe->cqe_sqid);
740 	ASSERT(cmd->nc_sqe.sqe_cid == cqe->cqe_cid);
741 	bcopy(cqe, &cmd->nc_cqe, sizeof (nvme_cqe_t));
742 
743 	qp->nq_sqhead = cqe->cqe_sqhd;
744 
745 	head.b.cqhdbl_cqh = qp->nq_cqhead = (qp->nq_cqhead + 1) % qp->nq_nentry;
746 
747 	/* Toggle phase on wrap-around. */
748 	if (qp->nq_cqhead == 0)
749 		qp->nq_phase = qp->nq_phase ? 0 : 1;
750 
751 	nvme_put32(cmd->nc_nvme, qp->nq_cqhdbl, head.r);
752 
753 	return (cmd);
754 }
755 
756 static int
757 nvme_check_unknown_cmd_status(nvme_cmd_t *cmd)
758 {
759 	nvme_cqe_t *cqe = &cmd->nc_cqe;
760 
761 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
762 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
763 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
764 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
765 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
766 
767 	bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
768 
769 	if (cmd->nc_nvme->n_strict_version) {
770 		cmd->nc_nvme->n_dead = B_TRUE;
771 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
772 	}
773 
774 	return (EIO);
775 }
776 
777 static int
778 nvme_check_vendor_cmd_status(nvme_cmd_t *cmd)
779 {
780 	nvme_cqe_t *cqe = &cmd->nc_cqe;
781 
782 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
783 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
784 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
785 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
786 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
787 	if (cmd->nc_nvme->n_ignore_unknown_vendor_status) {
788 		cmd->nc_nvme->n_dead = B_TRUE;
789 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
790 	}
791 
792 	return (EIO);
793 }
794 
795 static int
796 nvme_check_integrity_cmd_status(nvme_cmd_t *cmd)
797 {
798 	nvme_cqe_t *cqe = &cmd->nc_cqe;
799 
800 	switch (cqe->cqe_sf.sf_sc) {
801 	case NVME_CQE_SC_INT_NVM_WRITE:
802 		/* write fail */
803 		/* TODO: post ereport */
804 		bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
805 		return (EIO);
806 
807 	case NVME_CQE_SC_INT_NVM_READ:
808 		/* read fail */
809 		/* TODO: post ereport */
810 		bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
811 		return (EIO);
812 
813 	default:
814 		return (nvme_check_unknown_cmd_status(cmd));
815 	}
816 }
817 
818 static int
819 nvme_check_generic_cmd_status(nvme_cmd_t *cmd)
820 {
821 	nvme_cqe_t *cqe = &cmd->nc_cqe;
822 
823 	switch (cqe->cqe_sf.sf_sc) {
824 	case NVME_CQE_SC_GEN_SUCCESS:
825 		return (0);
826 
827 	/*
828 	 * Errors indicating a bug in the driver should cause a panic.
829 	 */
830 	case NVME_CQE_SC_GEN_INV_OPC:
831 		/* Invalid Command Opcode */
832 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
833 		    "invalid opcode in cmd %p", (void *)cmd);
834 		return (0);
835 
836 	case NVME_CQE_SC_GEN_INV_FLD:
837 		/* Invalid Field in Command */
838 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
839 		    "invalid field in cmd %p", (void *)cmd);
840 		return (0);
841 
842 	case NVME_CQE_SC_GEN_ID_CNFL:
843 		/* Command ID Conflict */
844 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
845 		    "cmd ID conflict in cmd %p", (void *)cmd);
846 		return (0);
847 
848 	case NVME_CQE_SC_GEN_INV_NS:
849 		/* Invalid Namespace or Format */
850 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
851 		    "invalid NS/format in cmd %p", (void *)cmd);
852 		return (0);
853 
854 	case NVME_CQE_SC_GEN_NVM_LBA_RANGE:
855 		/* LBA Out Of Range */
856 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
857 		    "LBA out of range in cmd %p", (void *)cmd);
858 		return (0);
859 
860 	/*
861 	 * Non-fatal errors, handle gracefully.
862 	 */
863 	case NVME_CQE_SC_GEN_DATA_XFR_ERR:
864 		/* Data Transfer Error (DMA) */
865 		/* TODO: post ereport */
866 		atomic_inc_32(&cmd->nc_nvme->n_data_xfr_err);
867 		bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
868 		return (EIO);
869 
870 	case NVME_CQE_SC_GEN_INTERNAL_ERR:
871 		/*
872 		 * Internal Error. The spec (v1.0, section 4.5.1.2) says
873 		 * detailed error information is returned as async event,
874 		 * so we pretty much ignore the error here and handle it
875 		 * in the async event handler.
876 		 */
877 		atomic_inc_32(&cmd->nc_nvme->n_internal_err);
878 		bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
879 		return (EIO);
880 
881 	case NVME_CQE_SC_GEN_ABORT_REQUEST:
882 		/*
883 		 * Command Abort Requested. This normally happens only when a
884 		 * command times out.
885 		 */
886 		/* TODO: post ereport or change blkdev to handle this? */
887 		atomic_inc_32(&cmd->nc_nvme->n_abort_rq_err);
888 		return (ECANCELED);
889 
890 	case NVME_CQE_SC_GEN_ABORT_PWRLOSS:
891 		/* Command Aborted due to Power Loss Notification */
892 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
893 		cmd->nc_nvme->n_dead = B_TRUE;
894 		return (EIO);
895 
896 	case NVME_CQE_SC_GEN_ABORT_SQ_DEL:
897 		/* Command Aborted due to SQ Deletion */
898 		atomic_inc_32(&cmd->nc_nvme->n_abort_sq_del);
899 		return (EIO);
900 
901 	case NVME_CQE_SC_GEN_NVM_CAP_EXC:
902 		/* Capacity Exceeded */
903 		atomic_inc_32(&cmd->nc_nvme->n_nvm_cap_exc);
904 		bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
905 		return (EIO);
906 
907 	case NVME_CQE_SC_GEN_NVM_NS_NOTRDY:
908 		/* Namespace Not Ready */
909 		atomic_inc_32(&cmd->nc_nvme->n_nvm_ns_notrdy);
910 		bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
911 		return (EIO);
912 
913 	default:
914 		return (nvme_check_unknown_cmd_status(cmd));
915 	}
916 }
917 
918 static int
919 nvme_check_specific_cmd_status(nvme_cmd_t *cmd)
920 {
921 	nvme_cqe_t *cqe = &cmd->nc_cqe;
922 
923 	switch (cqe->cqe_sf.sf_sc) {
924 	case NVME_CQE_SC_SPC_INV_CQ:
925 		/* Completion Queue Invalid */
926 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE);
927 		atomic_inc_32(&cmd->nc_nvme->n_inv_cq_err);
928 		return (EINVAL);
929 
930 	case NVME_CQE_SC_SPC_INV_QID:
931 		/* Invalid Queue Identifier */
932 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
933 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_SQUEUE ||
934 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE ||
935 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
936 		atomic_inc_32(&cmd->nc_nvme->n_inv_qid_err);
937 		return (EINVAL);
938 
939 	case NVME_CQE_SC_SPC_MAX_QSZ_EXC:
940 		/* Max Queue Size Exceeded */
941 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
942 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
943 		atomic_inc_32(&cmd->nc_nvme->n_max_qsz_exc);
944 		return (EINVAL);
945 
946 	case NVME_CQE_SC_SPC_ABRT_CMD_EXC:
947 		/* Abort Command Limit Exceeded */
948 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT);
949 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
950 		    "abort command limit exceeded in cmd %p", (void *)cmd);
951 		return (0);
952 
953 	case NVME_CQE_SC_SPC_ASYNC_EVREQ_EXC:
954 		/* Async Event Request Limit Exceeded */
955 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ASYNC_EVENT);
956 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
957 		    "async event request limit exceeded in cmd %p",
958 		    (void *)cmd);
959 		return (0);
960 
961 	case NVME_CQE_SC_SPC_INV_INT_VECT:
962 		/* Invalid Interrupt Vector */
963 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
964 		atomic_inc_32(&cmd->nc_nvme->n_inv_int_vect);
965 		return (EINVAL);
966 
967 	case NVME_CQE_SC_SPC_INV_LOG_PAGE:
968 		/* Invalid Log Page */
969 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_GET_LOG_PAGE);
970 		atomic_inc_32(&cmd->nc_nvme->n_inv_log_page);
971 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
972 		return (EINVAL);
973 
974 	case NVME_CQE_SC_SPC_INV_FORMAT:
975 		/* Invalid Format */
976 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_FORMAT);
977 		atomic_inc_32(&cmd->nc_nvme->n_inv_format);
978 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
979 		return (EINVAL);
980 
981 	case NVME_CQE_SC_SPC_INV_Q_DEL:
982 		/* Invalid Queue Deletion */
983 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
984 		atomic_inc_32(&cmd->nc_nvme->n_inv_q_del);
985 		return (EINVAL);
986 
987 	case NVME_CQE_SC_SPC_NVM_CNFL_ATTR:
988 		/* Conflicting Attributes */
989 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_DSET_MGMT ||
990 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
991 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
992 		atomic_inc_32(&cmd->nc_nvme->n_cnfl_attr);
993 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
994 		return (EINVAL);
995 
996 	case NVME_CQE_SC_SPC_NVM_INV_PROT:
997 		/* Invalid Protection Information */
998 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_COMPARE ||
999 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
1000 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1001 		atomic_inc_32(&cmd->nc_nvme->n_inv_prot);
1002 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1003 		return (EINVAL);
1004 
1005 	case NVME_CQE_SC_SPC_NVM_READONLY:
1006 		/* Write to Read Only Range */
1007 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1008 		atomic_inc_32(&cmd->nc_nvme->n_readonly);
1009 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1010 		return (EROFS);
1011 
1012 	default:
1013 		return (nvme_check_unknown_cmd_status(cmd));
1014 	}
1015 }
1016 
1017 static inline int
1018 nvme_check_cmd_status(nvme_cmd_t *cmd)
1019 {
1020 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1021 
1022 	/* take a shortcut if everything is alright */
1023 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1024 	    cqe->cqe_sf.sf_sc == NVME_CQE_SC_GEN_SUCCESS)
1025 		return (0);
1026 
1027 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC)
1028 		return (nvme_check_generic_cmd_status(cmd));
1029 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_SPECIFIC)
1030 		return (nvme_check_specific_cmd_status(cmd));
1031 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_INTEGRITY)
1032 		return (nvme_check_integrity_cmd_status(cmd));
1033 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_VENDOR)
1034 		return (nvme_check_vendor_cmd_status(cmd));
1035 
1036 	return (nvme_check_unknown_cmd_status(cmd));
1037 }
1038 
1039 /*
1040  * nvme_abort_cmd_cb -- replaces nc_callback of aborted commands
1041  *
1042  * This functions takes care of cleaning up aborted commands. The command
1043  * status is checked to catch any fatal errors.
1044  */
1045 static void
1046 nvme_abort_cmd_cb(void *arg)
1047 {
1048 	nvme_cmd_t *cmd = arg;
1049 
1050 	/*
1051 	 * Grab the command mutex. Once we have it we hold the last reference
1052 	 * to the command and can safely free it.
1053 	 */
1054 	mutex_enter(&cmd->nc_mutex);
1055 	(void) nvme_check_cmd_status(cmd);
1056 	mutex_exit(&cmd->nc_mutex);
1057 
1058 	nvme_free_cmd(cmd);
1059 }
1060 
1061 static void
1062 nvme_abort_cmd(nvme_cmd_t *abort_cmd)
1063 {
1064 	nvme_t *nvme = abort_cmd->nc_nvme;
1065 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1066 	nvme_abort_cmd_t ac = { 0 };
1067 
1068 	sema_p(&nvme->n_abort_sema);
1069 
1070 	ac.b.ac_cid = abort_cmd->nc_sqe.sqe_cid;
1071 	ac.b.ac_sqid = abort_cmd->nc_sqid;
1072 
1073 	/*
1074 	 * Drop the mutex of the aborted command. From this point on
1075 	 * we must assume that the abort callback has freed the command.
1076 	 */
1077 	mutex_exit(&abort_cmd->nc_mutex);
1078 
1079 	cmd->nc_sqid = 0;
1080 	cmd->nc_sqe.sqe_opc = NVME_OPC_ABORT;
1081 	cmd->nc_callback = nvme_wakeup_cmd;
1082 	cmd->nc_sqe.sqe_cdw10 = ac.r;
1083 
1084 	/*
1085 	 * Send the ABORT to the hardware. The ABORT command will return _after_
1086 	 * the aborted command has completed (aborted or otherwise).
1087 	 */
1088 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1089 		sema_v(&nvme->n_abort_sema);
1090 		dev_err(nvme->n_dip, CE_WARN,
1091 		    "!nvme_admin_cmd failed for ABORT");
1092 		atomic_inc_32(&nvme->n_abort_failed);
1093 		return;
1094 	}
1095 	sema_v(&nvme->n_abort_sema);
1096 
1097 	if (nvme_check_cmd_status(cmd)) {
1098 		dev_err(nvme->n_dip, CE_WARN,
1099 		    "!ABORT failed with sct = %x, sc = %x",
1100 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1101 		atomic_inc_32(&nvme->n_abort_failed);
1102 	} else {
1103 		atomic_inc_32(&nvme->n_cmd_aborted);
1104 	}
1105 
1106 	nvme_free_cmd(cmd);
1107 }
1108 
1109 /*
1110  * nvme_wait_cmd -- wait for command completion or timeout
1111  *
1112  * Returns B_TRUE if the command completed normally.
1113  *
1114  * Returns B_FALSE if the command timed out and an abort was attempted. The
1115  * command mutex will be dropped and the command must be considered freed. The
1116  * freeing of the command is normally done by the abort command callback.
1117  *
1118  * In case of a serious error or a timeout of the abort command the hardware
1119  * will be declared dead and FMA will be notified.
1120  */
1121 static boolean_t
1122 nvme_wait_cmd(nvme_cmd_t *cmd, uint_t usec)
1123 {
1124 	clock_t timeout = ddi_get_lbolt() + drv_usectohz(usec);
1125 	nvme_t *nvme = cmd->nc_nvme;
1126 	nvme_reg_csts_t csts;
1127 
1128 	ASSERT(mutex_owned(&cmd->nc_mutex));
1129 
1130 	while (!cmd->nc_completed) {
1131 		if (cv_timedwait(&cmd->nc_cv, &cmd->nc_mutex, timeout) == -1)
1132 			break;
1133 	}
1134 
1135 	if (cmd->nc_completed)
1136 		return (B_TRUE);
1137 
1138 	/*
1139 	 * The command timed out. Change the callback to the cleanup function.
1140 	 */
1141 	cmd->nc_callback = nvme_abort_cmd_cb;
1142 
1143 	/*
1144 	 * Check controller for fatal status, any errors associated with the
1145 	 * register or DMA handle, or for a double timeout (abort command timed
1146 	 * out). If necessary log a warning and call FMA.
1147 	 */
1148 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1149 	dev_err(nvme->n_dip, CE_WARN, "!command timeout, "
1150 	    "OPC = %x, CFS = %d", cmd->nc_sqe.sqe_opc, csts.b.csts_cfs);
1151 	atomic_inc_32(&nvme->n_cmd_timeout);
1152 
1153 	if (csts.b.csts_cfs ||
1154 	    nvme_check_regs_hdl(nvme) ||
1155 	    nvme_check_dma_hdl(cmd->nc_dma) ||
1156 	    cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT) {
1157 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1158 		nvme->n_dead = B_TRUE;
1159 		mutex_exit(&cmd->nc_mutex);
1160 	} else {
1161 		/*
1162 		 * Try to abort the command. The command mutex is released by
1163 		 * nvme_abort_cmd().
1164 		 * If the abort succeeds it will have freed the aborted command.
1165 		 * If the abort fails for other reasons we must assume that the
1166 		 * command may complete at any time, and the callback will free
1167 		 * it for us.
1168 		 */
1169 		nvme_abort_cmd(cmd);
1170 	}
1171 
1172 	return (B_FALSE);
1173 }
1174 
1175 static void
1176 nvme_wakeup_cmd(void *arg)
1177 {
1178 	nvme_cmd_t *cmd = arg;
1179 
1180 	mutex_enter(&cmd->nc_mutex);
1181 	/*
1182 	 * There is a slight chance that this command completed shortly after
1183 	 * the timeout was hit in nvme_wait_cmd() but before the callback was
1184 	 * changed. Catch that case here and clean up accordingly.
1185 	 */
1186 	if (cmd->nc_callback == nvme_abort_cmd_cb) {
1187 		mutex_exit(&cmd->nc_mutex);
1188 		nvme_abort_cmd_cb(cmd);
1189 		return;
1190 	}
1191 
1192 	cmd->nc_completed = B_TRUE;
1193 	cv_signal(&cmd->nc_cv);
1194 	mutex_exit(&cmd->nc_mutex);
1195 }
1196 
1197 static void
1198 nvme_async_event_task(void *arg)
1199 {
1200 	nvme_cmd_t *cmd = arg;
1201 	nvme_t *nvme = cmd->nc_nvme;
1202 	nvme_error_log_entry_t *error_log = NULL;
1203 	nvme_health_log_t *health_log = NULL;
1204 	nvme_async_event_t event;
1205 	int ret;
1206 
1207 	/*
1208 	 * Check for errors associated with the async request itself. The only
1209 	 * command-specific error is "async event limit exceeded", which
1210 	 * indicates a programming error in the driver and causes a panic in
1211 	 * nvme_check_cmd_status().
1212 	 *
1213 	 * Other possible errors are various scenarios where the async request
1214 	 * was aborted, or internal errors in the device. Internal errors are
1215 	 * reported to FMA, the command aborts need no special handling here.
1216 	 */
1217 	if (nvme_check_cmd_status(cmd)) {
1218 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1219 		    "!async event request returned failure, sct = %x, "
1220 		    "sc = %x, dnr = %d, m = %d", cmd->nc_cqe.cqe_sf.sf_sct,
1221 		    cmd->nc_cqe.cqe_sf.sf_sc, cmd->nc_cqe.cqe_sf.sf_dnr,
1222 		    cmd->nc_cqe.cqe_sf.sf_m);
1223 
1224 		if (cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1225 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INTERNAL_ERR) {
1226 			cmd->nc_nvme->n_dead = B_TRUE;
1227 			ddi_fm_service_impact(cmd->nc_nvme->n_dip,
1228 			    DDI_SERVICE_LOST);
1229 		}
1230 		nvme_free_cmd(cmd);
1231 		return;
1232 	}
1233 
1234 
1235 	event.r = cmd->nc_cqe.cqe_dw0;
1236 
1237 	/* Clear CQE and re-submit the async request. */
1238 	bzero(&cmd->nc_cqe, sizeof (nvme_cqe_t));
1239 	ret = nvme_submit_cmd(nvme->n_adminq, cmd);
1240 
1241 	if (ret != DDI_SUCCESS) {
1242 		dev_err(nvme->n_dip, CE_WARN,
1243 		    "!failed to resubmit async event request");
1244 		atomic_inc_32(&nvme->n_async_resubmit_failed);
1245 		nvme_free_cmd(cmd);
1246 	}
1247 
1248 	switch (event.b.ae_type) {
1249 	case NVME_ASYNC_TYPE_ERROR:
1250 		if (event.b.ae_logpage == NVME_LOGPAGE_ERROR) {
1251 			error_log = (nvme_error_log_entry_t *)
1252 			    nvme_get_logpage(nvme, event.b.ae_logpage);
1253 		} else {
1254 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1255 			    "async event reply: %d", event.b.ae_logpage);
1256 			atomic_inc_32(&nvme->n_wrong_logpage);
1257 		}
1258 
1259 		switch (event.b.ae_info) {
1260 		case NVME_ASYNC_ERROR_INV_SQ:
1261 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1262 			    "invalid submission queue");
1263 			return;
1264 
1265 		case NVME_ASYNC_ERROR_INV_DBL:
1266 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1267 			    "invalid doorbell write value");
1268 			return;
1269 
1270 		case NVME_ASYNC_ERROR_DIAGFAIL:
1271 			dev_err(nvme->n_dip, CE_WARN, "!diagnostic failure");
1272 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1273 			nvme->n_dead = B_TRUE;
1274 			atomic_inc_32(&nvme->n_diagfail_event);
1275 			break;
1276 
1277 		case NVME_ASYNC_ERROR_PERSISTENT:
1278 			dev_err(nvme->n_dip, CE_WARN, "!persistent internal "
1279 			    "device error");
1280 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1281 			nvme->n_dead = B_TRUE;
1282 			atomic_inc_32(&nvme->n_persistent_event);
1283 			break;
1284 
1285 		case NVME_ASYNC_ERROR_TRANSIENT:
1286 			dev_err(nvme->n_dip, CE_WARN, "!transient internal "
1287 			    "device error");
1288 			/* TODO: send ereport */
1289 			atomic_inc_32(&nvme->n_transient_event);
1290 			break;
1291 
1292 		case NVME_ASYNC_ERROR_FW_LOAD:
1293 			dev_err(nvme->n_dip, CE_WARN,
1294 			    "!firmware image load error");
1295 			atomic_inc_32(&nvme->n_fw_load_event);
1296 			break;
1297 		}
1298 		break;
1299 
1300 	case NVME_ASYNC_TYPE_HEALTH:
1301 		if (event.b.ae_logpage == NVME_LOGPAGE_HEALTH) {
1302 			health_log = (nvme_health_log_t *)
1303 			    nvme_get_logpage(nvme, event.b.ae_logpage, -1);
1304 		} else {
1305 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1306 			    "async event reply: %d", event.b.ae_logpage);
1307 			atomic_inc_32(&nvme->n_wrong_logpage);
1308 		}
1309 
1310 		switch (event.b.ae_info) {
1311 		case NVME_ASYNC_HEALTH_RELIABILITY:
1312 			dev_err(nvme->n_dip, CE_WARN,
1313 			    "!device reliability compromised");
1314 			/* TODO: send ereport */
1315 			atomic_inc_32(&nvme->n_reliability_event);
1316 			break;
1317 
1318 		case NVME_ASYNC_HEALTH_TEMPERATURE:
1319 			dev_err(nvme->n_dip, CE_WARN,
1320 			    "!temperature above threshold");
1321 			/* TODO: send ereport */
1322 			atomic_inc_32(&nvme->n_temperature_event);
1323 			break;
1324 
1325 		case NVME_ASYNC_HEALTH_SPARE:
1326 			dev_err(nvme->n_dip, CE_WARN,
1327 			    "!spare space below threshold");
1328 			/* TODO: send ereport */
1329 			atomic_inc_32(&nvme->n_spare_event);
1330 			break;
1331 		}
1332 		break;
1333 
1334 	case NVME_ASYNC_TYPE_VENDOR:
1335 		dev_err(nvme->n_dip, CE_WARN, "!vendor specific async event "
1336 		    "received, info = %x, logpage = %x", event.b.ae_info,
1337 		    event.b.ae_logpage);
1338 		atomic_inc_32(&nvme->n_vendor_event);
1339 		break;
1340 
1341 	default:
1342 		dev_err(nvme->n_dip, CE_WARN, "!unknown async event received, "
1343 		    "type = %x, info = %x, logpage = %x", event.b.ae_type,
1344 		    event.b.ae_info, event.b.ae_logpage);
1345 		atomic_inc_32(&nvme->n_unknown_event);
1346 		break;
1347 	}
1348 
1349 	if (error_log)
1350 		kmem_free(error_log, sizeof (nvme_error_log_entry_t) *
1351 		    nvme->n_error_log_len);
1352 
1353 	if (health_log)
1354 		kmem_free(health_log, sizeof (nvme_health_log_t));
1355 }
1356 
1357 static int
1358 nvme_admin_cmd(nvme_cmd_t *cmd, int usec)
1359 {
1360 	int ret;
1361 
1362 	mutex_enter(&cmd->nc_mutex);
1363 	ret = nvme_submit_cmd(cmd->nc_nvme->n_adminq, cmd);
1364 
1365 	if (ret != DDI_SUCCESS) {
1366 		mutex_exit(&cmd->nc_mutex);
1367 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1368 		    "!nvme_submit_cmd failed");
1369 		atomic_inc_32(&cmd->nc_nvme->n_admin_queue_full);
1370 		nvme_free_cmd(cmd);
1371 		return (DDI_FAILURE);
1372 	}
1373 
1374 	if (nvme_wait_cmd(cmd, usec) == B_FALSE) {
1375 		/*
1376 		 * The command timed out. An abort command was posted that
1377 		 * will take care of the cleanup.
1378 		 */
1379 		return (DDI_FAILURE);
1380 	}
1381 	mutex_exit(&cmd->nc_mutex);
1382 
1383 	return (DDI_SUCCESS);
1384 }
1385 
1386 static int
1387 nvme_async_event(nvme_t *nvme)
1388 {
1389 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1390 	int ret;
1391 
1392 	cmd->nc_sqid = 0;
1393 	cmd->nc_sqe.sqe_opc = NVME_OPC_ASYNC_EVENT;
1394 	cmd->nc_callback = nvme_async_event_task;
1395 
1396 	ret = nvme_submit_cmd(nvme->n_adminq, cmd);
1397 
1398 	if (ret != DDI_SUCCESS) {
1399 		dev_err(nvme->n_dip, CE_WARN,
1400 		    "!nvme_submit_cmd failed for ASYNCHRONOUS EVENT");
1401 		nvme_free_cmd(cmd);
1402 		return (DDI_FAILURE);
1403 	}
1404 
1405 	return (DDI_SUCCESS);
1406 }
1407 
1408 static void *
1409 nvme_get_logpage(nvme_t *nvme, uint8_t logpage, ...)
1410 {
1411 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1412 	void *buf = NULL;
1413 	nvme_getlogpage_t getlogpage;
1414 	size_t bufsize;
1415 	va_list ap;
1416 
1417 	va_start(ap, logpage);
1418 
1419 	cmd->nc_sqid = 0;
1420 	cmd->nc_callback = nvme_wakeup_cmd;
1421 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_LOG_PAGE;
1422 
1423 	getlogpage.b.lp_lid = logpage;
1424 
1425 	switch (logpage) {
1426 	case NVME_LOGPAGE_ERROR:
1427 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1428 		bufsize = nvme->n_error_log_len *
1429 		    sizeof (nvme_error_log_entry_t);
1430 		break;
1431 
1432 	case NVME_LOGPAGE_HEALTH:
1433 		cmd->nc_sqe.sqe_nsid = va_arg(ap, uint32_t);
1434 		bufsize = sizeof (nvme_health_log_t);
1435 		break;
1436 
1437 	case NVME_LOGPAGE_FWSLOT:
1438 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1439 		bufsize = sizeof (nvme_fwslot_log_t);
1440 		break;
1441 
1442 	default:
1443 		dev_err(nvme->n_dip, CE_WARN, "!unknown log page requested: %d",
1444 		    logpage);
1445 		atomic_inc_32(&nvme->n_unknown_logpage);
1446 		goto fail;
1447 	}
1448 
1449 	va_end(ap);
1450 
1451 	getlogpage.b.lp_numd = bufsize / sizeof (uint32_t) - 1;
1452 
1453 	cmd->nc_sqe.sqe_cdw10 = getlogpage.r;
1454 
1455 	if (nvme_zalloc_dma(nvme, getlogpage.b.lp_numd * sizeof (uint32_t),
1456 	    DDI_DMA_READ, &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1457 		dev_err(nvme->n_dip, CE_WARN,
1458 		    "!nvme_zalloc_dma failed for GET LOG PAGE");
1459 		goto fail;
1460 	}
1461 
1462 	if (cmd->nc_dma->nd_ncookie > 2) {
1463 		dev_err(nvme->n_dip, CE_WARN,
1464 		    "!too many DMA cookies for GET LOG PAGE");
1465 		atomic_inc_32(&nvme->n_too_many_cookies);
1466 		goto fail;
1467 	}
1468 
1469 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1470 	if (cmd->nc_dma->nd_ncookie > 1) {
1471 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1472 		    &cmd->nc_dma->nd_cookie);
1473 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1474 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1475 	}
1476 
1477 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1478 		dev_err(nvme->n_dip, CE_WARN,
1479 		    "!nvme_admin_cmd failed for GET LOG PAGE");
1480 		return (NULL);
1481 	}
1482 
1483 	if (nvme_check_cmd_status(cmd)) {
1484 		dev_err(nvme->n_dip, CE_WARN,
1485 		    "!GET LOG PAGE failed with sct = %x, sc = %x",
1486 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1487 		goto fail;
1488 	}
1489 
1490 	buf = kmem_alloc(bufsize, KM_SLEEP);
1491 	bcopy(cmd->nc_dma->nd_memp, buf, bufsize);
1492 
1493 fail:
1494 	nvme_free_cmd(cmd);
1495 
1496 	return (buf);
1497 }
1498 
1499 static void *
1500 nvme_identify(nvme_t *nvme, uint32_t nsid)
1501 {
1502 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1503 	void *buf = NULL;
1504 
1505 	cmd->nc_sqid = 0;
1506 	cmd->nc_callback = nvme_wakeup_cmd;
1507 	cmd->nc_sqe.sqe_opc = NVME_OPC_IDENTIFY;
1508 	cmd->nc_sqe.sqe_nsid = nsid;
1509 	cmd->nc_sqe.sqe_cdw10 = nsid ? NVME_IDENTIFY_NSID : NVME_IDENTIFY_CTRL;
1510 
1511 	if (nvme_zalloc_dma(nvme, NVME_IDENTIFY_BUFSIZE, DDI_DMA_READ,
1512 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1513 		dev_err(nvme->n_dip, CE_WARN,
1514 		    "!nvme_zalloc_dma failed for IDENTIFY");
1515 		goto fail;
1516 	}
1517 
1518 	if (cmd->nc_dma->nd_ncookie > 2) {
1519 		dev_err(nvme->n_dip, CE_WARN,
1520 		    "!too many DMA cookies for IDENTIFY");
1521 		atomic_inc_32(&nvme->n_too_many_cookies);
1522 		goto fail;
1523 	}
1524 
1525 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1526 	if (cmd->nc_dma->nd_ncookie > 1) {
1527 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1528 		    &cmd->nc_dma->nd_cookie);
1529 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1530 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1531 	}
1532 
1533 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1534 		dev_err(nvme->n_dip, CE_WARN,
1535 		    "!nvme_admin_cmd failed for IDENTIFY");
1536 		return (NULL);
1537 	}
1538 
1539 	if (nvme_check_cmd_status(cmd)) {
1540 		dev_err(nvme->n_dip, CE_WARN,
1541 		    "!IDENTIFY failed with sct = %x, sc = %x",
1542 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1543 		goto fail;
1544 	}
1545 
1546 	buf = kmem_alloc(NVME_IDENTIFY_BUFSIZE, KM_SLEEP);
1547 	bcopy(cmd->nc_dma->nd_memp, buf, NVME_IDENTIFY_BUFSIZE);
1548 
1549 fail:
1550 	nvme_free_cmd(cmd);
1551 
1552 	return (buf);
1553 }
1554 
1555 static int
1556 nvme_set_nqueues(nvme_t *nvme, uint16_t nqueues)
1557 {
1558 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1559 	nvme_nqueue_t nq = { 0 };
1560 
1561 	nq.b.nq_nsq = nq.b.nq_ncq = nqueues;
1562 
1563 	cmd->nc_sqid = 0;
1564 	cmd->nc_callback = nvme_wakeup_cmd;
1565 	cmd->nc_sqe.sqe_opc = NVME_OPC_SET_FEATURES;
1566 	cmd->nc_sqe.sqe_cdw10 = NVME_FEAT_NQUEUES;
1567 	cmd->nc_sqe.sqe_cdw11 = nq.r;
1568 
1569 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1570 		dev_err(nvme->n_dip, CE_WARN,
1571 		    "!nvme_admin_cmd failed for SET FEATURES (NQUEUES)");
1572 		return (0);
1573 	}
1574 
1575 	if (nvme_check_cmd_status(cmd)) {
1576 		dev_err(nvme->n_dip, CE_WARN,
1577 		    "!SET FEATURES (NQUEUES) failed with sct = %x, sc = %x",
1578 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1579 		nvme_free_cmd(cmd);
1580 		return (0);
1581 	}
1582 
1583 	nq.r = cmd->nc_cqe.cqe_dw0;
1584 	nvme_free_cmd(cmd);
1585 
1586 	/*
1587 	 * Always use the same number of submission and completion queues, and
1588 	 * never use more than the requested number of queues.
1589 	 */
1590 	return (MIN(nqueues, MIN(nq.b.nq_nsq, nq.b.nq_ncq)));
1591 }
1592 
1593 static int
1594 nvme_create_io_qpair(nvme_t *nvme, nvme_qpair_t *qp, uint16_t idx)
1595 {
1596 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1597 	nvme_create_queue_dw10_t dw10 = { 0 };
1598 	nvme_create_cq_dw11_t c_dw11 = { 0 };
1599 	nvme_create_sq_dw11_t s_dw11 = { 0 };
1600 
1601 	dw10.b.q_qid = idx;
1602 	dw10.b.q_qsize = qp->nq_nentry - 1;
1603 
1604 	c_dw11.b.cq_pc = 1;
1605 	c_dw11.b.cq_ien = 1;
1606 	c_dw11.b.cq_iv = idx % nvme->n_intr_cnt;
1607 
1608 	cmd->nc_sqid = 0;
1609 	cmd->nc_callback = nvme_wakeup_cmd;
1610 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_CQUEUE;
1611 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
1612 	cmd->nc_sqe.sqe_cdw11 = c_dw11.r;
1613 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_cqdma->nd_cookie.dmac_laddress;
1614 
1615 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1616 		dev_err(nvme->n_dip, CE_WARN,
1617 		    "!nvme_admin_cmd failed for CREATE CQUEUE");
1618 		return (DDI_FAILURE);
1619 	}
1620 
1621 	if (nvme_check_cmd_status(cmd)) {
1622 		dev_err(nvme->n_dip, CE_WARN,
1623 		    "!CREATE CQUEUE failed with sct = %x, sc = %x",
1624 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1625 		nvme_free_cmd(cmd);
1626 		return (DDI_FAILURE);
1627 	}
1628 
1629 	nvme_free_cmd(cmd);
1630 
1631 	s_dw11.b.sq_pc = 1;
1632 	s_dw11.b.sq_cqid = idx;
1633 
1634 	cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1635 	cmd->nc_sqid = 0;
1636 	cmd->nc_callback = nvme_wakeup_cmd;
1637 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_SQUEUE;
1638 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
1639 	cmd->nc_sqe.sqe_cdw11 = s_dw11.r;
1640 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_sqdma->nd_cookie.dmac_laddress;
1641 
1642 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1643 		dev_err(nvme->n_dip, CE_WARN,
1644 		    "!nvme_admin_cmd failed for CREATE SQUEUE");
1645 		return (DDI_FAILURE);
1646 	}
1647 
1648 	if (nvme_check_cmd_status(cmd)) {
1649 		dev_err(nvme->n_dip, CE_WARN,
1650 		    "!CREATE SQUEUE failed with sct = %x, sc = %x",
1651 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1652 		nvme_free_cmd(cmd);
1653 		return (DDI_FAILURE);
1654 	}
1655 
1656 	nvme_free_cmd(cmd);
1657 
1658 	return (DDI_SUCCESS);
1659 }
1660 
1661 static boolean_t
1662 nvme_reset(nvme_t *nvme, boolean_t quiesce)
1663 {
1664 	nvme_reg_csts_t csts;
1665 	int i;
1666 
1667 	nvme_put32(nvme, NVME_REG_CC, 0);
1668 
1669 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1670 	if (csts.b.csts_rdy == 1) {
1671 		nvme_put32(nvme, NVME_REG_CC, 0);
1672 		for (i = 0; i != nvme->n_timeout * 10; i++) {
1673 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1674 			if (csts.b.csts_rdy == 0)
1675 				break;
1676 
1677 			if (quiesce)
1678 				drv_usecwait(50000);
1679 			else
1680 				delay(drv_usectohz(50000));
1681 		}
1682 	}
1683 
1684 	nvme_put32(nvme, NVME_REG_AQA, 0);
1685 	nvme_put32(nvme, NVME_REG_ASQ, 0);
1686 	nvme_put32(nvme, NVME_REG_ACQ, 0);
1687 
1688 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1689 	return (csts.b.csts_rdy == 0 ? B_TRUE : B_FALSE);
1690 }
1691 
1692 static void
1693 nvme_shutdown(nvme_t *nvme, int mode, boolean_t quiesce)
1694 {
1695 	nvme_reg_cc_t cc;
1696 	nvme_reg_csts_t csts;
1697 	int i;
1698 
1699 	ASSERT(mode == NVME_CC_SHN_NORMAL || mode == NVME_CC_SHN_ABRUPT);
1700 
1701 	cc.r = nvme_get32(nvme, NVME_REG_CC);
1702 	cc.b.cc_shn = mode & 0x3;
1703 	nvme_put32(nvme, NVME_REG_CC, cc.r);
1704 
1705 	for (i = 0; i != 10; i++) {
1706 		csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1707 		if (csts.b.csts_shst == NVME_CSTS_SHN_COMPLETE)
1708 			break;
1709 
1710 		if (quiesce)
1711 			drv_usecwait(100000);
1712 		else
1713 			delay(drv_usectohz(100000));
1714 	}
1715 }
1716 
1717 
1718 static void
1719 nvme_prepare_devid(nvme_t *nvme, uint32_t nsid)
1720 {
1721 	char model[sizeof (nvme->n_idctl->id_model) + 1];
1722 	char serial[sizeof (nvme->n_idctl->id_serial) + 1];
1723 
1724 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
1725 	bcopy(nvme->n_idctl->id_serial, serial,
1726 	    sizeof (nvme->n_idctl->id_serial));
1727 
1728 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
1729 	serial[sizeof (nvme->n_idctl->id_serial)] = '\0';
1730 
1731 	(void) snprintf(nvme->n_ns[nsid - 1].ns_devid,
1732 	    sizeof (nvme->n_ns[0].ns_devid), "%4X-%s-%s-%X",
1733 	    nvme->n_idctl->id_vid, model, serial, nsid);
1734 }
1735 
1736 static int
1737 nvme_init(nvme_t *nvme)
1738 {
1739 	nvme_reg_cc_t cc = { 0 };
1740 	nvme_reg_aqa_t aqa = { 0 };
1741 	nvme_reg_asq_t asq = { 0 };
1742 	nvme_reg_acq_t acq = { 0 };
1743 	nvme_reg_cap_t cap;
1744 	nvme_reg_vs_t vs;
1745 	nvme_reg_csts_t csts;
1746 	int i = 0;
1747 	int nqueues;
1748 	char model[sizeof (nvme->n_idctl->id_model) + 1];
1749 	char *vendor, *product;
1750 
1751 	/* Setup fixed interrupt for admin queue. */
1752 	if (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_FIXED, 1)
1753 	    != DDI_SUCCESS) {
1754 		dev_err(nvme->n_dip, CE_WARN,
1755 		    "!failed to setup fixed interrupt");
1756 		goto fail;
1757 	}
1758 
1759 	/* Check controller version */
1760 	vs.r = nvme_get32(nvme, NVME_REG_VS);
1761 	dev_err(nvme->n_dip, CE_CONT, "?NVMe spec version %d.%d",
1762 	    vs.b.vs_mjr, vs.b.vs_mnr);
1763 
1764 	if (nvme_version_major < vs.b.vs_mjr ||
1765 	    (nvme_version_major == vs.b.vs_mjr &&
1766 	    nvme_version_minor < vs.b.vs_mnr)) {
1767 		dev_err(nvme->n_dip, CE_WARN, "!no support for version > %d.%d",
1768 		    nvme_version_major, nvme_version_minor);
1769 		if (nvme->n_strict_version)
1770 			goto fail;
1771 	}
1772 
1773 	/* retrieve controller configuration */
1774 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
1775 
1776 	if ((cap.b.cap_css & NVME_CAP_CSS_NVM) == 0) {
1777 		dev_err(nvme->n_dip, CE_WARN,
1778 		    "!NVM command set not supported by hardware");
1779 		goto fail;
1780 	}
1781 
1782 	nvme->n_nssr_supported = cap.b.cap_nssrs;
1783 	nvme->n_doorbell_stride = 4 << cap.b.cap_dstrd;
1784 	nvme->n_timeout = cap.b.cap_to;
1785 	nvme->n_arbitration_mechanisms = cap.b.cap_ams;
1786 	nvme->n_cont_queues_reqd = cap.b.cap_cqr;
1787 	nvme->n_max_queue_entries = cap.b.cap_mqes + 1;
1788 
1789 	/*
1790 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to specify
1791 	 * the base page size of 4k (1<<12), so add 12 here to get the real
1792 	 * page size value.
1793 	 */
1794 	nvme->n_pageshift = MIN(MAX(cap.b.cap_mpsmin + 12, PAGESHIFT),
1795 	    cap.b.cap_mpsmax + 12);
1796 	nvme->n_pagesize = 1UL << (nvme->n_pageshift);
1797 
1798 	/*
1799 	 * Set up Queue DMA to transfer at least 1 page-aligned page at a time.
1800 	 */
1801 	nvme->n_queue_dma_attr.dma_attr_align = nvme->n_pagesize;
1802 	nvme->n_queue_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
1803 
1804 	/*
1805 	 * Set up PRP DMA to transfer 1 page-aligned page at a time.
1806 	 * Maxxfer may be increased after we identified the controller limits.
1807 	 */
1808 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_pagesize;
1809 	nvme->n_prp_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
1810 	nvme->n_prp_dma_attr.dma_attr_align = nvme->n_pagesize;
1811 
1812 	/*
1813 	 * Reset controller if it's still in ready state.
1814 	 */
1815 	if (nvme_reset(nvme, B_FALSE) == B_FALSE) {
1816 		dev_err(nvme->n_dip, CE_WARN, "!unable to reset controller");
1817 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1818 		nvme->n_dead = B_TRUE;
1819 		goto fail;
1820 	}
1821 
1822 	/*
1823 	 * Create the admin queue pair.
1824 	 */
1825 	if (nvme_alloc_qpair(nvme, nvme->n_admin_queue_len, &nvme->n_adminq, 0)
1826 	    != DDI_SUCCESS) {
1827 		dev_err(nvme->n_dip, CE_WARN,
1828 		    "!unable to allocate admin qpair");
1829 		goto fail;
1830 	}
1831 	nvme->n_ioq = kmem_alloc(sizeof (nvme_qpair_t *), KM_SLEEP);
1832 	nvme->n_ioq[0] = nvme->n_adminq;
1833 
1834 	nvme->n_progress |= NVME_ADMIN_QUEUE;
1835 
1836 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
1837 	    "admin-queue-len", nvme->n_admin_queue_len);
1838 
1839 	aqa.b.aqa_asqs = aqa.b.aqa_acqs = nvme->n_admin_queue_len - 1;
1840 	asq = nvme->n_adminq->nq_sqdma->nd_cookie.dmac_laddress;
1841 	acq = nvme->n_adminq->nq_cqdma->nd_cookie.dmac_laddress;
1842 
1843 	ASSERT((asq & (nvme->n_pagesize - 1)) == 0);
1844 	ASSERT((acq & (nvme->n_pagesize - 1)) == 0);
1845 
1846 	nvme_put32(nvme, NVME_REG_AQA, aqa.r);
1847 	nvme_put64(nvme, NVME_REG_ASQ, asq);
1848 	nvme_put64(nvme, NVME_REG_ACQ, acq);
1849 
1850 	cc.b.cc_ams = 0; /* use Round-Robin arbitration */
1851 	cc.b.cc_css = 0; /* use NVM command set */
1852 	cc.b.cc_mps = nvme->n_pageshift - 12;
1853 	cc.b.cc_shn = 0; /* no shutdown in progress */
1854 	cc.b.cc_en = 1;  /* enable controller */
1855 
1856 	nvme_put32(nvme, NVME_REG_CC, cc.r);
1857 
1858 	/*
1859 	 * Wait for the controller to become ready.
1860 	 */
1861 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1862 	if (csts.b.csts_rdy == 0) {
1863 		for (i = 0; i != nvme->n_timeout * 10; i++) {
1864 			delay(drv_usectohz(50000));
1865 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1866 
1867 			if (csts.b.csts_cfs == 1) {
1868 				dev_err(nvme->n_dip, CE_WARN,
1869 				    "!controller fatal status at init");
1870 				ddi_fm_service_impact(nvme->n_dip,
1871 				    DDI_SERVICE_LOST);
1872 				nvme->n_dead = B_TRUE;
1873 				goto fail;
1874 			}
1875 
1876 			if (csts.b.csts_rdy == 1)
1877 				break;
1878 		}
1879 	}
1880 
1881 	if (csts.b.csts_rdy == 0) {
1882 		dev_err(nvme->n_dip, CE_WARN, "!controller not ready");
1883 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1884 		nvme->n_dead = B_TRUE;
1885 		goto fail;
1886 	}
1887 
1888 	/*
1889 	 * Assume an abort command limit of 1. We'll destroy and re-init
1890 	 * that later when we know the true abort command limit.
1891 	 */
1892 	sema_init(&nvme->n_abort_sema, 1, NULL, SEMA_DRIVER, NULL);
1893 
1894 	/*
1895 	 * Post an asynchronous event command to catch errors.
1896 	 */
1897 	if (nvme_async_event(nvme) != DDI_SUCCESS) {
1898 		dev_err(nvme->n_dip, CE_WARN,
1899 		    "!failed to post async event");
1900 		goto fail;
1901 	}
1902 
1903 	/*
1904 	 * Identify Controller
1905 	 */
1906 	nvme->n_idctl = nvme_identify(nvme, 0);
1907 	if (nvme->n_idctl == NULL) {
1908 		dev_err(nvme->n_dip, CE_WARN,
1909 		    "!failed to identify controller");
1910 		goto fail;
1911 	}
1912 
1913 	/*
1914 	 * Get Vendor & Product ID
1915 	 */
1916 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
1917 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
1918 	sata_split_model(model, &vendor, &product);
1919 
1920 	if (vendor == NULL)
1921 		nvme->n_vendor = strdup("NVMe");
1922 	else
1923 		nvme->n_vendor = strdup(vendor);
1924 
1925 	nvme->n_product = strdup(product);
1926 
1927 	/*
1928 	 * Get controller limits.
1929 	 */
1930 	nvme->n_async_event_limit = MAX(NVME_MIN_ASYNC_EVENT_LIMIT,
1931 	    MIN(nvme->n_admin_queue_len / 10,
1932 	    MIN(nvme->n_idctl->id_aerl + 1, nvme->n_async_event_limit)));
1933 
1934 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
1935 	    "async-event-limit", nvme->n_async_event_limit);
1936 
1937 	nvme->n_abort_command_limit = nvme->n_idctl->id_acl + 1;
1938 
1939 	/* disable NVMe interrupts while reinitializing the semaphore */
1940 	nvme_disable_interrupts(nvme);
1941 	sema_destroy(&nvme->n_abort_sema);
1942 	sema_init(&nvme->n_abort_sema, nvme->n_abort_command_limit - 1, NULL,
1943 	    SEMA_DRIVER, NULL);
1944 	if (nvme_enable_interrupts(nvme) != DDI_SUCCESS) {
1945 		dev_err(nvme->n_dip, CE_WARN,
1946 		    "!failed to re-enable interrupts");
1947 		goto fail;
1948 	}
1949 
1950 	nvme->n_progress |= NVME_CTRL_LIMITS;
1951 
1952 	if (nvme->n_idctl->id_mdts == 0)
1953 		nvme->n_max_data_transfer_size = nvme->n_pagesize * 65536;
1954 	else
1955 		nvme->n_max_data_transfer_size =
1956 		    1ull << (nvme->n_pageshift + nvme->n_idctl->id_mdts);
1957 
1958 	nvme->n_error_log_len = nvme->n_idctl->id_elpe + 1;
1959 
1960 	/*
1961 	 * Limit n_max_data_transfer_size to what we can handle in one PRP.
1962 	 * Chained PRPs are currently unsupported.
1963 	 *
1964 	 * This is a no-op on hardware which doesn't support a transfer size
1965 	 * big enough to require chained PRPs.
1966 	 */
1967 	nvme->n_max_data_transfer_size = MIN(nvme->n_max_data_transfer_size,
1968 	    (nvme->n_pagesize / sizeof (uint64_t) * nvme->n_pagesize));
1969 
1970 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_max_data_transfer_size;
1971 
1972 	/*
1973 	 * Make sure the minimum/maximum queue entry sizes are not
1974 	 * larger/smaller than the default.
1975 	 */
1976 
1977 	if (((1 << nvme->n_idctl->id_sqes.qes_min) > sizeof (nvme_sqe_t)) ||
1978 	    ((1 << nvme->n_idctl->id_sqes.qes_max) < sizeof (nvme_sqe_t)) ||
1979 	    ((1 << nvme->n_idctl->id_cqes.qes_min) > sizeof (nvme_cqe_t)) ||
1980 	    ((1 << nvme->n_idctl->id_cqes.qes_max) < sizeof (nvme_cqe_t)))
1981 		goto fail;
1982 
1983 	/*
1984 	 * Check for the presence of a Volatile Write Cache. If present,
1985 	 * enable it by default.
1986 	 */
1987 	if (nvme->n_idctl->id_vwc.vwc_present == 0) {
1988 		nvme->n_volatile_write_cache_enabled = B_FALSE;
1989 		nvme_bd_ops.o_sync_cache = NULL;
1990 	} else {
1991 		/*
1992 		 * TODO: send SET FEATURES to enable VWC
1993 		 * (have no hardware to test this)
1994 		 */
1995 		nvme->n_volatile_write_cache_enabled = B_FALSE;
1996 		nvme_bd_ops.o_sync_cache = NULL;
1997 	}
1998 
1999 	/*
2000 	 * Grab a copy of all mandatory log pages.
2001 	 *
2002 	 * TODO: should go away once user space tool exists to print logs
2003 	 */
2004 	nvme->n_error_log = (nvme_error_log_entry_t *)
2005 	    nvme_get_logpage(nvme, NVME_LOGPAGE_ERROR);
2006 	nvme->n_health_log = (nvme_health_log_t *)
2007 	    nvme_get_logpage(nvme, NVME_LOGPAGE_HEALTH, -1);
2008 	nvme->n_fwslot_log = (nvme_fwslot_log_t *)
2009 	    nvme_get_logpage(nvme, NVME_LOGPAGE_FWSLOT);
2010 
2011 	/*
2012 	 * Identify Namespaces
2013 	 */
2014 	nvme->n_namespace_count = nvme->n_idctl->id_nn;
2015 	nvme->n_ns = kmem_zalloc(sizeof (nvme_namespace_t) *
2016 	    nvme->n_namespace_count, KM_SLEEP);
2017 
2018 	for (i = 0; i != nvme->n_namespace_count; i++) {
2019 		nvme_identify_nsid_t *idns;
2020 		int last_rp;
2021 
2022 		nvme->n_ns[i].ns_nvme = nvme;
2023 		nvme->n_ns[i].ns_idns = idns = nvme_identify(nvme, i + 1);
2024 
2025 		if (idns == NULL) {
2026 			dev_err(nvme->n_dip, CE_WARN,
2027 			    "!failed to identify namespace %d", i + 1);
2028 			goto fail;
2029 		}
2030 
2031 		nvme->n_ns[i].ns_id = i + 1;
2032 		nvme->n_ns[i].ns_block_count = idns->id_nsize;
2033 		nvme->n_ns[i].ns_block_size =
2034 		    1 << idns->id_lbaf[idns->id_flbas.lba_format].lbaf_lbads;
2035 		nvme->n_ns[i].ns_best_block_size = nvme->n_ns[i].ns_block_size;
2036 
2037 		nvme_prepare_devid(nvme, nvme->n_ns[i].ns_id);
2038 
2039 		/*
2040 		 * Find the LBA format with no metadata and the best relative
2041 		 * performance. A value of 3 means "degraded", 0 is best.
2042 		 */
2043 		last_rp = 3;
2044 		for (int j = 0; j != idns->id_nlbaf; j++) {
2045 			if (idns->id_lbaf[j].lbaf_lbads == 0)
2046 				break;
2047 			if (idns->id_lbaf[j].lbaf_ms != 0)
2048 				continue;
2049 			if (idns->id_lbaf[j].lbaf_rp >= last_rp)
2050 				continue;
2051 			last_rp = idns->id_lbaf[j].lbaf_rp;
2052 			nvme->n_ns[i].ns_best_block_size =
2053 			    1 << idns->id_lbaf[j].lbaf_lbads;
2054 		}
2055 
2056 		/*
2057 		 * We currently don't support namespaces that use either:
2058 		 * - thin provisioning
2059 		 * - extended LBAs
2060 		 * - protection information
2061 		 */
2062 		if (idns->id_nsfeat.f_thin ||
2063 		    idns->id_flbas.lba_extlba ||
2064 		    idns->id_dps.dp_pinfo) {
2065 			dev_err(nvme->n_dip, CE_WARN,
2066 			    "!ignoring namespace %d, unsupported features: "
2067 			    "thin = %d, extlba = %d, pinfo = %d", i + 1,
2068 			    idns->id_nsfeat.f_thin, idns->id_flbas.lba_extlba,
2069 			    idns->id_dps.dp_pinfo);
2070 			nvme->n_ns[i].ns_ignore = B_TRUE;
2071 		}
2072 	}
2073 
2074 	/*
2075 	 * Try to set up MSI/MSI-X interrupts.
2076 	 */
2077 	if ((nvme->n_intr_types & (DDI_INTR_TYPE_MSI | DDI_INTR_TYPE_MSIX))
2078 	    != 0) {
2079 		nvme_release_interrupts(nvme);
2080 
2081 		nqueues = MIN(UINT16_MAX, ncpus);
2082 
2083 		if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX,
2084 		    nqueues) != DDI_SUCCESS) &&
2085 		    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI,
2086 		    nqueues) != DDI_SUCCESS)) {
2087 			dev_err(nvme->n_dip, CE_WARN,
2088 			    "!failed to setup MSI/MSI-X interrupts");
2089 			goto fail;
2090 		}
2091 	}
2092 
2093 	nqueues = nvme->n_intr_cnt;
2094 
2095 	/*
2096 	 * Create I/O queue pairs.
2097 	 */
2098 	nvme->n_ioq_count = nvme_set_nqueues(nvme, nqueues);
2099 	if (nvme->n_ioq_count == 0) {
2100 		dev_err(nvme->n_dip, CE_WARN,
2101 		    "!failed to set number of I/O queues to %d", nqueues);
2102 		goto fail;
2103 	}
2104 
2105 	/*
2106 	 * Reallocate I/O queue array
2107 	 */
2108 	kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *));
2109 	nvme->n_ioq = kmem_zalloc(sizeof (nvme_qpair_t *) *
2110 	    (nvme->n_ioq_count + 1), KM_SLEEP);
2111 	nvme->n_ioq[0] = nvme->n_adminq;
2112 
2113 	/*
2114 	 * If we got less queues than we asked for we might as well give
2115 	 * some of the interrupt vectors back to the system.
2116 	 */
2117 	if (nvme->n_ioq_count < nqueues) {
2118 		nvme_release_interrupts(nvme);
2119 
2120 		if (nvme_setup_interrupts(nvme, nvme->n_intr_type, nqueues)
2121 		    != DDI_SUCCESS) {
2122 			dev_err(nvme->n_dip, CE_WARN,
2123 			    "!failed to reduce number of interrupts");
2124 			goto fail;
2125 		}
2126 	}
2127 
2128 	/*
2129 	 * Alloc & register I/O queue pairs
2130 	 */
2131 	nvme->n_io_queue_len =
2132 	    MIN(nvme->n_io_queue_len, nvme->n_max_queue_entries);
2133 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip, "io-queue-len",
2134 	    nvme->n_io_queue_len);
2135 
2136 	for (i = 1; i != nvme->n_ioq_count + 1; i++) {
2137 		if (nvme_alloc_qpair(nvme, nvme->n_io_queue_len,
2138 		    &nvme->n_ioq[i], i) != DDI_SUCCESS) {
2139 			dev_err(nvme->n_dip, CE_WARN,
2140 			    "!unable to allocate I/O qpair %d", i);
2141 			goto fail;
2142 		}
2143 
2144 		if (nvme_create_io_qpair(nvme, nvme->n_ioq[i], i)
2145 		    != DDI_SUCCESS) {
2146 			dev_err(nvme->n_dip, CE_WARN,
2147 			    "!unable to create I/O qpair %d", i);
2148 			goto fail;
2149 		}
2150 	}
2151 
2152 	/*
2153 	 * Post more asynchronous events commands to reduce event reporting
2154 	 * latency as suggested by the spec.
2155 	 */
2156 	for (i = 1; i != nvme->n_async_event_limit; i++) {
2157 		if (nvme_async_event(nvme) != DDI_SUCCESS) {
2158 			dev_err(nvme->n_dip, CE_WARN,
2159 			    "!failed to post async event %d", i);
2160 			goto fail;
2161 		}
2162 	}
2163 
2164 	return (DDI_SUCCESS);
2165 
2166 fail:
2167 	(void) nvme_reset(nvme, B_FALSE);
2168 	return (DDI_FAILURE);
2169 }
2170 
2171 static uint_t
2172 nvme_intr(caddr_t arg1, caddr_t arg2)
2173 {
2174 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
2175 	nvme_t *nvme = (nvme_t *)arg1;
2176 	int inum = (int)(uintptr_t)arg2;
2177 	int qnum;
2178 	nvme_cmd_t *cmd;
2179 
2180 	if (inum >= nvme->n_intr_cnt)
2181 		return (DDI_INTR_UNCLAIMED);
2182 
2183 	/*
2184 	 * The interrupt vector a queue uses is calculated as queue_idx %
2185 	 * intr_cnt in nvme_create_io_qpair(). Iterate through the queue array
2186 	 * in steps of n_intr_cnt to process all queues using this vector.
2187 	 */
2188 	for (qnum = inum;
2189 	    qnum < nvme->n_ioq_count + 1 && nvme->n_ioq[qnum] != NULL;
2190 	    qnum += nvme->n_intr_cnt) {
2191 		while ((cmd = nvme_retrieve_cmd(nvme, nvme->n_ioq[qnum]))) {
2192 			taskq_dispatch_ent((taskq_t *)cmd->nc_nvme->n_cmd_taskq,
2193 			    cmd->nc_callback, cmd, TQ_NOSLEEP, &cmd->nc_tqent);
2194 		}
2195 	}
2196 
2197 	return (DDI_INTR_CLAIMED);
2198 }
2199 
2200 static void
2201 nvme_disable_interrupts(nvme_t *nvme)
2202 {
2203 	int i;
2204 
2205 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2206 		if (nvme->n_inth[i] == NULL)
2207 			break;
2208 
2209 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
2210 			(void) ddi_intr_block_disable(&nvme->n_inth[i], 1);
2211 		else
2212 			(void) ddi_intr_disable(nvme->n_inth[i]);
2213 	}
2214 }
2215 
2216 static int
2217 nvme_enable_interrupts(nvme_t *nvme)
2218 {
2219 	int i, fail = 0;
2220 
2221 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2222 		if (nvme->n_inth[i] == NULL)
2223 			break;
2224 
2225 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK) {
2226 			if (ddi_intr_block_enable(&nvme->n_inth[i], 1) !=
2227 			    DDI_SUCCESS)
2228 				fail++;
2229 		} else {
2230 			if (ddi_intr_enable(nvme->n_inth[i]) != DDI_SUCCESS)
2231 				fail++;
2232 		}
2233 	}
2234 
2235 	return (fail ? DDI_FAILURE : DDI_SUCCESS);
2236 }
2237 
2238 static void
2239 nvme_release_interrupts(nvme_t *nvme)
2240 {
2241 	int i;
2242 
2243 	nvme_disable_interrupts(nvme);
2244 
2245 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2246 		if (nvme->n_inth[i] == NULL)
2247 			break;
2248 
2249 		(void) ddi_intr_remove_handler(nvme->n_inth[i]);
2250 		(void) ddi_intr_free(nvme->n_inth[i]);
2251 	}
2252 
2253 	kmem_free(nvme->n_inth, nvme->n_inth_sz);
2254 	nvme->n_inth = NULL;
2255 	nvme->n_inth_sz = 0;
2256 
2257 	nvme->n_progress &= ~NVME_INTERRUPTS;
2258 }
2259 
2260 static int
2261 nvme_setup_interrupts(nvme_t *nvme, int intr_type, int nqpairs)
2262 {
2263 	int nintrs, navail, count;
2264 	int ret;
2265 	int i;
2266 
2267 	if (nvme->n_intr_types == 0) {
2268 		ret = ddi_intr_get_supported_types(nvme->n_dip,
2269 		    &nvme->n_intr_types);
2270 		if (ret != DDI_SUCCESS) {
2271 			dev_err(nvme->n_dip, CE_WARN,
2272 			    "!%s: ddi_intr_get_supported types failed",
2273 			    __func__);
2274 			return (ret);
2275 		}
2276 	}
2277 
2278 	if ((nvme->n_intr_types & intr_type) == 0)
2279 		return (DDI_FAILURE);
2280 
2281 	ret = ddi_intr_get_nintrs(nvme->n_dip, intr_type, &nintrs);
2282 	if (ret != DDI_SUCCESS) {
2283 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_nintrs failed",
2284 		    __func__);
2285 		return (ret);
2286 	}
2287 
2288 	ret = ddi_intr_get_navail(nvme->n_dip, intr_type, &navail);
2289 	if (ret != DDI_SUCCESS) {
2290 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_navail failed",
2291 		    __func__);
2292 		return (ret);
2293 	}
2294 
2295 	/* We want at most one interrupt per queue pair. */
2296 	if (navail > nqpairs)
2297 		navail = nqpairs;
2298 
2299 	nvme->n_inth_sz = sizeof (ddi_intr_handle_t) * navail;
2300 	nvme->n_inth = kmem_zalloc(nvme->n_inth_sz, KM_SLEEP);
2301 
2302 	ret = ddi_intr_alloc(nvme->n_dip, nvme->n_inth, intr_type, 0, navail,
2303 	    &count, 0);
2304 	if (ret != DDI_SUCCESS) {
2305 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_alloc failed",
2306 		    __func__);
2307 		goto fail;
2308 	}
2309 
2310 	nvme->n_intr_cnt = count;
2311 
2312 	ret = ddi_intr_get_pri(nvme->n_inth[0], &nvme->n_intr_pri);
2313 	if (ret != DDI_SUCCESS) {
2314 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_pri failed",
2315 		    __func__);
2316 		goto fail;
2317 	}
2318 
2319 	for (i = 0; i < count; i++) {
2320 		ret = ddi_intr_add_handler(nvme->n_inth[i], nvme_intr,
2321 		    (void *)nvme, (void *)(uintptr_t)i);
2322 		if (ret != DDI_SUCCESS) {
2323 			dev_err(nvme->n_dip, CE_WARN,
2324 			    "!%s: ddi_intr_add_handler failed", __func__);
2325 			goto fail;
2326 		}
2327 	}
2328 
2329 	(void) ddi_intr_get_cap(nvme->n_inth[0], &nvme->n_intr_cap);
2330 
2331 	ret = nvme_enable_interrupts(nvme);
2332 
2333 	if (ret != DDI_SUCCESS) {
2334 		dev_err(nvme->n_dip, CE_WARN,
2335 		    "!%s: nvme_enable_interrupts failed", __func__);
2336 		goto fail;
2337 	}
2338 
2339 	nvme->n_intr_type = intr_type;
2340 
2341 	nvme->n_progress |= NVME_INTERRUPTS;
2342 
2343 	return (DDI_SUCCESS);
2344 
2345 fail:
2346 	nvme_release_interrupts(nvme);
2347 
2348 	return (ret);
2349 }
2350 
2351 static int
2352 nvme_fm_errcb(dev_info_t *dip, ddi_fm_error_t *fm_error, const void *arg)
2353 {
2354 	_NOTE(ARGUNUSED(arg));
2355 
2356 	pci_ereport_post(dip, fm_error, NULL);
2357 	return (fm_error->fme_status);
2358 }
2359 
2360 static int
2361 nvme_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
2362 {
2363 	nvme_t *nvme;
2364 	int instance;
2365 	int nregs;
2366 	off_t regsize;
2367 	int i;
2368 	char name[32];
2369 
2370 	if (cmd != DDI_ATTACH)
2371 		return (DDI_FAILURE);
2372 
2373 	instance = ddi_get_instance(dip);
2374 
2375 	if (ddi_soft_state_zalloc(nvme_state, instance) != DDI_SUCCESS)
2376 		return (DDI_FAILURE);
2377 
2378 	nvme = ddi_get_soft_state(nvme_state, instance);
2379 	ddi_set_driver_private(dip, nvme);
2380 	nvme->n_dip = dip;
2381 
2382 	nvme->n_strict_version = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2383 	    DDI_PROP_DONTPASS, "strict-version", 1) == 1 ? B_TRUE : B_FALSE;
2384 	nvme->n_ignore_unknown_vendor_status = ddi_prop_get_int(DDI_DEV_T_ANY,
2385 	    dip, DDI_PROP_DONTPASS, "ignore-unknown-vendor-status", 0) == 1 ?
2386 	    B_TRUE : B_FALSE;
2387 	nvme->n_admin_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2388 	    DDI_PROP_DONTPASS, "admin-queue-len", NVME_DEFAULT_ADMIN_QUEUE_LEN);
2389 	nvme->n_io_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2390 	    DDI_PROP_DONTPASS, "io-queue-len", NVME_DEFAULT_IO_QUEUE_LEN);
2391 	nvme->n_async_event_limit = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2392 	    DDI_PROP_DONTPASS, "async-event-limit",
2393 	    NVME_DEFAULT_ASYNC_EVENT_LIMIT);
2394 
2395 	if (nvme->n_admin_queue_len < NVME_MIN_ADMIN_QUEUE_LEN)
2396 		nvme->n_admin_queue_len = NVME_MIN_ADMIN_QUEUE_LEN;
2397 	else if (nvme->n_admin_queue_len > NVME_MAX_ADMIN_QUEUE_LEN)
2398 		nvme->n_admin_queue_len = NVME_MAX_ADMIN_QUEUE_LEN;
2399 
2400 	if (nvme->n_io_queue_len < NVME_MIN_IO_QUEUE_LEN)
2401 		nvme->n_io_queue_len = NVME_MIN_IO_QUEUE_LEN;
2402 
2403 	if (nvme->n_async_event_limit < 1)
2404 		nvme->n_async_event_limit = NVME_DEFAULT_ASYNC_EVENT_LIMIT;
2405 
2406 	nvme->n_reg_acc_attr = nvme_reg_acc_attr;
2407 	nvme->n_queue_dma_attr = nvme_queue_dma_attr;
2408 	nvme->n_prp_dma_attr = nvme_prp_dma_attr;
2409 	nvme->n_sgl_dma_attr = nvme_sgl_dma_attr;
2410 
2411 	/*
2412 	 * Setup FMA support.
2413 	 */
2414 	nvme->n_fm_cap = ddi_getprop(DDI_DEV_T_ANY, dip,
2415 	    DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
2416 	    DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
2417 	    DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
2418 
2419 	ddi_fm_init(dip, &nvme->n_fm_cap, &nvme->n_fm_ibc);
2420 
2421 	if (nvme->n_fm_cap) {
2422 		if (nvme->n_fm_cap & DDI_FM_ACCCHK_CAPABLE)
2423 			nvme->n_reg_acc_attr.devacc_attr_access =
2424 			    DDI_FLAGERR_ACC;
2425 
2426 		if (nvme->n_fm_cap & DDI_FM_DMACHK_CAPABLE) {
2427 			nvme->n_prp_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2428 			nvme->n_sgl_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2429 		}
2430 
2431 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
2432 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2433 			pci_ereport_setup(dip);
2434 
2435 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2436 			ddi_fm_handler_register(dip, nvme_fm_errcb,
2437 			    (void *)nvme);
2438 	}
2439 
2440 	nvme->n_progress |= NVME_FMA_INIT;
2441 
2442 	/*
2443 	 * The spec defines several register sets. Only the controller
2444 	 * registers (set 1) are currently used.
2445 	 */
2446 	if (ddi_dev_nregs(dip, &nregs) == DDI_FAILURE ||
2447 	    nregs < 2 ||
2448 	    ddi_dev_regsize(dip, 1, &regsize) == DDI_FAILURE)
2449 		goto fail;
2450 
2451 	if (ddi_regs_map_setup(dip, 1, &nvme->n_regs, 0, regsize,
2452 	    &nvme->n_reg_acc_attr, &nvme->n_regh) != DDI_SUCCESS) {
2453 		dev_err(dip, CE_WARN, "!failed to map regset 1");
2454 		goto fail;
2455 	}
2456 
2457 	nvme->n_progress |= NVME_REGS_MAPPED;
2458 
2459 	/*
2460 	 * Create taskq for command completion.
2461 	 */
2462 	(void) snprintf(name, sizeof (name), "%s%d_cmd_taskq",
2463 	    ddi_driver_name(dip), ddi_get_instance(dip));
2464 	nvme->n_cmd_taskq = ddi_taskq_create(dip, name, MIN(UINT16_MAX, ncpus),
2465 	    TASKQ_DEFAULTPRI, 0);
2466 	if (nvme->n_cmd_taskq == NULL) {
2467 		dev_err(dip, CE_WARN, "!failed to create cmd taskq");
2468 		goto fail;
2469 	}
2470 
2471 
2472 	if (nvme_init(nvme) != DDI_SUCCESS)
2473 		goto fail;
2474 
2475 	/*
2476 	 * Attach the blkdev driver for each namespace.
2477 	 */
2478 	for (i = 0; i != nvme->n_namespace_count; i++) {
2479 		if (nvme->n_ns[i].ns_ignore)
2480 			continue;
2481 
2482 		nvme->n_ns[i].ns_bd_hdl = bd_alloc_handle(&nvme->n_ns[i],
2483 		    &nvme_bd_ops, &nvme->n_prp_dma_attr, KM_SLEEP);
2484 
2485 		if (nvme->n_ns[i].ns_bd_hdl == NULL) {
2486 			dev_err(dip, CE_WARN,
2487 			    "!failed to get blkdev handle for namespace %d", i);
2488 			goto fail;
2489 		}
2490 
2491 		if (bd_attach_handle(dip, nvme->n_ns[i].ns_bd_hdl)
2492 		    != DDI_SUCCESS) {
2493 			dev_err(dip, CE_WARN,
2494 			    "!failed to attach blkdev handle for namespace %d",
2495 			    i);
2496 			goto fail;
2497 		}
2498 	}
2499 
2500 	return (DDI_SUCCESS);
2501 
2502 fail:
2503 	/* attach successful anyway so that FMA can retire the device */
2504 	if (nvme->n_dead)
2505 		return (DDI_SUCCESS);
2506 
2507 	(void) nvme_detach(dip, DDI_DETACH);
2508 
2509 	return (DDI_FAILURE);
2510 }
2511 
2512 static int
2513 nvme_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
2514 {
2515 	int instance, i;
2516 	nvme_t *nvme;
2517 
2518 	if (cmd != DDI_DETACH)
2519 		return (DDI_FAILURE);
2520 
2521 	instance = ddi_get_instance(dip);
2522 
2523 	nvme = ddi_get_soft_state(nvme_state, instance);
2524 
2525 	if (nvme == NULL)
2526 		return (DDI_FAILURE);
2527 
2528 	if (nvme->n_ns) {
2529 		for (i = 0; i != nvme->n_namespace_count; i++) {
2530 			if (nvme->n_ns[i].ns_bd_hdl) {
2531 				(void) bd_detach_handle(
2532 				    nvme->n_ns[i].ns_bd_hdl);
2533 				bd_free_handle(nvme->n_ns[i].ns_bd_hdl);
2534 			}
2535 
2536 			if (nvme->n_ns[i].ns_idns)
2537 				kmem_free(nvme->n_ns[i].ns_idns,
2538 				    sizeof (nvme_identify_nsid_t));
2539 		}
2540 
2541 		kmem_free(nvme->n_ns, sizeof (nvme_namespace_t) *
2542 		    nvme->n_namespace_count);
2543 	}
2544 
2545 	if (nvme->n_progress & NVME_INTERRUPTS)
2546 		nvme_release_interrupts(nvme);
2547 
2548 	if (nvme->n_cmd_taskq)
2549 		ddi_taskq_wait(nvme->n_cmd_taskq);
2550 
2551 	if (nvme->n_ioq_count > 0) {
2552 		for (i = 1; i != nvme->n_ioq_count + 1; i++) {
2553 			if (nvme->n_ioq[i] != NULL) {
2554 				/* TODO: send destroy queue commands */
2555 				nvme_free_qpair(nvme->n_ioq[i]);
2556 			}
2557 		}
2558 
2559 		kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *) *
2560 		    (nvme->n_ioq_count + 1));
2561 	}
2562 
2563 	if (nvme->n_progress & NVME_REGS_MAPPED) {
2564 		nvme_shutdown(nvme, NVME_CC_SHN_NORMAL, B_FALSE);
2565 		(void) nvme_reset(nvme, B_FALSE);
2566 	}
2567 
2568 	if (nvme->n_cmd_taskq)
2569 		ddi_taskq_destroy(nvme->n_cmd_taskq);
2570 
2571 	if (nvme->n_progress & NVME_CTRL_LIMITS)
2572 		sema_destroy(&nvme->n_abort_sema);
2573 
2574 	if (nvme->n_progress & NVME_ADMIN_QUEUE)
2575 		nvme_free_qpair(nvme->n_adminq);
2576 
2577 	if (nvme->n_idctl)
2578 		kmem_free(nvme->n_idctl, sizeof (nvme_identify_ctrl_t));
2579 
2580 	if (nvme->n_progress & NVME_REGS_MAPPED)
2581 		ddi_regs_map_free(&nvme->n_regh);
2582 
2583 	if (nvme->n_progress & NVME_FMA_INIT) {
2584 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2585 			ddi_fm_handler_unregister(nvme->n_dip);
2586 
2587 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
2588 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2589 			pci_ereport_teardown(nvme->n_dip);
2590 
2591 		ddi_fm_fini(nvme->n_dip);
2592 	}
2593 
2594 	if (nvme->n_vendor != NULL)
2595 		strfree(nvme->n_vendor);
2596 
2597 	if (nvme->n_product != NULL)
2598 		strfree(nvme->n_product);
2599 
2600 	ddi_soft_state_free(nvme_state, instance);
2601 
2602 	return (DDI_SUCCESS);
2603 }
2604 
2605 static int
2606 nvme_quiesce(dev_info_t *dip)
2607 {
2608 	int instance;
2609 	nvme_t *nvme;
2610 
2611 	instance = ddi_get_instance(dip);
2612 
2613 	nvme = ddi_get_soft_state(nvme_state, instance);
2614 
2615 	if (nvme == NULL)
2616 		return (DDI_FAILURE);
2617 
2618 	nvme_shutdown(nvme, NVME_CC_SHN_ABRUPT, B_TRUE);
2619 
2620 	(void) nvme_reset(nvme, B_TRUE);
2621 
2622 	return (DDI_FAILURE);
2623 }
2624 
2625 static int
2626 nvme_fill_prp(nvme_cmd_t *cmd, bd_xfer_t *xfer)
2627 {
2628 	nvme_t *nvme = cmd->nc_nvme;
2629 	int nprp_page, nprp;
2630 	uint64_t *prp;
2631 
2632 	if (xfer->x_ndmac == 0)
2633 		return (DDI_FAILURE);
2634 
2635 	cmd->nc_sqe.sqe_dptr.d_prp[0] = xfer->x_dmac.dmac_laddress;
2636 	ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
2637 
2638 	if (xfer->x_ndmac == 1) {
2639 		cmd->nc_sqe.sqe_dptr.d_prp[1] = 0;
2640 		return (DDI_SUCCESS);
2641 	} else if (xfer->x_ndmac == 2) {
2642 		cmd->nc_sqe.sqe_dptr.d_prp[1] = xfer->x_dmac.dmac_laddress;
2643 		return (DDI_SUCCESS);
2644 	}
2645 
2646 	xfer->x_ndmac--;
2647 
2648 	nprp_page = nvme->n_pagesize / sizeof (uint64_t) - 1;
2649 	ASSERT(nprp_page > 0);
2650 	nprp = (xfer->x_ndmac + nprp_page - 1) / nprp_page;
2651 
2652 	/*
2653 	 * We currently don't support chained PRPs and set up our DMA
2654 	 * attributes to reflect that. If we still get an I/O request
2655 	 * that needs a chained PRP something is very wrong.
2656 	 */
2657 	VERIFY(nprp == 1);
2658 
2659 	if (nvme_zalloc_dma(nvme, nvme->n_pagesize * nprp, DDI_DMA_READ,
2660 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
2661 		dev_err(nvme->n_dip, CE_WARN, "!%s: nvme_zalloc_dma failed",
2662 		    __func__);
2663 		return (DDI_FAILURE);
2664 	}
2665 
2666 	cmd->nc_sqe.sqe_dptr.d_prp[1] = cmd->nc_dma->nd_cookie.dmac_laddress;
2667 	ddi_dma_nextcookie(cmd->nc_dma->nd_dmah, &cmd->nc_dma->nd_cookie);
2668 
2669 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
2670 	for (prp = (uint64_t *)cmd->nc_dma->nd_memp;
2671 	    xfer->x_ndmac > 0;
2672 	    prp++, xfer->x_ndmac--) {
2673 		*prp = xfer->x_dmac.dmac_laddress;
2674 		ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
2675 	}
2676 
2677 	(void) ddi_dma_sync(cmd->nc_dma->nd_dmah, 0, cmd->nc_dma->nd_len,
2678 	    DDI_DMA_SYNC_FORDEV);
2679 	return (DDI_SUCCESS);
2680 }
2681 
2682 static nvme_cmd_t *
2683 nvme_create_nvm_cmd(nvme_namespace_t *ns, uint8_t opc, bd_xfer_t *xfer)
2684 {
2685 	nvme_t *nvme = ns->ns_nvme;
2686 	nvme_cmd_t *cmd;
2687 
2688 	/*
2689 	 * Blkdev only sets BD_XFER_POLL when dumping, so don't sleep.
2690 	 */
2691 	cmd = nvme_alloc_cmd(nvme, (xfer->x_flags & BD_XFER_POLL) ?
2692 	    KM_NOSLEEP : KM_SLEEP);
2693 
2694 	if (cmd == NULL)
2695 		return (NULL);
2696 
2697 	cmd->nc_sqe.sqe_opc = opc;
2698 	cmd->nc_callback = nvme_bd_xfer_done;
2699 	cmd->nc_xfer = xfer;
2700 
2701 	switch (opc) {
2702 	case NVME_OPC_NVM_WRITE:
2703 	case NVME_OPC_NVM_READ:
2704 		VERIFY(xfer->x_nblks <= 0x10000);
2705 
2706 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
2707 
2708 		cmd->nc_sqe.sqe_cdw10 = xfer->x_blkno & 0xffffffffu;
2709 		cmd->nc_sqe.sqe_cdw11 = (xfer->x_blkno >> 32);
2710 		cmd->nc_sqe.sqe_cdw12 = (uint16_t)(xfer->x_nblks - 1);
2711 
2712 		if (nvme_fill_prp(cmd, xfer) != DDI_SUCCESS)
2713 			goto fail;
2714 		break;
2715 
2716 	case NVME_OPC_NVM_FLUSH:
2717 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
2718 		break;
2719 
2720 	default:
2721 		goto fail;
2722 	}
2723 
2724 	return (cmd);
2725 
2726 fail:
2727 	nvme_free_cmd(cmd);
2728 	return (NULL);
2729 }
2730 
2731 static void
2732 nvme_bd_xfer_done(void *arg)
2733 {
2734 	nvme_cmd_t *cmd = arg;
2735 	bd_xfer_t *xfer = cmd->nc_xfer;
2736 	int error = 0;
2737 
2738 	error = nvme_check_cmd_status(cmd);
2739 	nvme_free_cmd(cmd);
2740 
2741 	bd_xfer_done(xfer, error);
2742 }
2743 
2744 static void
2745 nvme_bd_driveinfo(void *arg, bd_drive_t *drive)
2746 {
2747 	nvme_namespace_t *ns = arg;
2748 	nvme_t *nvme = ns->ns_nvme;
2749 
2750 	/*
2751 	 * blkdev maintains one queue size per instance (namespace),
2752 	 * but all namespace share the I/O queues.
2753 	 * TODO: need to figure out a sane default, or use per-NS I/O queues,
2754 	 * or change blkdev to handle EAGAIN
2755 	 */
2756 	drive->d_qsize = nvme->n_ioq_count * nvme->n_io_queue_len
2757 	    / nvme->n_namespace_count;
2758 
2759 	/*
2760 	 * d_maxxfer is not set, which means the value is taken from the DMA
2761 	 * attributes specified to bd_alloc_handle.
2762 	 */
2763 
2764 	drive->d_removable = B_FALSE;
2765 	drive->d_hotpluggable = B_FALSE;
2766 
2767 	drive->d_target = ns->ns_id;
2768 	drive->d_lun = 0;
2769 
2770 	drive->d_model = nvme->n_idctl->id_model;
2771 	drive->d_model_len = sizeof (nvme->n_idctl->id_model);
2772 	drive->d_vendor = nvme->n_vendor;
2773 	drive->d_vendor_len = strlen(nvme->n_vendor);
2774 	drive->d_product = nvme->n_product;
2775 	drive->d_product_len = strlen(nvme->n_product);
2776 	drive->d_serial = nvme->n_idctl->id_serial;
2777 	drive->d_serial_len = sizeof (nvme->n_idctl->id_serial);
2778 	drive->d_revision = nvme->n_idctl->id_fwrev;
2779 	drive->d_revision_len = sizeof (nvme->n_idctl->id_fwrev);
2780 }
2781 
2782 static int
2783 nvme_bd_mediainfo(void *arg, bd_media_t *media)
2784 {
2785 	nvme_namespace_t *ns = arg;
2786 
2787 	media->m_nblks = ns->ns_block_count;
2788 	media->m_blksize = ns->ns_block_size;
2789 	media->m_readonly = B_FALSE;
2790 	media->m_solidstate = B_TRUE;
2791 
2792 	media->m_pblksize = ns->ns_best_block_size;
2793 
2794 	return (0);
2795 }
2796 
2797 static int
2798 nvme_bd_cmd(nvme_namespace_t *ns, bd_xfer_t *xfer, uint8_t opc)
2799 {
2800 	nvme_t *nvme = ns->ns_nvme;
2801 	nvme_cmd_t *cmd;
2802 
2803 	if (nvme->n_dead)
2804 		return (EIO);
2805 
2806 	/* No polling for now */
2807 	if (xfer->x_flags & BD_XFER_POLL)
2808 		return (EIO);
2809 
2810 	cmd = nvme_create_nvm_cmd(ns, opc, xfer);
2811 	if (cmd == NULL)
2812 		return (ENOMEM);
2813 
2814 	cmd->nc_sqid = (CPU->cpu_id % nvme->n_ioq_count) + 1;
2815 	ASSERT(cmd->nc_sqid <= nvme->n_ioq_count);
2816 
2817 	if (nvme_submit_cmd(nvme->n_ioq[cmd->nc_sqid], cmd)
2818 	    != DDI_SUCCESS)
2819 		return (EAGAIN);
2820 
2821 	return (0);
2822 }
2823 
2824 static int
2825 nvme_bd_read(void *arg, bd_xfer_t *xfer)
2826 {
2827 	nvme_namespace_t *ns = arg;
2828 
2829 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_READ));
2830 }
2831 
2832 static int
2833 nvme_bd_write(void *arg, bd_xfer_t *xfer)
2834 {
2835 	nvme_namespace_t *ns = arg;
2836 
2837 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_WRITE));
2838 }
2839 
2840 static int
2841 nvme_bd_sync(void *arg, bd_xfer_t *xfer)
2842 {
2843 	nvme_namespace_t *ns = arg;
2844 
2845 	if (ns->ns_nvme->n_dead)
2846 		return (EIO);
2847 
2848 	/*
2849 	 * If the volatile write cache isn't enabled the FLUSH command is a
2850 	 * no-op, so we can take a shortcut here.
2851 	 */
2852 	if (ns->ns_nvme->n_volatile_write_cache_enabled == B_FALSE) {
2853 		bd_xfer_done(xfer, ENOTSUP);
2854 		return (0);
2855 	}
2856 
2857 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_FLUSH));
2858 }
2859 
2860 static int
2861 nvme_bd_devid(void *arg, dev_info_t *devinfo, ddi_devid_t *devid)
2862 {
2863 	nvme_namespace_t *ns = arg;
2864 
2865 	return (ddi_devid_init(devinfo, DEVID_ENCAP, strlen(ns->ns_devid),
2866 	    ns->ns_devid, devid));
2867 }
2868