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