xref: /titanic_51/usr/src/uts/common/io/nvme/nvme.c (revision 510a68476ba6e33759b7603130d76db4cec783d1)
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 	if (cmd->nc_nvme->n_strict_version) {
768 		cmd->nc_nvme->n_dead = B_TRUE;
769 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
770 	}
771 
772 	return (EIO);
773 }
774 
775 static int
776 nvme_check_vendor_cmd_status(nvme_cmd_t *cmd)
777 {
778 	nvme_cqe_t *cqe = &cmd->nc_cqe;
779 
780 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
781 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
782 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
783 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
784 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
785 	if (cmd->nc_nvme->n_ignore_unknown_vendor_status) {
786 		cmd->nc_nvme->n_dead = B_TRUE;
787 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
788 	}
789 
790 	return (EIO);
791 }
792 
793 static int
794 nvme_check_integrity_cmd_status(nvme_cmd_t *cmd)
795 {
796 	nvme_cqe_t *cqe = &cmd->nc_cqe;
797 
798 	switch (cqe->cqe_sf.sf_sc) {
799 	case NVME_CQE_SC_INT_NVM_WRITE:
800 		/* write fail */
801 		/* TODO: post ereport */
802 		return (EIO);
803 
804 	case NVME_CQE_SC_INT_NVM_READ:
805 		/* read fail */
806 		/* TODO: post ereport */
807 		return (EIO);
808 
809 	default:
810 		return (nvme_check_unknown_cmd_status(cmd));
811 	}
812 }
813 
814 static int
815 nvme_check_generic_cmd_status(nvme_cmd_t *cmd)
816 {
817 	nvme_cqe_t *cqe = &cmd->nc_cqe;
818 
819 	switch (cqe->cqe_sf.sf_sc) {
820 	case NVME_CQE_SC_GEN_SUCCESS:
821 		return (0);
822 
823 	/*
824 	 * Errors indicating a bug in the driver should cause a panic.
825 	 */
826 	case NVME_CQE_SC_GEN_INV_OPC:
827 		/* Invalid Command Opcode */
828 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
829 		    "invalid opcode in cmd %p", (void *)cmd);
830 		return (0);
831 
832 	case NVME_CQE_SC_GEN_INV_FLD:
833 		/* Invalid Field in Command */
834 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
835 		    "invalid field in cmd %p", (void *)cmd);
836 		return (0);
837 
838 	case NVME_CQE_SC_GEN_ID_CNFL:
839 		/* Command ID Conflict */
840 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
841 		    "cmd ID conflict in cmd %p", (void *)cmd);
842 		return (0);
843 
844 	case NVME_CQE_SC_GEN_INV_NS:
845 		/* Invalid Namespace or Format */
846 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
847 		    "invalid NS/format in cmd %p", (void *)cmd);
848 		return (0);
849 
850 	case NVME_CQE_SC_GEN_NVM_LBA_RANGE:
851 		/* LBA Out Of Range */
852 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
853 		    "LBA out of range in cmd %p", (void *)cmd);
854 		return (0);
855 
856 	/*
857 	 * Non-fatal errors, handle gracefully.
858 	 */
859 	case NVME_CQE_SC_GEN_DATA_XFR_ERR:
860 		/* Data Transfer Error (DMA) */
861 		/* TODO: post ereport */
862 		atomic_inc_32(&cmd->nc_nvme->n_data_xfr_err);
863 		return (EIO);
864 
865 	case NVME_CQE_SC_GEN_INTERNAL_ERR:
866 		/*
867 		 * Internal Error. The spec (v1.0, section 4.5.1.2) says
868 		 * detailed error information is returned as async event,
869 		 * so we pretty much ignore the error here and handle it
870 		 * in the async event handler.
871 		 */
872 		atomic_inc_32(&cmd->nc_nvme->n_internal_err);
873 		return (EIO);
874 
875 	case NVME_CQE_SC_GEN_ABORT_REQUEST:
876 		/*
877 		 * Command Abort Requested. This normally happens only when a
878 		 * command times out.
879 		 */
880 		/* TODO: post ereport or change blkdev to handle this? */
881 		atomic_inc_32(&cmd->nc_nvme->n_abort_rq_err);
882 		return (ECANCELED);
883 
884 	case NVME_CQE_SC_GEN_ABORT_PWRLOSS:
885 		/* Command Aborted due to Power Loss Notification */
886 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
887 		cmd->nc_nvme->n_dead = B_TRUE;
888 		return (EIO);
889 
890 	case NVME_CQE_SC_GEN_ABORT_SQ_DEL:
891 		/* Command Aborted due to SQ Deletion */
892 		atomic_inc_32(&cmd->nc_nvme->n_abort_sq_del);
893 		return (EIO);
894 
895 	case NVME_CQE_SC_GEN_NVM_CAP_EXC:
896 		/* Capacity Exceeded */
897 		atomic_inc_32(&cmd->nc_nvme->n_nvm_cap_exc);
898 		return (EIO);
899 
900 	case NVME_CQE_SC_GEN_NVM_NS_NOTRDY:
901 		/* Namespace Not Ready */
902 		atomic_inc_32(&cmd->nc_nvme->n_nvm_ns_notrdy);
903 		return (EIO);
904 
905 	default:
906 		return (nvme_check_unknown_cmd_status(cmd));
907 	}
908 }
909 
910 static int
911 nvme_check_specific_cmd_status(nvme_cmd_t *cmd)
912 {
913 	nvme_cqe_t *cqe = &cmd->nc_cqe;
914 
915 	switch (cqe->cqe_sf.sf_sc) {
916 	case NVME_CQE_SC_SPC_INV_CQ:
917 		/* Completion Queue Invalid */
918 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE);
919 		atomic_inc_32(&cmd->nc_nvme->n_inv_cq_err);
920 		return (EINVAL);
921 
922 	case NVME_CQE_SC_SPC_INV_QID:
923 		/* Invalid Queue Identifier */
924 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
925 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_SQUEUE ||
926 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE ||
927 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
928 		atomic_inc_32(&cmd->nc_nvme->n_inv_qid_err);
929 		return (EINVAL);
930 
931 	case NVME_CQE_SC_SPC_MAX_QSZ_EXC:
932 		/* Max Queue Size Exceeded */
933 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
934 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
935 		atomic_inc_32(&cmd->nc_nvme->n_max_qsz_exc);
936 		return (EINVAL);
937 
938 	case NVME_CQE_SC_SPC_ABRT_CMD_EXC:
939 		/* Abort Command Limit Exceeded */
940 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT);
941 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
942 		    "abort command limit exceeded in cmd %p", (void *)cmd);
943 		return (0);
944 
945 	case NVME_CQE_SC_SPC_ASYNC_EVREQ_EXC:
946 		/* Async Event Request Limit Exceeded */
947 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ASYNC_EVENT);
948 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
949 		    "async event request limit exceeded in cmd %p",
950 		    (void *)cmd);
951 		return (0);
952 
953 	case NVME_CQE_SC_SPC_INV_INT_VECT:
954 		/* Invalid Interrupt Vector */
955 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
956 		atomic_inc_32(&cmd->nc_nvme->n_inv_int_vect);
957 		return (EINVAL);
958 
959 	case NVME_CQE_SC_SPC_INV_LOG_PAGE:
960 		/* Invalid Log Page */
961 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_GET_LOG_PAGE);
962 		atomic_inc_32(&cmd->nc_nvme->n_inv_log_page);
963 		return (EINVAL);
964 
965 	case NVME_CQE_SC_SPC_INV_FORMAT:
966 		/* Invalid Format */
967 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_FORMAT);
968 		atomic_inc_32(&cmd->nc_nvme->n_inv_format);
969 		return (EINVAL);
970 
971 	case NVME_CQE_SC_SPC_INV_Q_DEL:
972 		/* Invalid Queue Deletion */
973 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
974 		atomic_inc_32(&cmd->nc_nvme->n_inv_q_del);
975 		return (EINVAL);
976 
977 	case NVME_CQE_SC_SPC_NVM_CNFL_ATTR:
978 		/* Conflicting Attributes */
979 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_DSET_MGMT ||
980 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
981 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
982 		atomic_inc_32(&cmd->nc_nvme->n_cnfl_attr);
983 		return (EINVAL);
984 
985 	case NVME_CQE_SC_SPC_NVM_INV_PROT:
986 		/* Invalid Protection Information */
987 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_COMPARE ||
988 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
989 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
990 		atomic_inc_32(&cmd->nc_nvme->n_inv_prot);
991 		return (EINVAL);
992 
993 	case NVME_CQE_SC_SPC_NVM_READONLY:
994 		/* Write to Read Only Range */
995 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
996 		atomic_inc_32(&cmd->nc_nvme->n_readonly);
997 		return (EROFS);
998 
999 	default:
1000 		return (nvme_check_unknown_cmd_status(cmd));
1001 	}
1002 }
1003 
1004 static inline int
1005 nvme_check_cmd_status(nvme_cmd_t *cmd)
1006 {
1007 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1008 
1009 	/* take a shortcut if everything is alright */
1010 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1011 	    cqe->cqe_sf.sf_sc == NVME_CQE_SC_GEN_SUCCESS)
1012 		return (0);
1013 
1014 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC)
1015 		return (nvme_check_generic_cmd_status(cmd));
1016 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_SPECIFIC)
1017 		return (nvme_check_specific_cmd_status(cmd));
1018 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_INTEGRITY)
1019 		return (nvme_check_integrity_cmd_status(cmd));
1020 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_VENDOR)
1021 		return (nvme_check_vendor_cmd_status(cmd));
1022 
1023 	return (nvme_check_unknown_cmd_status(cmd));
1024 }
1025 
1026 /*
1027  * nvme_abort_cmd_cb -- replaces nc_callback of aborted commands
1028  *
1029  * This functions takes care of cleaning up aborted commands. The command
1030  * status is checked to catch any fatal errors.
1031  */
1032 static void
1033 nvme_abort_cmd_cb(void *arg)
1034 {
1035 	nvme_cmd_t *cmd = arg;
1036 
1037 	/*
1038 	 * Grab the command mutex. Once we have it we hold the last reference
1039 	 * to the command and can safely free it.
1040 	 */
1041 	mutex_enter(&cmd->nc_mutex);
1042 	(void) nvme_check_cmd_status(cmd);
1043 	mutex_exit(&cmd->nc_mutex);
1044 
1045 	nvme_free_cmd(cmd);
1046 }
1047 
1048 static void
1049 nvme_abort_cmd(nvme_cmd_t *abort_cmd)
1050 {
1051 	nvme_t *nvme = abort_cmd->nc_nvme;
1052 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1053 	nvme_abort_cmd_t ac = { 0 };
1054 
1055 	sema_p(&nvme->n_abort_sema);
1056 
1057 	ac.b.ac_cid = abort_cmd->nc_sqe.sqe_cid;
1058 	ac.b.ac_sqid = abort_cmd->nc_sqid;
1059 
1060 	/*
1061 	 * Drop the mutex of the aborted command. From this point on
1062 	 * we must assume that the abort callback has freed the command.
1063 	 */
1064 	mutex_exit(&abort_cmd->nc_mutex);
1065 
1066 	cmd->nc_sqid = 0;
1067 	cmd->nc_sqe.sqe_opc = NVME_OPC_ABORT;
1068 	cmd->nc_callback = nvme_wakeup_cmd;
1069 	cmd->nc_sqe.sqe_cdw10 = ac.r;
1070 
1071 	/*
1072 	 * Send the ABORT to the hardware. The ABORT command will return _after_
1073 	 * the aborted command has completed (aborted or otherwise).
1074 	 */
1075 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1076 		sema_v(&nvme->n_abort_sema);
1077 		dev_err(nvme->n_dip, CE_WARN,
1078 		    "!nvme_admin_cmd failed for ABORT");
1079 		atomic_inc_32(&nvme->n_abort_failed);
1080 		return;
1081 	}
1082 	sema_v(&nvme->n_abort_sema);
1083 
1084 	if (nvme_check_cmd_status(cmd)) {
1085 		dev_err(nvme->n_dip, CE_WARN,
1086 		    "!ABORT failed with sct = %x, sc = %x",
1087 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1088 		atomic_inc_32(&nvme->n_abort_failed);
1089 	} else {
1090 		atomic_inc_32(&nvme->n_cmd_aborted);
1091 	}
1092 
1093 	nvme_free_cmd(cmd);
1094 }
1095 
1096 /*
1097  * nvme_wait_cmd -- wait for command completion or timeout
1098  *
1099  * Returns B_TRUE if the command completed normally.
1100  *
1101  * Returns B_FALSE if the command timed out and an abort was attempted. The
1102  * command mutex will be dropped and the command must be considered freed. The
1103  * freeing of the command is normally done by the abort command callback.
1104  *
1105  * In case of a serious error or a timeout of the abort command the hardware
1106  * will be declared dead and FMA will be notified.
1107  */
1108 static boolean_t
1109 nvme_wait_cmd(nvme_cmd_t *cmd, uint_t usec)
1110 {
1111 	clock_t timeout = ddi_get_lbolt() + drv_usectohz(usec);
1112 	nvme_t *nvme = cmd->nc_nvme;
1113 	nvme_reg_csts_t csts;
1114 
1115 	ASSERT(mutex_owned(&cmd->nc_mutex));
1116 
1117 	while (!cmd->nc_completed) {
1118 		if (cv_timedwait(&cmd->nc_cv, &cmd->nc_mutex, timeout) == -1)
1119 			break;
1120 	}
1121 
1122 	if (cmd->nc_completed)
1123 		return (B_TRUE);
1124 
1125 	/*
1126 	 * The command timed out. Change the callback to the cleanup function.
1127 	 */
1128 	cmd->nc_callback = nvme_abort_cmd_cb;
1129 
1130 	/*
1131 	 * Check controller for fatal status, any errors associated with the
1132 	 * register or DMA handle, or for a double timeout (abort command timed
1133 	 * out). If necessary log a warning and call FMA.
1134 	 */
1135 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1136 	dev_err(nvme->n_dip, CE_WARN, "!command timeout, "
1137 	    "OPC = %x, CFS = %d", cmd->nc_sqe.sqe_opc, csts.b.csts_cfs);
1138 	atomic_inc_32(&nvme->n_cmd_timeout);
1139 
1140 	if (csts.b.csts_cfs ||
1141 	    nvme_check_regs_hdl(nvme) ||
1142 	    nvme_check_dma_hdl(cmd->nc_dma) ||
1143 	    cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT) {
1144 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1145 		nvme->n_dead = B_TRUE;
1146 		mutex_exit(&cmd->nc_mutex);
1147 	} else {
1148 		/*
1149 		 * Try to abort the command. The command mutex is released by
1150 		 * nvme_abort_cmd().
1151 		 * If the abort succeeds it will have freed the aborted command.
1152 		 * If the abort fails for other reasons we must assume that the
1153 		 * command may complete at any time, and the callback will free
1154 		 * it for us.
1155 		 */
1156 		nvme_abort_cmd(cmd);
1157 	}
1158 
1159 	return (B_FALSE);
1160 }
1161 
1162 static void
1163 nvme_wakeup_cmd(void *arg)
1164 {
1165 	nvme_cmd_t *cmd = arg;
1166 
1167 	mutex_enter(&cmd->nc_mutex);
1168 	/*
1169 	 * There is a slight chance that this command completed shortly after
1170 	 * the timeout was hit in nvme_wait_cmd() but before the callback was
1171 	 * changed. Catch that case here and clean up accordingly.
1172 	 */
1173 	if (cmd->nc_callback == nvme_abort_cmd_cb) {
1174 		mutex_exit(&cmd->nc_mutex);
1175 		nvme_abort_cmd_cb(cmd);
1176 		return;
1177 	}
1178 
1179 	cmd->nc_completed = B_TRUE;
1180 	cv_signal(&cmd->nc_cv);
1181 	mutex_exit(&cmd->nc_mutex);
1182 }
1183 
1184 static void
1185 nvme_async_event_task(void *arg)
1186 {
1187 	nvme_cmd_t *cmd = arg;
1188 	nvme_t *nvme = cmd->nc_nvme;
1189 	nvme_error_log_entry_t *error_log = NULL;
1190 	nvme_health_log_t *health_log = NULL;
1191 	nvme_async_event_t event;
1192 	int ret;
1193 
1194 	/*
1195 	 * Check for errors associated with the async request itself. The only
1196 	 * command-specific error is "async event limit exceeded", which
1197 	 * indicates a programming error in the driver and causes a panic in
1198 	 * nvme_check_cmd_status().
1199 	 *
1200 	 * Other possible errors are various scenarios where the async request
1201 	 * was aborted, or internal errors in the device. Internal errors are
1202 	 * reported to FMA, the command aborts need no special handling here.
1203 	 */
1204 	if (nvme_check_cmd_status(cmd)) {
1205 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1206 		    "!async event request returned failure, sct = %x, "
1207 		    "sc = %x, dnr = %d, m = %d", cmd->nc_cqe.cqe_sf.sf_sct,
1208 		    cmd->nc_cqe.cqe_sf.sf_sc, cmd->nc_cqe.cqe_sf.sf_dnr,
1209 		    cmd->nc_cqe.cqe_sf.sf_m);
1210 
1211 		if (cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1212 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INTERNAL_ERR) {
1213 			cmd->nc_nvme->n_dead = B_TRUE;
1214 			ddi_fm_service_impact(cmd->nc_nvme->n_dip,
1215 			    DDI_SERVICE_LOST);
1216 		}
1217 		nvme_free_cmd(cmd);
1218 		return;
1219 	}
1220 
1221 
1222 	event.r = cmd->nc_cqe.cqe_dw0;
1223 
1224 	/* Clear CQE and re-submit the async request. */
1225 	bzero(&cmd->nc_cqe, sizeof (nvme_cqe_t));
1226 	ret = nvme_submit_cmd(nvme->n_adminq, cmd);
1227 
1228 	if (ret != DDI_SUCCESS) {
1229 		dev_err(nvme->n_dip, CE_WARN,
1230 		    "!failed to resubmit async event request");
1231 		atomic_inc_32(&nvme->n_async_resubmit_failed);
1232 		nvme_free_cmd(cmd);
1233 	}
1234 
1235 	switch (event.b.ae_type) {
1236 	case NVME_ASYNC_TYPE_ERROR:
1237 		if (event.b.ae_logpage == NVME_LOGPAGE_ERROR) {
1238 			error_log = (nvme_error_log_entry_t *)
1239 			    nvme_get_logpage(nvme, event.b.ae_logpage);
1240 		} else {
1241 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1242 			    "async event reply: %d", event.b.ae_logpage);
1243 			atomic_inc_32(&nvme->n_wrong_logpage);
1244 		}
1245 
1246 		switch (event.b.ae_info) {
1247 		case NVME_ASYNC_ERROR_INV_SQ:
1248 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1249 			    "invalid submission queue");
1250 			return;
1251 
1252 		case NVME_ASYNC_ERROR_INV_DBL:
1253 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1254 			    "invalid doorbell write value");
1255 			return;
1256 
1257 		case NVME_ASYNC_ERROR_DIAGFAIL:
1258 			dev_err(nvme->n_dip, CE_WARN, "!diagnostic failure");
1259 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1260 			nvme->n_dead = B_TRUE;
1261 			atomic_inc_32(&nvme->n_diagfail_event);
1262 			break;
1263 
1264 		case NVME_ASYNC_ERROR_PERSISTENT:
1265 			dev_err(nvme->n_dip, CE_WARN, "!persistent internal "
1266 			    "device error");
1267 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1268 			nvme->n_dead = B_TRUE;
1269 			atomic_inc_32(&nvme->n_persistent_event);
1270 			break;
1271 
1272 		case NVME_ASYNC_ERROR_TRANSIENT:
1273 			dev_err(nvme->n_dip, CE_WARN, "!transient internal "
1274 			    "device error");
1275 			/* TODO: send ereport */
1276 			atomic_inc_32(&nvme->n_transient_event);
1277 			break;
1278 
1279 		case NVME_ASYNC_ERROR_FW_LOAD:
1280 			dev_err(nvme->n_dip, CE_WARN,
1281 			    "!firmware image load error");
1282 			atomic_inc_32(&nvme->n_fw_load_event);
1283 			break;
1284 		}
1285 		break;
1286 
1287 	case NVME_ASYNC_TYPE_HEALTH:
1288 		if (event.b.ae_logpage == NVME_LOGPAGE_HEALTH) {
1289 			health_log = (nvme_health_log_t *)
1290 			    nvme_get_logpage(nvme, event.b.ae_logpage, -1);
1291 		} else {
1292 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1293 			    "async event reply: %d", event.b.ae_logpage);
1294 			atomic_inc_32(&nvme->n_wrong_logpage);
1295 		}
1296 
1297 		switch (event.b.ae_info) {
1298 		case NVME_ASYNC_HEALTH_RELIABILITY:
1299 			dev_err(nvme->n_dip, CE_WARN,
1300 			    "!device reliability compromised");
1301 			/* TODO: send ereport */
1302 			atomic_inc_32(&nvme->n_reliability_event);
1303 			break;
1304 
1305 		case NVME_ASYNC_HEALTH_TEMPERATURE:
1306 			dev_err(nvme->n_dip, CE_WARN,
1307 			    "!temperature above threshold");
1308 			/* TODO: send ereport */
1309 			atomic_inc_32(&nvme->n_temperature_event);
1310 			break;
1311 
1312 		case NVME_ASYNC_HEALTH_SPARE:
1313 			dev_err(nvme->n_dip, CE_WARN,
1314 			    "!spare space below threshold");
1315 			/* TODO: send ereport */
1316 			atomic_inc_32(&nvme->n_spare_event);
1317 			break;
1318 		}
1319 		break;
1320 
1321 	case NVME_ASYNC_TYPE_VENDOR:
1322 		dev_err(nvme->n_dip, CE_WARN, "!vendor specific async event "
1323 		    "received, info = %x, logpage = %x", event.b.ae_info,
1324 		    event.b.ae_logpage);
1325 		atomic_inc_32(&nvme->n_vendor_event);
1326 		break;
1327 
1328 	default:
1329 		dev_err(nvme->n_dip, CE_WARN, "!unknown async event received, "
1330 		    "type = %x, info = %x, logpage = %x", event.b.ae_type,
1331 		    event.b.ae_info, event.b.ae_logpage);
1332 		atomic_inc_32(&nvme->n_unknown_event);
1333 		break;
1334 	}
1335 
1336 	if (error_log)
1337 		kmem_free(error_log, sizeof (nvme_error_log_entry_t) *
1338 		    nvme->n_error_log_len);
1339 
1340 	if (health_log)
1341 		kmem_free(health_log, sizeof (nvme_health_log_t));
1342 }
1343 
1344 static int
1345 nvme_admin_cmd(nvme_cmd_t *cmd, int usec)
1346 {
1347 	int ret;
1348 
1349 	mutex_enter(&cmd->nc_mutex);
1350 	ret = nvme_submit_cmd(cmd->nc_nvme->n_adminq, cmd);
1351 
1352 	if (ret != DDI_SUCCESS) {
1353 		mutex_exit(&cmd->nc_mutex);
1354 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1355 		    "!nvme_submit_cmd failed");
1356 		atomic_inc_32(&cmd->nc_nvme->n_admin_queue_full);
1357 		nvme_free_cmd(cmd);
1358 		return (DDI_FAILURE);
1359 	}
1360 
1361 	if (nvme_wait_cmd(cmd, usec) == B_FALSE) {
1362 		/*
1363 		 * The command timed out. An abort command was posted that
1364 		 * will take care of the cleanup.
1365 		 */
1366 		return (DDI_FAILURE);
1367 	}
1368 	mutex_exit(&cmd->nc_mutex);
1369 
1370 	return (DDI_SUCCESS);
1371 }
1372 
1373 static int
1374 nvme_async_event(nvme_t *nvme)
1375 {
1376 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1377 	int ret;
1378 
1379 	cmd->nc_sqid = 0;
1380 	cmd->nc_sqe.sqe_opc = NVME_OPC_ASYNC_EVENT;
1381 	cmd->nc_callback = nvme_async_event_task;
1382 
1383 	ret = nvme_submit_cmd(nvme->n_adminq, cmd);
1384 
1385 	if (ret != DDI_SUCCESS) {
1386 		dev_err(nvme->n_dip, CE_WARN,
1387 		    "!nvme_submit_cmd failed for ASYNCHRONOUS EVENT");
1388 		nvme_free_cmd(cmd);
1389 		return (DDI_FAILURE);
1390 	}
1391 
1392 	return (DDI_SUCCESS);
1393 }
1394 
1395 static void *
1396 nvme_get_logpage(nvme_t *nvme, uint8_t logpage, ...)
1397 {
1398 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1399 	void *buf = NULL;
1400 	nvme_getlogpage_t getlogpage;
1401 	size_t bufsize;
1402 	va_list ap;
1403 
1404 	va_start(ap, logpage);
1405 
1406 	cmd->nc_sqid = 0;
1407 	cmd->nc_callback = nvme_wakeup_cmd;
1408 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_LOG_PAGE;
1409 
1410 	getlogpage.b.lp_lid = logpage;
1411 
1412 	switch (logpage) {
1413 	case NVME_LOGPAGE_ERROR:
1414 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1415 		bufsize = nvme->n_error_log_len *
1416 		    sizeof (nvme_error_log_entry_t);
1417 		break;
1418 
1419 	case NVME_LOGPAGE_HEALTH:
1420 		cmd->nc_sqe.sqe_nsid = va_arg(ap, uint32_t);
1421 		bufsize = sizeof (nvme_health_log_t);
1422 		break;
1423 
1424 	case NVME_LOGPAGE_FWSLOT:
1425 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1426 		bufsize = sizeof (nvme_fwslot_log_t);
1427 		break;
1428 
1429 	default:
1430 		dev_err(nvme->n_dip, CE_WARN, "!unknown log page requested: %d",
1431 		    logpage);
1432 		atomic_inc_32(&nvme->n_unknown_logpage);
1433 		goto fail;
1434 	}
1435 
1436 	va_end(ap);
1437 
1438 	getlogpage.b.lp_numd = bufsize / sizeof (uint32_t);
1439 
1440 	cmd->nc_sqe.sqe_cdw10 = getlogpage.r;
1441 
1442 	if (nvme_zalloc_dma(nvme, getlogpage.b.lp_numd * sizeof (uint32_t),
1443 	    DDI_DMA_READ, &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1444 		dev_err(nvme->n_dip, CE_WARN,
1445 		    "!nvme_zalloc_dma failed for GET LOG PAGE");
1446 		goto fail;
1447 	}
1448 
1449 	if (cmd->nc_dma->nd_ncookie > 2) {
1450 		dev_err(nvme->n_dip, CE_WARN,
1451 		    "!too many DMA cookies for GET LOG PAGE");
1452 		atomic_inc_32(&nvme->n_too_many_cookies);
1453 		goto fail;
1454 	}
1455 
1456 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1457 	if (cmd->nc_dma->nd_ncookie > 1) {
1458 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1459 		    &cmd->nc_dma->nd_cookie);
1460 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1461 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1462 	}
1463 
1464 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1465 		dev_err(nvme->n_dip, CE_WARN,
1466 		    "!nvme_admin_cmd failed for GET LOG PAGE");
1467 		return (NULL);
1468 	}
1469 
1470 	if (nvme_check_cmd_status(cmd)) {
1471 		dev_err(nvme->n_dip, CE_WARN,
1472 		    "!GET LOG PAGE failed with sct = %x, sc = %x",
1473 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1474 		goto fail;
1475 	}
1476 
1477 	buf = kmem_alloc(bufsize, KM_SLEEP);
1478 	bcopy(cmd->nc_dma->nd_memp, buf, bufsize);
1479 
1480 fail:
1481 	nvme_free_cmd(cmd);
1482 
1483 	return (buf);
1484 }
1485 
1486 static void *
1487 nvme_identify(nvme_t *nvme, uint32_t nsid)
1488 {
1489 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1490 	void *buf = NULL;
1491 
1492 	cmd->nc_sqid = 0;
1493 	cmd->nc_callback = nvme_wakeup_cmd;
1494 	cmd->nc_sqe.sqe_opc = NVME_OPC_IDENTIFY;
1495 	cmd->nc_sqe.sqe_nsid = nsid;
1496 	cmd->nc_sqe.sqe_cdw10 = nsid ? NVME_IDENTIFY_NSID : NVME_IDENTIFY_CTRL;
1497 
1498 	if (nvme_zalloc_dma(nvme, NVME_IDENTIFY_BUFSIZE, DDI_DMA_READ,
1499 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1500 		dev_err(nvme->n_dip, CE_WARN,
1501 		    "!nvme_zalloc_dma failed for IDENTIFY");
1502 		goto fail;
1503 	}
1504 
1505 	if (cmd->nc_dma->nd_ncookie > 2) {
1506 		dev_err(nvme->n_dip, CE_WARN,
1507 		    "!too many DMA cookies for IDENTIFY");
1508 		atomic_inc_32(&nvme->n_too_many_cookies);
1509 		goto fail;
1510 	}
1511 
1512 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1513 	if (cmd->nc_dma->nd_ncookie > 1) {
1514 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1515 		    &cmd->nc_dma->nd_cookie);
1516 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1517 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1518 	}
1519 
1520 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1521 		dev_err(nvme->n_dip, CE_WARN,
1522 		    "!nvme_admin_cmd failed for IDENTIFY");
1523 		return (NULL);
1524 	}
1525 
1526 	if (nvme_check_cmd_status(cmd)) {
1527 		dev_err(nvme->n_dip, CE_WARN,
1528 		    "!IDENTIFY failed with sct = %x, sc = %x",
1529 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1530 		goto fail;
1531 	}
1532 
1533 	buf = kmem_alloc(NVME_IDENTIFY_BUFSIZE, KM_SLEEP);
1534 	bcopy(cmd->nc_dma->nd_memp, buf, NVME_IDENTIFY_BUFSIZE);
1535 
1536 fail:
1537 	nvme_free_cmd(cmd);
1538 
1539 	return (buf);
1540 }
1541 
1542 static int
1543 nvme_set_nqueues(nvme_t *nvme, uint16_t nqueues)
1544 {
1545 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1546 	nvme_nqueue_t nq = { 0 };
1547 
1548 	nq.b.nq_nsq = nq.b.nq_ncq = nqueues;
1549 
1550 	cmd->nc_sqid = 0;
1551 	cmd->nc_callback = nvme_wakeup_cmd;
1552 	cmd->nc_sqe.sqe_opc = NVME_OPC_SET_FEATURES;
1553 	cmd->nc_sqe.sqe_cdw10 = NVME_FEAT_NQUEUES;
1554 	cmd->nc_sqe.sqe_cdw11 = nq.r;
1555 
1556 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1557 		dev_err(nvme->n_dip, CE_WARN,
1558 		    "!nvme_admin_cmd failed for SET FEATURES (NQUEUES)");
1559 		return (0);
1560 	}
1561 
1562 	if (nvme_check_cmd_status(cmd)) {
1563 		dev_err(nvme->n_dip, CE_WARN,
1564 		    "!SET FEATURES (NQUEUES) failed with sct = %x, sc = %x",
1565 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1566 		nvme_free_cmd(cmd);
1567 		return (0);
1568 	}
1569 
1570 	nq.r = cmd->nc_cqe.cqe_dw0;
1571 	nvme_free_cmd(cmd);
1572 
1573 	/*
1574 	 * Always use the same number of submission and completion queues, and
1575 	 * never use more than the requested number of queues.
1576 	 */
1577 	return (MIN(nqueues, MIN(nq.b.nq_nsq, nq.b.nq_ncq)));
1578 }
1579 
1580 static int
1581 nvme_create_io_qpair(nvme_t *nvme, nvme_qpair_t *qp, uint16_t idx)
1582 {
1583 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1584 	nvme_create_queue_dw10_t dw10 = { 0 };
1585 	nvme_create_cq_dw11_t c_dw11 = { 0 };
1586 	nvme_create_sq_dw11_t s_dw11 = { 0 };
1587 
1588 	dw10.b.q_qid = idx;
1589 	dw10.b.q_qsize = qp->nq_nentry - 1;
1590 
1591 	c_dw11.b.cq_pc = 1;
1592 	c_dw11.b.cq_ien = 1;
1593 	c_dw11.b.cq_iv = idx % nvme->n_intr_cnt;
1594 
1595 	cmd->nc_sqid = 0;
1596 	cmd->nc_callback = nvme_wakeup_cmd;
1597 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_CQUEUE;
1598 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
1599 	cmd->nc_sqe.sqe_cdw11 = c_dw11.r;
1600 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_cqdma->nd_cookie.dmac_laddress;
1601 
1602 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1603 		dev_err(nvme->n_dip, CE_WARN,
1604 		    "!nvme_admin_cmd failed for CREATE CQUEUE");
1605 		return (DDI_FAILURE);
1606 	}
1607 
1608 	if (nvme_check_cmd_status(cmd)) {
1609 		dev_err(nvme->n_dip, CE_WARN,
1610 		    "!CREATE CQUEUE failed with sct = %x, sc = %x",
1611 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1612 		nvme_free_cmd(cmd);
1613 		return (DDI_FAILURE);
1614 	}
1615 
1616 	nvme_free_cmd(cmd);
1617 
1618 	s_dw11.b.sq_pc = 1;
1619 	s_dw11.b.sq_cqid = idx;
1620 
1621 	cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1622 	cmd->nc_sqid = 0;
1623 	cmd->nc_callback = nvme_wakeup_cmd;
1624 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_SQUEUE;
1625 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
1626 	cmd->nc_sqe.sqe_cdw11 = s_dw11.r;
1627 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_sqdma->nd_cookie.dmac_laddress;
1628 
1629 	if (nvme_admin_cmd(cmd, NVME_ADMIN_CMD_TIMEOUT) != DDI_SUCCESS) {
1630 		dev_err(nvme->n_dip, CE_WARN,
1631 		    "!nvme_admin_cmd failed for CREATE SQUEUE");
1632 		return (DDI_FAILURE);
1633 	}
1634 
1635 	if (nvme_check_cmd_status(cmd)) {
1636 		dev_err(nvme->n_dip, CE_WARN,
1637 		    "!CREATE SQUEUE failed with sct = %x, sc = %x",
1638 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1639 		nvme_free_cmd(cmd);
1640 		return (DDI_FAILURE);
1641 	}
1642 
1643 	nvme_free_cmd(cmd);
1644 
1645 	return (DDI_SUCCESS);
1646 }
1647 
1648 static boolean_t
1649 nvme_reset(nvme_t *nvme, boolean_t quiesce)
1650 {
1651 	nvme_reg_csts_t csts;
1652 	int i;
1653 
1654 	nvme_put32(nvme, NVME_REG_CC, 0);
1655 
1656 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1657 	if (csts.b.csts_rdy == 1) {
1658 		nvme_put32(nvme, NVME_REG_CC, 0);
1659 		for (i = 0; i != nvme->n_timeout * 10; i++) {
1660 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1661 			if (csts.b.csts_rdy == 0)
1662 				break;
1663 
1664 			if (quiesce)
1665 				drv_usecwait(50000);
1666 			else
1667 				delay(drv_usectohz(50000));
1668 		}
1669 	}
1670 
1671 	nvme_put32(nvme, NVME_REG_AQA, 0);
1672 	nvme_put32(nvme, NVME_REG_ASQ, 0);
1673 	nvme_put32(nvme, NVME_REG_ACQ, 0);
1674 
1675 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1676 	return (csts.b.csts_rdy == 0 ? B_TRUE : B_FALSE);
1677 }
1678 
1679 static void
1680 nvme_shutdown(nvme_t *nvme, int mode, boolean_t quiesce)
1681 {
1682 	nvme_reg_cc_t cc;
1683 	nvme_reg_csts_t csts;
1684 	int i;
1685 
1686 	ASSERT(mode == NVME_CC_SHN_NORMAL || mode == NVME_CC_SHN_ABRUPT);
1687 
1688 	cc.r = nvme_get32(nvme, NVME_REG_CC);
1689 	cc.b.cc_shn = mode & 0x3;
1690 	nvme_put32(nvme, NVME_REG_CC, cc.r);
1691 
1692 	for (i = 0; i != 10; i++) {
1693 		csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1694 		if (csts.b.csts_shst == NVME_CSTS_SHN_COMPLETE)
1695 			break;
1696 
1697 		if (quiesce)
1698 			drv_usecwait(100000);
1699 		else
1700 			delay(drv_usectohz(100000));
1701 	}
1702 }
1703 
1704 
1705 static void
1706 nvme_prepare_devid(nvme_t *nvme, uint32_t nsid)
1707 {
1708 	char model[sizeof (nvme->n_idctl->id_model) + 1];
1709 	char serial[sizeof (nvme->n_idctl->id_serial) + 1];
1710 
1711 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
1712 	bcopy(nvme->n_idctl->id_serial, serial,
1713 	    sizeof (nvme->n_idctl->id_serial));
1714 
1715 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
1716 	serial[sizeof (nvme->n_idctl->id_serial)] = '\0';
1717 
1718 	(void) snprintf(nvme->n_ns[nsid - 1].ns_devid,
1719 	    sizeof (nvme->n_ns[0].ns_devid), "%4X-%s-%s-%X",
1720 	    nvme->n_idctl->id_vid, model, serial, nsid);
1721 }
1722 
1723 static int
1724 nvme_init(nvme_t *nvme)
1725 {
1726 	nvme_reg_cc_t cc = { 0 };
1727 	nvme_reg_aqa_t aqa = { 0 };
1728 	nvme_reg_asq_t asq = { 0 };
1729 	nvme_reg_acq_t acq = { 0 };
1730 	nvme_reg_cap_t cap;
1731 	nvme_reg_vs_t vs;
1732 	nvme_reg_csts_t csts;
1733 	int i = 0;
1734 	int nqueues;
1735 	char model[sizeof (nvme->n_idctl->id_model) + 1];
1736 	char *vendor, *product;
1737 
1738 	/* Setup fixed interrupt for admin queue. */
1739 	if (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_FIXED, 1)
1740 	    != DDI_SUCCESS) {
1741 		dev_err(nvme->n_dip, CE_WARN,
1742 		    "!failed to setup fixed interrupt");
1743 		goto fail;
1744 	}
1745 
1746 	/* Check controller version */
1747 	vs.r = nvme_get32(nvme, NVME_REG_VS);
1748 	dev_err(nvme->n_dip, CE_CONT, "?NVMe spec version %d.%d",
1749 	    vs.b.vs_mjr, vs.b.vs_mnr);
1750 
1751 	if (nvme_version_major < vs.b.vs_mjr &&
1752 	    nvme_version_minor < vs.b.vs_mnr) {
1753 		dev_err(nvme->n_dip, CE_WARN, "!no support for version > %d.%d",
1754 		    nvme_version_major, nvme_version_minor);
1755 		if (nvme->n_strict_version)
1756 			goto fail;
1757 	}
1758 
1759 	/* retrieve controller configuration */
1760 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
1761 
1762 	if ((cap.b.cap_css & NVME_CAP_CSS_NVM) == 0) {
1763 		dev_err(nvme->n_dip, CE_WARN,
1764 		    "!NVM command set not supported by hardware");
1765 		goto fail;
1766 	}
1767 
1768 	nvme->n_nssr_supported = cap.b.cap_nssrs;
1769 	nvme->n_doorbell_stride = 4 << cap.b.cap_dstrd;
1770 	nvme->n_timeout = cap.b.cap_to;
1771 	nvme->n_arbitration_mechanisms = cap.b.cap_ams;
1772 	nvme->n_cont_queues_reqd = cap.b.cap_cqr;
1773 	nvme->n_max_queue_entries = cap.b.cap_mqes + 1;
1774 
1775 	/*
1776 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to specify
1777 	 * the base page size of 4k (1<<12), so add 12 here to get the real
1778 	 * page size value.
1779 	 */
1780 	nvme->n_pageshift = MIN(MAX(cap.b.cap_mpsmin + 12, PAGESHIFT),
1781 	    cap.b.cap_mpsmax + 12);
1782 	nvme->n_pagesize = 1UL << (nvme->n_pageshift);
1783 
1784 	/*
1785 	 * Set up Queue DMA to transfer at least 1 page-aligned page at a time.
1786 	 */
1787 	nvme->n_queue_dma_attr.dma_attr_align = nvme->n_pagesize;
1788 	nvme->n_queue_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
1789 
1790 	/*
1791 	 * Set up PRP DMA to transfer 1 page-aligned page at a time.
1792 	 * Maxxfer may be increased after we identified the controller limits.
1793 	 */
1794 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_pagesize;
1795 	nvme->n_prp_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
1796 	nvme->n_prp_dma_attr.dma_attr_align = nvme->n_pagesize;
1797 
1798 	/*
1799 	 * Reset controller if it's still in ready state.
1800 	 */
1801 	if (nvme_reset(nvme, B_FALSE) == B_FALSE) {
1802 		dev_err(nvme->n_dip, CE_WARN, "!unable to reset controller");
1803 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1804 		nvme->n_dead = B_TRUE;
1805 		goto fail;
1806 	}
1807 
1808 	/*
1809 	 * Create the admin queue pair.
1810 	 */
1811 	if (nvme_alloc_qpair(nvme, nvme->n_admin_queue_len, &nvme->n_adminq, 0)
1812 	    != DDI_SUCCESS) {
1813 		dev_err(nvme->n_dip, CE_WARN,
1814 		    "!unable to allocate admin qpair");
1815 		goto fail;
1816 	}
1817 	nvme->n_ioq = kmem_alloc(sizeof (nvme_qpair_t *), KM_SLEEP);
1818 	nvme->n_ioq[0] = nvme->n_adminq;
1819 
1820 	nvme->n_progress |= NVME_ADMIN_QUEUE;
1821 
1822 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
1823 	    "admin-queue-len", nvme->n_admin_queue_len);
1824 
1825 	aqa.b.aqa_asqs = aqa.b.aqa_acqs = nvme->n_admin_queue_len - 1;
1826 	asq = nvme->n_adminq->nq_sqdma->nd_cookie.dmac_laddress;
1827 	acq = nvme->n_adminq->nq_cqdma->nd_cookie.dmac_laddress;
1828 
1829 	ASSERT((asq & (nvme->n_pagesize - 1)) == 0);
1830 	ASSERT((acq & (nvme->n_pagesize - 1)) == 0);
1831 
1832 	nvme_put32(nvme, NVME_REG_AQA, aqa.r);
1833 	nvme_put64(nvme, NVME_REG_ASQ, asq);
1834 	nvme_put64(nvme, NVME_REG_ACQ, acq);
1835 
1836 	cc.b.cc_ams = 0; /* use Round-Robin arbitration */
1837 	cc.b.cc_css = 0; /* use NVM command set */
1838 	cc.b.cc_mps = nvme->n_pageshift - 12;
1839 	cc.b.cc_shn = 0; /* no shutdown in progress */
1840 	cc.b.cc_en = 1;  /* enable controller */
1841 
1842 	nvme_put32(nvme, NVME_REG_CC, cc.r);
1843 
1844 	/*
1845 	 * Wait for the controller to become ready.
1846 	 */
1847 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1848 	if (csts.b.csts_rdy == 0) {
1849 		for (i = 0; i != nvme->n_timeout * 10; i++) {
1850 			delay(drv_usectohz(50000));
1851 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1852 
1853 			if (csts.b.csts_cfs == 1) {
1854 				dev_err(nvme->n_dip, CE_WARN,
1855 				    "!controller fatal status at init");
1856 				ddi_fm_service_impact(nvme->n_dip,
1857 				    DDI_SERVICE_LOST);
1858 				nvme->n_dead = B_TRUE;
1859 				goto fail;
1860 			}
1861 
1862 			if (csts.b.csts_rdy == 1)
1863 				break;
1864 		}
1865 	}
1866 
1867 	if (csts.b.csts_rdy == 0) {
1868 		dev_err(nvme->n_dip, CE_WARN, "!controller not ready");
1869 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1870 		nvme->n_dead = B_TRUE;
1871 		goto fail;
1872 	}
1873 
1874 	/*
1875 	 * Assume an abort command limit of 1. We'll destroy and re-init
1876 	 * that later when we know the true abort command limit.
1877 	 */
1878 	sema_init(&nvme->n_abort_sema, 1, NULL, SEMA_DRIVER, NULL);
1879 
1880 	/*
1881 	 * Post an asynchronous event command to catch errors.
1882 	 */
1883 	if (nvme_async_event(nvme) != DDI_SUCCESS) {
1884 		dev_err(nvme->n_dip, CE_WARN,
1885 		    "!failed to post async event");
1886 		goto fail;
1887 	}
1888 
1889 	/*
1890 	 * Identify Controller
1891 	 */
1892 	nvme->n_idctl = nvme_identify(nvme, 0);
1893 	if (nvme->n_idctl == NULL) {
1894 		dev_err(nvme->n_dip, CE_WARN,
1895 		    "!failed to identify controller");
1896 		goto fail;
1897 	}
1898 
1899 	/*
1900 	 * Get Vendor & Product ID
1901 	 */
1902 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
1903 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
1904 	sata_split_model(model, &vendor, &product);
1905 
1906 	if (vendor == NULL)
1907 		nvme->n_vendor = strdup("NVMe");
1908 	else
1909 		nvme->n_vendor = strdup(vendor);
1910 
1911 	nvme->n_product = strdup(product);
1912 
1913 	/*
1914 	 * Get controller limits.
1915 	 */
1916 	nvme->n_async_event_limit = MAX(NVME_MIN_ASYNC_EVENT_LIMIT,
1917 	    MIN(nvme->n_admin_queue_len / 10,
1918 	    MIN(nvme->n_idctl->id_aerl + 1, nvme->n_async_event_limit)));
1919 
1920 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
1921 	    "async-event-limit", nvme->n_async_event_limit);
1922 
1923 	nvme->n_abort_command_limit = nvme->n_idctl->id_acl + 1;
1924 
1925 	/* disable NVMe interrupts while reinitializing the semaphore */
1926 	nvme_disable_interrupts(nvme);
1927 	sema_destroy(&nvme->n_abort_sema);
1928 	sema_init(&nvme->n_abort_sema, nvme->n_abort_command_limit - 1, NULL,
1929 	    SEMA_DRIVER, NULL);
1930 	if (nvme_enable_interrupts(nvme) != DDI_SUCCESS) {
1931 		dev_err(nvme->n_dip, CE_WARN,
1932 		    "!failed to re-enable interrupts");
1933 		goto fail;
1934 	}
1935 
1936 	nvme->n_progress |= NVME_CTRL_LIMITS;
1937 
1938 	if (nvme->n_idctl->id_mdts == 0)
1939 		nvme->n_max_data_transfer_size = nvme->n_pagesize * 65536;
1940 	else
1941 		nvme->n_max_data_transfer_size =
1942 		    1ull << (nvme->n_pageshift + nvme->n_idctl->id_mdts);
1943 
1944 	nvme->n_error_log_len = nvme->n_idctl->id_elpe + 1;
1945 
1946 	/*
1947 	 * Limit n_max_data_transfer_size to what we can handle in one PRP.
1948 	 * Chained PRPs are currently unsupported.
1949 	 *
1950 	 * This is a no-op on hardware which doesn't support a transfer size
1951 	 * big enough to require chained PRPs.
1952 	 */
1953 	nvme->n_max_data_transfer_size = MIN(nvme->n_max_data_transfer_size,
1954 	    (nvme->n_pagesize / sizeof (uint64_t) * nvme->n_pagesize));
1955 
1956 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_max_data_transfer_size;
1957 
1958 	/*
1959 	 * Make sure the minimum/maximum queue entry sizes are not
1960 	 * larger/smaller than the default.
1961 	 */
1962 
1963 	if (((1 << nvme->n_idctl->id_sqes.qes_min) > sizeof (nvme_sqe_t)) ||
1964 	    ((1 << nvme->n_idctl->id_sqes.qes_max) < sizeof (nvme_sqe_t)) ||
1965 	    ((1 << nvme->n_idctl->id_cqes.qes_min) > sizeof (nvme_cqe_t)) ||
1966 	    ((1 << nvme->n_idctl->id_cqes.qes_max) < sizeof (nvme_cqe_t)))
1967 		goto fail;
1968 
1969 	/*
1970 	 * Check for the presence of a Volatile Write Cache. If present,
1971 	 * enable it by default.
1972 	 */
1973 	if (nvme->n_idctl->id_vwc.vwc_present == 0) {
1974 		nvme->n_volatile_write_cache_enabled = B_FALSE;
1975 		nvme_bd_ops.o_sync_cache = NULL;
1976 	} else {
1977 		/*
1978 		 * TODO: send SET FEATURES to enable VWC
1979 		 * (have no hardware to test this)
1980 		 */
1981 		nvme->n_volatile_write_cache_enabled = B_FALSE;
1982 		nvme_bd_ops.o_sync_cache = NULL;
1983 	}
1984 
1985 	/*
1986 	 * Grab a copy of all mandatory log pages.
1987 	 *
1988 	 * TODO: should go away once user space tool exists to print logs
1989 	 */
1990 	nvme->n_error_log = (nvme_error_log_entry_t *)
1991 	    nvme_get_logpage(nvme, NVME_LOGPAGE_ERROR);
1992 	nvme->n_health_log = (nvme_health_log_t *)
1993 	    nvme_get_logpage(nvme, NVME_LOGPAGE_HEALTH, -1);
1994 	nvme->n_fwslot_log = (nvme_fwslot_log_t *)
1995 	    nvme_get_logpage(nvme, NVME_LOGPAGE_FWSLOT);
1996 
1997 	/*
1998 	 * Identify Namespaces
1999 	 */
2000 	nvme->n_namespace_count = nvme->n_idctl->id_nn;
2001 	nvme->n_ns = kmem_zalloc(sizeof (nvme_namespace_t) *
2002 	    nvme->n_namespace_count, KM_SLEEP);
2003 
2004 	for (i = 0; i != nvme->n_namespace_count; i++) {
2005 		nvme_identify_nsid_t *idns;
2006 		int last_rp;
2007 
2008 		nvme->n_ns[i].ns_nvme = nvme;
2009 		nvme->n_ns[i].ns_idns = idns = nvme_identify(nvme, i + 1);
2010 
2011 		if (idns == NULL) {
2012 			dev_err(nvme->n_dip, CE_WARN,
2013 			    "!failed to identify namespace %d", i + 1);
2014 			goto fail;
2015 		}
2016 
2017 		nvme->n_ns[i].ns_id = i + 1;
2018 		nvme->n_ns[i].ns_block_count = idns->id_nsize;
2019 		nvme->n_ns[i].ns_block_size =
2020 		    1 << idns->id_lbaf[idns->id_flbas.lba_format].lbaf_lbads;
2021 		nvme->n_ns[i].ns_best_block_size = nvme->n_ns[i].ns_block_size;
2022 
2023 		nvme_prepare_devid(nvme, nvme->n_ns[i].ns_id);
2024 
2025 		/*
2026 		 * Find the LBA format with no metadata and the best relative
2027 		 * performance. A value of 3 means "degraded", 0 is best.
2028 		 */
2029 		last_rp = 3;
2030 		for (int j = 0; j != idns->id_nlbaf; j++) {
2031 			if (idns->id_lbaf[j].lbaf_lbads == 0)
2032 				break;
2033 			if (idns->id_lbaf[j].lbaf_ms != 0)
2034 				continue;
2035 			if (idns->id_lbaf[j].lbaf_rp >= last_rp)
2036 				continue;
2037 			last_rp = idns->id_lbaf[j].lbaf_rp;
2038 			nvme->n_ns[i].ns_best_block_size =
2039 			    1 << idns->id_lbaf[j].lbaf_lbads;
2040 		}
2041 
2042 		/*
2043 		 * We currently don't support namespaces that use either:
2044 		 * - thin provisioning
2045 		 * - extended LBAs
2046 		 * - protection information
2047 		 */
2048 		if (idns->id_nsfeat.f_thin ||
2049 		    idns->id_flbas.lba_extlba ||
2050 		    idns->id_dps.dp_pinfo) {
2051 			dev_err(nvme->n_dip, CE_WARN,
2052 			    "!ignoring namespace %d, unsupported features: "
2053 			    "thin = %d, extlba = %d, pinfo = %d", i + 1,
2054 			    idns->id_nsfeat.f_thin, idns->id_flbas.lba_extlba,
2055 			    idns->id_dps.dp_pinfo);
2056 			nvme->n_ns[i].ns_ignore = B_TRUE;
2057 		}
2058 	}
2059 
2060 	/*
2061 	 * Try to set up MSI/MSI-X interrupts.
2062 	 */
2063 	if ((nvme->n_intr_types & (DDI_INTR_TYPE_MSI | DDI_INTR_TYPE_MSIX))
2064 	    != 0) {
2065 		nvme_release_interrupts(nvme);
2066 
2067 		nqueues = MIN(UINT16_MAX, ncpus);
2068 
2069 		if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX,
2070 		    nqueues) != DDI_SUCCESS) &&
2071 		    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI,
2072 		    nqueues) != DDI_SUCCESS)) {
2073 			dev_err(nvme->n_dip, CE_WARN,
2074 			    "!failed to setup MSI/MSI-X interrupts");
2075 			goto fail;
2076 		}
2077 	}
2078 
2079 	nqueues = nvme->n_intr_cnt;
2080 
2081 	/*
2082 	 * Create I/O queue pairs.
2083 	 */
2084 	nvme->n_ioq_count = nvme_set_nqueues(nvme, nqueues);
2085 	if (nvme->n_ioq_count == 0) {
2086 		dev_err(nvme->n_dip, CE_WARN,
2087 		    "!failed to set number of I/O queues to %d", nqueues);
2088 		goto fail;
2089 	}
2090 
2091 	/*
2092 	 * Reallocate I/O queue array
2093 	 */
2094 	kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *));
2095 	nvme->n_ioq = kmem_zalloc(sizeof (nvme_qpair_t *) *
2096 	    (nvme->n_ioq_count + 1), KM_SLEEP);
2097 	nvme->n_ioq[0] = nvme->n_adminq;
2098 
2099 	/*
2100 	 * If we got less queues than we asked for we might as well give
2101 	 * some of the interrupt vectors back to the system.
2102 	 */
2103 	if (nvme->n_ioq_count < nqueues) {
2104 		nvme_release_interrupts(nvme);
2105 
2106 		if (nvme_setup_interrupts(nvme, nvme->n_intr_type, nqueues)
2107 		    != DDI_SUCCESS) {
2108 			dev_err(nvme->n_dip, CE_WARN,
2109 			    "!failed to reduce number of interrupts");
2110 			goto fail;
2111 		}
2112 	}
2113 
2114 	/*
2115 	 * Alloc & register I/O queue pairs
2116 	 */
2117 	nvme->n_io_queue_len =
2118 	    MIN(nvme->n_io_queue_len, nvme->n_max_queue_entries);
2119 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip, "io-queue-len",
2120 	    nvme->n_io_queue_len);
2121 
2122 	for (i = 1; i != nvme->n_ioq_count + 1; i++) {
2123 		if (nvme_alloc_qpair(nvme, nvme->n_io_queue_len,
2124 		    &nvme->n_ioq[i], i) != DDI_SUCCESS) {
2125 			dev_err(nvme->n_dip, CE_WARN,
2126 			    "!unable to allocate I/O qpair %d", i);
2127 			goto fail;
2128 		}
2129 
2130 		if (nvme_create_io_qpair(nvme, nvme->n_ioq[i], i)
2131 		    != DDI_SUCCESS) {
2132 			dev_err(nvme->n_dip, CE_WARN,
2133 			    "!unable to create I/O qpair %d", i);
2134 			goto fail;
2135 		}
2136 	}
2137 
2138 	/*
2139 	 * Post more asynchronous events commands to reduce event reporting
2140 	 * latency as suggested by the spec.
2141 	 */
2142 	for (i = 1; i != nvme->n_async_event_limit; i++) {
2143 		if (nvme_async_event(nvme) != DDI_SUCCESS) {
2144 			dev_err(nvme->n_dip, CE_WARN,
2145 			    "!failed to post async event %d", i);
2146 			goto fail;
2147 		}
2148 	}
2149 
2150 	return (DDI_SUCCESS);
2151 
2152 fail:
2153 	(void) nvme_reset(nvme, B_FALSE);
2154 	return (DDI_FAILURE);
2155 }
2156 
2157 static uint_t
2158 nvme_intr(caddr_t arg1, caddr_t arg2)
2159 {
2160 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
2161 	nvme_t *nvme = (nvme_t *)arg1;
2162 	int inum = (int)(uintptr_t)arg2;
2163 	int qnum;
2164 	nvme_cmd_t *cmd;
2165 
2166 	if (inum >= nvme->n_intr_cnt)
2167 		return (DDI_INTR_UNCLAIMED);
2168 
2169 	/*
2170 	 * The interrupt vector a queue uses is calculated as queue_idx %
2171 	 * intr_cnt in nvme_create_io_qpair(). Iterate through the queue array
2172 	 * in steps of n_intr_cnt to process all queues using this vector.
2173 	 */
2174 	for (qnum = inum;
2175 	    qnum < nvme->n_ioq_count + 1 && nvme->n_ioq[qnum] != NULL;
2176 	    qnum += nvme->n_intr_cnt) {
2177 		while ((cmd = nvme_retrieve_cmd(nvme, nvme->n_ioq[qnum]))) {
2178 			taskq_dispatch_ent((taskq_t *)cmd->nc_nvme->n_cmd_taskq,
2179 			    cmd->nc_callback, cmd, TQ_NOSLEEP, &cmd->nc_tqent);
2180 		}
2181 	}
2182 
2183 	return (DDI_INTR_CLAIMED);
2184 }
2185 
2186 static void
2187 nvme_disable_interrupts(nvme_t *nvme)
2188 {
2189 	int i;
2190 
2191 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2192 		if (nvme->n_inth[i] == NULL)
2193 			break;
2194 
2195 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
2196 			(void) ddi_intr_block_disable(&nvme->n_inth[i], 1);
2197 		else
2198 			(void) ddi_intr_disable(nvme->n_inth[i]);
2199 	}
2200 }
2201 
2202 static int
2203 nvme_enable_interrupts(nvme_t *nvme)
2204 {
2205 	int i, fail = 0;
2206 
2207 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2208 		if (nvme->n_inth[i] == NULL)
2209 			break;
2210 
2211 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK) {
2212 			if (ddi_intr_block_enable(&nvme->n_inth[i], 1) !=
2213 			    DDI_SUCCESS)
2214 				fail++;
2215 		} else {
2216 			if (ddi_intr_enable(nvme->n_inth[i]) != DDI_SUCCESS)
2217 				fail++;
2218 		}
2219 	}
2220 
2221 	return (fail ? DDI_FAILURE : DDI_SUCCESS);
2222 }
2223 
2224 static void
2225 nvme_release_interrupts(nvme_t *nvme)
2226 {
2227 	int i;
2228 
2229 	nvme_disable_interrupts(nvme);
2230 
2231 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2232 		if (nvme->n_inth[i] == NULL)
2233 			break;
2234 
2235 		(void) ddi_intr_remove_handler(nvme->n_inth[i]);
2236 		(void) ddi_intr_free(nvme->n_inth[i]);
2237 	}
2238 
2239 	kmem_free(nvme->n_inth, nvme->n_inth_sz);
2240 	nvme->n_inth = NULL;
2241 	nvme->n_inth_sz = 0;
2242 
2243 	nvme->n_progress &= ~NVME_INTERRUPTS;
2244 }
2245 
2246 static int
2247 nvme_setup_interrupts(nvme_t *nvme, int intr_type, int nqpairs)
2248 {
2249 	int nintrs, navail, count;
2250 	int ret;
2251 	int i;
2252 
2253 	if (nvme->n_intr_types == 0) {
2254 		ret = ddi_intr_get_supported_types(nvme->n_dip,
2255 		    &nvme->n_intr_types);
2256 		if (ret != DDI_SUCCESS) {
2257 			dev_err(nvme->n_dip, CE_WARN,
2258 			    "!%s: ddi_intr_get_supported types failed",
2259 			    __func__);
2260 			return (ret);
2261 		}
2262 	}
2263 
2264 	if ((nvme->n_intr_types & intr_type) == 0)
2265 		return (DDI_FAILURE);
2266 
2267 	ret = ddi_intr_get_nintrs(nvme->n_dip, intr_type, &nintrs);
2268 	if (ret != DDI_SUCCESS) {
2269 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_nintrs failed",
2270 		    __func__);
2271 		return (ret);
2272 	}
2273 
2274 	ret = ddi_intr_get_navail(nvme->n_dip, intr_type, &navail);
2275 	if (ret != DDI_SUCCESS) {
2276 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_navail failed",
2277 		    __func__);
2278 		return (ret);
2279 	}
2280 
2281 	/* We want at most one interrupt per queue pair. */
2282 	if (navail > nqpairs)
2283 		navail = nqpairs;
2284 
2285 	nvme->n_inth_sz = sizeof (ddi_intr_handle_t) * navail;
2286 	nvme->n_inth = kmem_zalloc(nvme->n_inth_sz, KM_SLEEP);
2287 
2288 	ret = ddi_intr_alloc(nvme->n_dip, nvme->n_inth, intr_type, 0, navail,
2289 	    &count, 0);
2290 	if (ret != DDI_SUCCESS) {
2291 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_alloc failed",
2292 		    __func__);
2293 		goto fail;
2294 	}
2295 
2296 	nvme->n_intr_cnt = count;
2297 
2298 	ret = ddi_intr_get_pri(nvme->n_inth[0], &nvme->n_intr_pri);
2299 	if (ret != DDI_SUCCESS) {
2300 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_pri failed",
2301 		    __func__);
2302 		goto fail;
2303 	}
2304 
2305 	for (i = 0; i < count; i++) {
2306 		ret = ddi_intr_add_handler(nvme->n_inth[i], nvme_intr,
2307 		    (void *)nvme, (void *)(uintptr_t)i);
2308 		if (ret != DDI_SUCCESS) {
2309 			dev_err(nvme->n_dip, CE_WARN,
2310 			    "!%s: ddi_intr_add_handler failed", __func__);
2311 			goto fail;
2312 		}
2313 	}
2314 
2315 	(void) ddi_intr_get_cap(nvme->n_inth[0], &nvme->n_intr_cap);
2316 
2317 	ret = nvme_enable_interrupts(nvme);
2318 
2319 	if (ret != DDI_SUCCESS) {
2320 		dev_err(nvme->n_dip, CE_WARN,
2321 		    "!%s: nvme_enable_interrupts failed", __func__);
2322 		goto fail;
2323 	}
2324 
2325 	nvme->n_intr_type = intr_type;
2326 
2327 	nvme->n_progress |= NVME_INTERRUPTS;
2328 
2329 	return (DDI_SUCCESS);
2330 
2331 fail:
2332 	nvme_release_interrupts(nvme);
2333 
2334 	return (ret);
2335 }
2336 
2337 static int
2338 nvme_fm_errcb(dev_info_t *dip, ddi_fm_error_t *fm_error, const void *arg)
2339 {
2340 	_NOTE(ARGUNUSED(arg));
2341 
2342 	pci_ereport_post(dip, fm_error, NULL);
2343 	return (fm_error->fme_status);
2344 }
2345 
2346 static int
2347 nvme_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
2348 {
2349 	nvme_t *nvme;
2350 	int instance;
2351 	int nregs;
2352 	off_t regsize;
2353 	int i;
2354 	char name[32];
2355 
2356 	if (cmd != DDI_ATTACH)
2357 		return (DDI_FAILURE);
2358 
2359 	instance = ddi_get_instance(dip);
2360 
2361 	if (ddi_soft_state_zalloc(nvme_state, instance) != DDI_SUCCESS)
2362 		return (DDI_FAILURE);
2363 
2364 	nvme = ddi_get_soft_state(nvme_state, instance);
2365 	ddi_set_driver_private(dip, nvme);
2366 	nvme->n_dip = dip;
2367 
2368 	nvme->n_strict_version = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2369 	    DDI_PROP_DONTPASS, "strict-version", 1) == 1 ? B_TRUE : B_FALSE;
2370 	nvme->n_ignore_unknown_vendor_status = ddi_prop_get_int(DDI_DEV_T_ANY,
2371 	    dip, DDI_PROP_DONTPASS, "ignore-unknown-vendor-status", 0) == 1 ?
2372 	    B_TRUE : B_FALSE;
2373 	nvme->n_admin_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2374 	    DDI_PROP_DONTPASS, "admin-queue-len", NVME_DEFAULT_ADMIN_QUEUE_LEN);
2375 	nvme->n_io_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2376 	    DDI_PROP_DONTPASS, "io-queue-len", NVME_DEFAULT_IO_QUEUE_LEN);
2377 	nvme->n_async_event_limit = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2378 	    DDI_PROP_DONTPASS, "async-event-limit",
2379 	    NVME_DEFAULT_ASYNC_EVENT_LIMIT);
2380 
2381 	if (nvme->n_admin_queue_len < NVME_MIN_ADMIN_QUEUE_LEN)
2382 		nvme->n_admin_queue_len = NVME_MIN_ADMIN_QUEUE_LEN;
2383 	else if (nvme->n_admin_queue_len > NVME_MAX_ADMIN_QUEUE_LEN)
2384 		nvme->n_admin_queue_len = NVME_MAX_ADMIN_QUEUE_LEN;
2385 
2386 	if (nvme->n_io_queue_len < NVME_MIN_IO_QUEUE_LEN)
2387 		nvme->n_io_queue_len = NVME_MIN_IO_QUEUE_LEN;
2388 
2389 	if (nvme->n_async_event_limit < 1)
2390 		nvme->n_async_event_limit = NVME_DEFAULT_ASYNC_EVENT_LIMIT;
2391 
2392 	nvme->n_reg_acc_attr = nvme_reg_acc_attr;
2393 	nvme->n_queue_dma_attr = nvme_queue_dma_attr;
2394 	nvme->n_prp_dma_attr = nvme_prp_dma_attr;
2395 	nvme->n_sgl_dma_attr = nvme_sgl_dma_attr;
2396 
2397 	/*
2398 	 * Setup FMA support.
2399 	 */
2400 	nvme->n_fm_cap = ddi_getprop(DDI_DEV_T_ANY, dip,
2401 	    DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
2402 	    DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
2403 	    DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
2404 
2405 	ddi_fm_init(dip, &nvme->n_fm_cap, &nvme->n_fm_ibc);
2406 
2407 	if (nvme->n_fm_cap) {
2408 		if (nvme->n_fm_cap & DDI_FM_ACCCHK_CAPABLE)
2409 			nvme->n_reg_acc_attr.devacc_attr_access =
2410 			    DDI_FLAGERR_ACC;
2411 
2412 		if (nvme->n_fm_cap & DDI_FM_DMACHK_CAPABLE) {
2413 			nvme->n_prp_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2414 			nvme->n_sgl_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2415 		}
2416 
2417 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
2418 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2419 			pci_ereport_setup(dip);
2420 
2421 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2422 			ddi_fm_handler_register(dip, nvme_fm_errcb,
2423 			    (void *)nvme);
2424 	}
2425 
2426 	nvme->n_progress |= NVME_FMA_INIT;
2427 
2428 	/*
2429 	 * The spec defines several register sets. Only the controller
2430 	 * registers (set 1) are currently used.
2431 	 */
2432 	if (ddi_dev_nregs(dip, &nregs) == DDI_FAILURE ||
2433 	    nregs < 2 ||
2434 	    ddi_dev_regsize(dip, 1, &regsize) == DDI_FAILURE)
2435 		goto fail;
2436 
2437 	if (ddi_regs_map_setup(dip, 1, &nvme->n_regs, 0, regsize,
2438 	    &nvme->n_reg_acc_attr, &nvme->n_regh) != DDI_SUCCESS) {
2439 		dev_err(dip, CE_WARN, "!failed to map regset 1");
2440 		goto fail;
2441 	}
2442 
2443 	nvme->n_progress |= NVME_REGS_MAPPED;
2444 
2445 	/*
2446 	 * Create taskq for command completion.
2447 	 */
2448 	(void) snprintf(name, sizeof (name), "%s%d_cmd_taskq",
2449 	    ddi_driver_name(dip), ddi_get_instance(dip));
2450 	nvme->n_cmd_taskq = ddi_taskq_create(dip, name, MIN(UINT16_MAX, ncpus),
2451 	    TASKQ_DEFAULTPRI, 0);
2452 	if (nvme->n_cmd_taskq == NULL) {
2453 		dev_err(dip, CE_WARN, "!failed to create cmd taskq");
2454 		goto fail;
2455 	}
2456 
2457 
2458 	if (nvme_init(nvme) != DDI_SUCCESS)
2459 		goto fail;
2460 
2461 	/*
2462 	 * Attach the blkdev driver for each namespace.
2463 	 */
2464 	for (i = 0; i != nvme->n_namespace_count; i++) {
2465 		if (nvme->n_ns[i].ns_ignore)
2466 			continue;
2467 
2468 		nvme->n_ns[i].ns_bd_hdl = bd_alloc_handle(&nvme->n_ns[i],
2469 		    &nvme_bd_ops, &nvme->n_prp_dma_attr, KM_SLEEP);
2470 
2471 		if (nvme->n_ns[i].ns_bd_hdl == NULL) {
2472 			dev_err(dip, CE_WARN,
2473 			    "!failed to get blkdev handle for namespace %d", i);
2474 			goto fail;
2475 		}
2476 
2477 		if (bd_attach_handle(dip, nvme->n_ns[i].ns_bd_hdl)
2478 		    != DDI_SUCCESS) {
2479 			dev_err(dip, CE_WARN,
2480 			    "!failed to attach blkdev handle for namespace %d",
2481 			    i);
2482 			goto fail;
2483 		}
2484 	}
2485 
2486 	return (DDI_SUCCESS);
2487 
2488 fail:
2489 	/* attach successful anyway so that FMA can retire the device */
2490 	if (nvme->n_dead)
2491 		return (DDI_SUCCESS);
2492 
2493 	(void) nvme_detach(dip, DDI_DETACH);
2494 
2495 	return (DDI_FAILURE);
2496 }
2497 
2498 static int
2499 nvme_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
2500 {
2501 	int instance, i;
2502 	nvme_t *nvme;
2503 
2504 	if (cmd != DDI_DETACH)
2505 		return (DDI_FAILURE);
2506 
2507 	instance = ddi_get_instance(dip);
2508 
2509 	nvme = ddi_get_soft_state(nvme_state, instance);
2510 
2511 	if (nvme == NULL)
2512 		return (DDI_FAILURE);
2513 
2514 	if (nvme->n_ns) {
2515 		for (i = 0; i != nvme->n_namespace_count; i++) {
2516 			if (nvme->n_ns[i].ns_bd_hdl) {
2517 				(void) bd_detach_handle(
2518 				    nvme->n_ns[i].ns_bd_hdl);
2519 				bd_free_handle(nvme->n_ns[i].ns_bd_hdl);
2520 			}
2521 
2522 			if (nvme->n_ns[i].ns_idns)
2523 				kmem_free(nvme->n_ns[i].ns_idns,
2524 				    sizeof (nvme_identify_nsid_t));
2525 		}
2526 
2527 		kmem_free(nvme->n_ns, sizeof (nvme_namespace_t) *
2528 		    nvme->n_namespace_count);
2529 	}
2530 
2531 	if (nvme->n_progress & NVME_INTERRUPTS)
2532 		nvme_release_interrupts(nvme);
2533 
2534 	if (nvme->n_cmd_taskq)
2535 		ddi_taskq_wait(nvme->n_cmd_taskq);
2536 
2537 	if (nvme->n_ioq_count > 0) {
2538 		for (i = 1; i != nvme->n_ioq_count + 1; i++) {
2539 			if (nvme->n_ioq[i] != NULL) {
2540 				/* TODO: send destroy queue commands */
2541 				nvme_free_qpair(nvme->n_ioq[i]);
2542 			}
2543 		}
2544 
2545 		kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *) *
2546 		    (nvme->n_ioq_count + 1));
2547 	}
2548 
2549 	if (nvme->n_progress & NVME_REGS_MAPPED) {
2550 		nvme_shutdown(nvme, NVME_CC_SHN_NORMAL, B_FALSE);
2551 		(void) nvme_reset(nvme, B_FALSE);
2552 	}
2553 
2554 	if (nvme->n_cmd_taskq)
2555 		ddi_taskq_destroy(nvme->n_cmd_taskq);
2556 
2557 	if (nvme->n_progress & NVME_CTRL_LIMITS)
2558 		sema_destroy(&nvme->n_abort_sema);
2559 
2560 	if (nvme->n_progress & NVME_ADMIN_QUEUE)
2561 		nvme_free_qpair(nvme->n_adminq);
2562 
2563 	if (nvme->n_idctl)
2564 		kmem_free(nvme->n_idctl, sizeof (nvme_identify_ctrl_t));
2565 
2566 	if (nvme->n_progress & NVME_REGS_MAPPED)
2567 		ddi_regs_map_free(&nvme->n_regh);
2568 
2569 	if (nvme->n_progress & NVME_FMA_INIT) {
2570 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2571 			ddi_fm_handler_unregister(nvme->n_dip);
2572 
2573 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
2574 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2575 			pci_ereport_teardown(nvme->n_dip);
2576 
2577 		ddi_fm_fini(nvme->n_dip);
2578 	}
2579 
2580 	if (nvme->n_vendor != NULL)
2581 		strfree(nvme->n_vendor);
2582 
2583 	if (nvme->n_product != NULL)
2584 		strfree(nvme->n_product);
2585 
2586 	ddi_soft_state_free(nvme_state, instance);
2587 
2588 	return (DDI_SUCCESS);
2589 }
2590 
2591 static int
2592 nvme_quiesce(dev_info_t *dip)
2593 {
2594 	int instance;
2595 	nvme_t *nvme;
2596 
2597 	instance = ddi_get_instance(dip);
2598 
2599 	nvme = ddi_get_soft_state(nvme_state, instance);
2600 
2601 	if (nvme == NULL)
2602 		return (DDI_FAILURE);
2603 
2604 	nvme_shutdown(nvme, NVME_CC_SHN_ABRUPT, B_TRUE);
2605 
2606 	(void) nvme_reset(nvme, B_TRUE);
2607 
2608 	return (DDI_FAILURE);
2609 }
2610 
2611 static int
2612 nvme_fill_prp(nvme_cmd_t *cmd, bd_xfer_t *xfer)
2613 {
2614 	nvme_t *nvme = cmd->nc_nvme;
2615 	int nprp_page, nprp;
2616 	uint64_t *prp;
2617 
2618 	if (xfer->x_ndmac == 0)
2619 		return (DDI_FAILURE);
2620 
2621 	cmd->nc_sqe.sqe_dptr.d_prp[0] = xfer->x_dmac.dmac_laddress;
2622 	ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
2623 
2624 	if (xfer->x_ndmac == 1) {
2625 		cmd->nc_sqe.sqe_dptr.d_prp[1] = 0;
2626 		return (DDI_SUCCESS);
2627 	} else if (xfer->x_ndmac == 2) {
2628 		cmd->nc_sqe.sqe_dptr.d_prp[1] = xfer->x_dmac.dmac_laddress;
2629 		return (DDI_SUCCESS);
2630 	}
2631 
2632 	xfer->x_ndmac--;
2633 
2634 	nprp_page = nvme->n_pagesize / sizeof (uint64_t) - 1;
2635 	ASSERT(nprp_page > 0);
2636 	nprp = (xfer->x_ndmac + nprp_page - 1) / nprp_page;
2637 
2638 	/*
2639 	 * We currently don't support chained PRPs and set up our DMA
2640 	 * attributes to reflect that. If we still get an I/O request
2641 	 * that needs a chained PRP something is very wrong.
2642 	 */
2643 	VERIFY(nprp == 1);
2644 
2645 	if (nvme_zalloc_dma(nvme, nvme->n_pagesize * nprp, DDI_DMA_READ,
2646 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
2647 		dev_err(nvme->n_dip, CE_WARN, "!%s: nvme_zalloc_dma failed",
2648 		    __func__);
2649 		return (DDI_FAILURE);
2650 	}
2651 
2652 	cmd->nc_sqe.sqe_dptr.d_prp[1] = cmd->nc_dma->nd_cookie.dmac_laddress;
2653 	ddi_dma_nextcookie(cmd->nc_dma->nd_dmah, &cmd->nc_dma->nd_cookie);
2654 
2655 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
2656 	for (prp = (uint64_t *)cmd->nc_dma->nd_memp;
2657 	    xfer->x_ndmac > 0;
2658 	    prp++, xfer->x_ndmac--) {
2659 		*prp = xfer->x_dmac.dmac_laddress;
2660 		ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
2661 	}
2662 
2663 	(void) ddi_dma_sync(cmd->nc_dma->nd_dmah, 0, cmd->nc_dma->nd_len,
2664 	    DDI_DMA_SYNC_FORDEV);
2665 	return (DDI_SUCCESS);
2666 }
2667 
2668 static nvme_cmd_t *
2669 nvme_create_nvm_cmd(nvme_namespace_t *ns, uint8_t opc, bd_xfer_t *xfer)
2670 {
2671 	nvme_t *nvme = ns->ns_nvme;
2672 	nvme_cmd_t *cmd;
2673 
2674 	/*
2675 	 * Blkdev only sets BD_XFER_POLL when dumping, so don't sleep.
2676 	 */
2677 	cmd = nvme_alloc_cmd(nvme, (xfer->x_flags & BD_XFER_POLL) ?
2678 	    KM_NOSLEEP : KM_SLEEP);
2679 
2680 	if (cmd == NULL)
2681 		return (NULL);
2682 
2683 	cmd->nc_sqe.sqe_opc = opc;
2684 	cmd->nc_callback = nvme_bd_xfer_done;
2685 	cmd->nc_xfer = xfer;
2686 
2687 	switch (opc) {
2688 	case NVME_OPC_NVM_WRITE:
2689 	case NVME_OPC_NVM_READ:
2690 		VERIFY(xfer->x_nblks <= 0x10000);
2691 
2692 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
2693 
2694 		cmd->nc_sqe.sqe_cdw10 = xfer->x_blkno & 0xffffffffu;
2695 		cmd->nc_sqe.sqe_cdw11 = (xfer->x_blkno >> 32);
2696 		cmd->nc_sqe.sqe_cdw12 = (uint16_t)(xfer->x_nblks - 1);
2697 
2698 		if (nvme_fill_prp(cmd, xfer) != DDI_SUCCESS)
2699 			goto fail;
2700 		break;
2701 
2702 	case NVME_OPC_NVM_FLUSH:
2703 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
2704 		break;
2705 
2706 	default:
2707 		goto fail;
2708 	}
2709 
2710 	return (cmd);
2711 
2712 fail:
2713 	nvme_free_cmd(cmd);
2714 	return (NULL);
2715 }
2716 
2717 static void
2718 nvme_bd_xfer_done(void *arg)
2719 {
2720 	nvme_cmd_t *cmd = arg;
2721 	bd_xfer_t *xfer = cmd->nc_xfer;
2722 	int error = 0;
2723 
2724 	error = nvme_check_cmd_status(cmd);
2725 	nvme_free_cmd(cmd);
2726 
2727 	bd_xfer_done(xfer, error);
2728 }
2729 
2730 static void
2731 nvme_bd_driveinfo(void *arg, bd_drive_t *drive)
2732 {
2733 	nvme_namespace_t *ns = arg;
2734 	nvme_t *nvme = ns->ns_nvme;
2735 
2736 	/*
2737 	 * blkdev maintains one queue size per instance (namespace),
2738 	 * but all namespace share the I/O queues.
2739 	 * TODO: need to figure out a sane default, or use per-NS I/O queues,
2740 	 * or change blkdev to handle EAGAIN
2741 	 */
2742 	drive->d_qsize = nvme->n_ioq_count * nvme->n_io_queue_len
2743 	    / nvme->n_namespace_count;
2744 
2745 	/*
2746 	 * d_maxxfer is not set, which means the value is taken from the DMA
2747 	 * attributes specified to bd_alloc_handle.
2748 	 */
2749 
2750 	drive->d_removable = B_FALSE;
2751 	drive->d_hotpluggable = B_FALSE;
2752 
2753 	drive->d_target = ns->ns_id;
2754 	drive->d_lun = 0;
2755 
2756 	drive->d_vendor = nvme->n_vendor;
2757 	drive->d_vendor_len = strlen(nvme->n_vendor);
2758 	drive->d_product = nvme->n_product;
2759 	drive->d_product_len = strlen(nvme->n_product);
2760 	drive->d_serial = nvme->n_idctl->id_serial;
2761 	drive->d_serial_len = sizeof (nvme->n_idctl->id_serial);
2762 	drive->d_revision = nvme->n_idctl->id_fwrev;
2763 	drive->d_revision_len = sizeof (nvme->n_idctl->id_fwrev);
2764 }
2765 
2766 static int
2767 nvme_bd_mediainfo(void *arg, bd_media_t *media)
2768 {
2769 	nvme_namespace_t *ns = arg;
2770 
2771 	media->m_nblks = ns->ns_block_count;
2772 	media->m_blksize = ns->ns_block_size;
2773 	media->m_readonly = B_FALSE;
2774 	media->m_solidstate = B_TRUE;
2775 
2776 	media->m_pblksize = ns->ns_best_block_size;
2777 
2778 	return (0);
2779 }
2780 
2781 static int
2782 nvme_bd_cmd(nvme_namespace_t *ns, bd_xfer_t *xfer, uint8_t opc)
2783 {
2784 	nvme_t *nvme = ns->ns_nvme;
2785 	nvme_cmd_t *cmd;
2786 
2787 	if (nvme->n_dead)
2788 		return (EIO);
2789 
2790 	/* No polling for now */
2791 	if (xfer->x_flags & BD_XFER_POLL)
2792 		return (EIO);
2793 
2794 	cmd = nvme_create_nvm_cmd(ns, opc, xfer);
2795 	if (cmd == NULL)
2796 		return (ENOMEM);
2797 
2798 	cmd->nc_sqid = (CPU->cpu_id % nvme->n_ioq_count) + 1;
2799 	ASSERT(cmd->nc_sqid <= nvme->n_ioq_count);
2800 
2801 	if (nvme_submit_cmd(nvme->n_ioq[cmd->nc_sqid], cmd)
2802 	    != DDI_SUCCESS)
2803 		return (EAGAIN);
2804 
2805 	return (0);
2806 }
2807 
2808 static int
2809 nvme_bd_read(void *arg, bd_xfer_t *xfer)
2810 {
2811 	nvme_namespace_t *ns = arg;
2812 
2813 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_READ));
2814 }
2815 
2816 static int
2817 nvme_bd_write(void *arg, bd_xfer_t *xfer)
2818 {
2819 	nvme_namespace_t *ns = arg;
2820 
2821 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_WRITE));
2822 }
2823 
2824 static int
2825 nvme_bd_sync(void *arg, bd_xfer_t *xfer)
2826 {
2827 	nvme_namespace_t *ns = arg;
2828 
2829 	if (ns->ns_nvme->n_dead)
2830 		return (EIO);
2831 
2832 	/*
2833 	 * If the volatile write cache isn't enabled the FLUSH command is a
2834 	 * no-op, so we can take a shortcut here.
2835 	 */
2836 	if (ns->ns_nvme->n_volatile_write_cache_enabled == B_FALSE) {
2837 		bd_xfer_done(xfer, ENOTSUP);
2838 		return (0);
2839 	}
2840 
2841 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_FLUSH));
2842 }
2843 
2844 static int
2845 nvme_bd_devid(void *arg, dev_info_t *devinfo, ddi_devid_t *devid)
2846 {
2847 	nvme_namespace_t *ns = arg;
2848 
2849 	return (ddi_devid_init(devinfo, DEVID_ENCAP, strlen(ns->ns_devid),
2850 	    ns->ns_devid, devid));
2851 }
2852