xref: /illumos-gate/usr/src/uts/common/io/nvme/nvme.c (revision dec98d2aa2912b1fbd0abd2574307a695b566692)
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 2016 Nexenta Systems, Inc. All rights reserved.
14  * Copyright 2016 Tegile Systems, Inc. All rights reserved.
15  * Copyright (c) 2016 The MathWorks, Inc.  All rights reserved.
16  * Copyright 2017 Joyent, Inc.
17  */
18 
19 /*
20  * blkdev driver for NVMe compliant storage devices
21  *
22  * This driver was written to conform to version 1.2.1 of the NVMe
23  * specification.  It may work with newer versions, but that is completely
24  * untested and disabled by default.
25  *
26  * The driver has only been tested on x86 systems and will not work on big-
27  * endian systems without changes to the code accessing registers and data
28  * structures used by the hardware.
29  *
30  *
31  * Interrupt Usage:
32  *
33  * The driver will use a single interrupt while configuring the device as the
34  * specification requires, but contrary to the specification it will try to use
35  * a single-message MSI(-X) or FIXED interrupt. Later in the attach process it
36  * will switch to multiple-message MSI(-X) if supported. The driver wants to
37  * have one interrupt vector per CPU, but it will work correctly if less are
38  * available. Interrupts can be shared by queues, the interrupt handler will
39  * iterate through the I/O queue array by steps of n_intr_cnt. Usually only
40  * the admin queue will share an interrupt with one I/O queue. The interrupt
41  * handler will retrieve completed commands from all queues sharing an interrupt
42  * vector and will post them to a taskq for completion processing.
43  *
44  *
45  * Command Processing:
46  *
47  * NVMe devices can have up to 65536 I/O queue pairs, with each queue holding up
48  * to 65536 I/O commands. The driver will configure one I/O queue pair per
49  * available interrupt vector, with the queue length usually much smaller than
50  * the maximum of 65536. If the hardware doesn't provide enough queues, fewer
51  * interrupt vectors will be used.
52  *
53  * Additionally the hardware provides a single special admin queue pair that can
54  * hold up to 4096 admin commands.
55  *
56  * From the hardware perspective both queues of a queue pair are independent,
57  * but they share some driver state: the command array (holding pointers to
58  * commands currently being processed by the hardware) and the active command
59  * counter. Access to the submission side of a queue pair and the shared state
60  * is protected by nq_mutex. The completion side of a queue pair does not need
61  * that protection apart from its access to the shared state; it is called only
62  * in the interrupt handler which does not run concurrently for the same
63  * interrupt vector.
64  *
65  * When a command is submitted to a queue pair the active command counter is
66  * incremented and a pointer to the command is stored in the command array. The
67  * array index is used as command identifier (CID) in the submission queue
68  * entry. Some commands may take a very long time to complete, and if the queue
69  * wraps around in that time a submission may find the next array slot to still
70  * be used by a long-running command. In this case the array is sequentially
71  * searched for the next free slot. The length of the command array is the same
72  * as the configured queue length.
73  *
74  *
75  * Namespace Support:
76  *
77  * NVMe devices can have multiple namespaces, each being a independent data
78  * store. The driver supports multiple namespaces and creates a blkdev interface
79  * for each namespace found. Namespaces can have various attributes to support
80  * thin provisioning and protection information. This driver does not support
81  * any of this and ignores namespaces that have these attributes.
82  *
83  * As of NVMe 1.1 namespaces can have an 64bit Extended Unique Identifier
84  * (EUI64). This driver uses the EUI64 if present to generate the devid and
85  * passes it to blkdev to use it in the device node names. As this is currently
86  * untested namespaces with EUI64 are ignored by default.
87  *
88  * We currently support only (2 << NVME_MINOR_INST_SHIFT) - 2 namespaces in a
89  * single controller. This is an artificial limit imposed by the driver to be
90  * able to address a reasonable number of controllers and namespaces using a
91  * 32bit minor node number.
92  *
93  *
94  * Minor nodes:
95  *
96  * For each NVMe device the driver exposes one minor node for the controller and
97  * one minor node for each namespace. The only operations supported by those
98  * minor nodes are open(9E), close(9E), and ioctl(9E). This serves as the
99  * interface for the nvmeadm(1M) utility.
100  *
101  *
102  * Blkdev Interface:
103  *
104  * This driver uses blkdev to do all the heavy lifting involved with presenting
105  * a disk device to the system. As a result, the processing of I/O requests is
106  * relatively simple as blkdev takes care of partitioning, boundary checks, DMA
107  * setup, and splitting of transfers into manageable chunks.
108  *
109  * I/O requests coming in from blkdev are turned into NVM commands and posted to
110  * an I/O queue. The queue is selected by taking the CPU id modulo the number of
111  * queues. There is currently no timeout handling of I/O commands.
112  *
113  * Blkdev also supports querying device/media information and generating a
114  * devid. The driver reports the best block size as determined by the namespace
115  * format back to blkdev as physical block size to support partition and block
116  * alignment. The devid is either based on the namespace EUI64, if present, or
117  * composed using the device vendor ID, model number, serial number, and the
118  * namespace ID.
119  *
120  *
121  * Error Handling:
122  *
123  * Error handling is currently limited to detecting fatal hardware errors,
124  * either by asynchronous events, or synchronously through command status or
125  * admin command timeouts. In case of severe errors the device is fenced off,
126  * all further requests will return EIO. FMA is then called to fault the device.
127  *
128  * The hardware has a limit for outstanding asynchronous event requests. Before
129  * this limit is known the driver assumes it is at least 1 and posts a single
130  * asynchronous request. Later when the limit is known more asynchronous event
131  * requests are posted to allow quicker reception of error information. When an
132  * asynchronous event is posted by the hardware the driver will parse the error
133  * status fields and log information or fault the device, depending on the
134  * severity of the asynchronous event. The asynchronous event request is then
135  * reused and posted to the admin queue again.
136  *
137  * On command completion the command status is checked for errors. In case of
138  * errors indicating a driver bug the driver panics. Almost all other error
139  * status values just cause EIO to be returned.
140  *
141  * Command timeouts are currently detected for all admin commands except
142  * asynchronous event requests. If a command times out and the hardware appears
143  * to be healthy the driver attempts to abort the command. If this fails the
144  * driver assumes the device to be dead, fences it off, and calls FMA to retire
145  * it. In general admin commands are issued at attach time only. No timeout
146  * handling of normal I/O commands is presently done.
147  *
148  * In some cases it may be possible that the ABORT command times out, too. In
149  * that case the device is also declared dead and fenced off.
150  *
151  *
152  * Quiesce / Fast Reboot:
153  *
154  * The driver currently does not support fast reboot. A quiesce(9E) entry point
155  * is still provided which is used to send a shutdown notification to the
156  * device.
157  *
158  *
159  * Driver Configuration:
160  *
161  * The following driver properties can be changed to control some aspects of the
162  * drivers operation:
163  * - strict-version: can be set to 0 to allow devices conforming to newer
164  *   versions or namespaces with EUI64 to be used
165  * - ignore-unknown-vendor-status: can be set to 1 to not handle any vendor
166  *   specific command status as a fatal error leading device faulting
167  * - admin-queue-len: the maximum length of the admin queue (16-4096)
168  * - io-queue-len: the maximum length of the I/O queues (16-65536)
169  * - async-event-limit: the maximum number of asynchronous event requests to be
170  *   posted by the driver
171  * - volatile-write-cache-enable: can be set to 0 to disable the volatile write
172  *   cache
173  * - min-phys-block-size: the minimum physical block size to report to blkdev,
174  *   which is among other things the basis for ZFS vdev ashift
175  *
176  *
177  * TODO:
178  * - figure out sane default for I/O queue depth reported to blkdev
179  * - polled I/O support to support kernel core dumping
180  * - FMA handling of media errors
181  * - support for devices supporting very large I/O requests using chained PRPs
182  * - support for configuring hardware parameters like interrupt coalescing
183  * - support for media formatting and hard partitioning into namespaces
184  * - support for big-endian systems
185  * - support for fast reboot
186  * - support for firmware updates
187  * - support for NVMe Subsystem Reset (1.1)
188  * - support for Scatter/Gather lists (1.1)
189  * - support for Reservations (1.1)
190  * - support for power management
191  */
192 
193 #include <sys/byteorder.h>
194 #ifdef _BIG_ENDIAN
195 #error nvme driver needs porting for big-endian platforms
196 #endif
197 
198 #include <sys/modctl.h>
199 #include <sys/conf.h>
200 #include <sys/devops.h>
201 #include <sys/ddi.h>
202 #include <sys/sunddi.h>
203 #include <sys/sunndi.h>
204 #include <sys/bitmap.h>
205 #include <sys/sysmacros.h>
206 #include <sys/param.h>
207 #include <sys/varargs.h>
208 #include <sys/cpuvar.h>
209 #include <sys/disp.h>
210 #include <sys/blkdev.h>
211 #include <sys/atomic.h>
212 #include <sys/archsystm.h>
213 #include <sys/sata/sata_hba.h>
214 #include <sys/stat.h>
215 #include <sys/policy.h>
216 
217 #include <sys/nvme.h>
218 
219 #ifdef __x86
220 #include <sys/x86_archext.h>
221 #endif
222 
223 #include "nvme_reg.h"
224 #include "nvme_var.h"
225 
226 
227 /* NVMe spec version supported */
228 static const int nvme_version_major = 1;
229 static const int nvme_version_minor = 2;
230 
231 /* tunable for admin command timeout in seconds, default is 1s */
232 int nvme_admin_cmd_timeout = 1;
233 
234 /* tunable for FORMAT NVM command timeout in seconds, default is 600s */
235 int nvme_format_cmd_timeout = 600;
236 
237 static int nvme_attach(dev_info_t *, ddi_attach_cmd_t);
238 static int nvme_detach(dev_info_t *, ddi_detach_cmd_t);
239 static int nvme_quiesce(dev_info_t *);
240 static int nvme_fm_errcb(dev_info_t *, ddi_fm_error_t *, const void *);
241 static int nvme_setup_interrupts(nvme_t *, int, int);
242 static void nvme_release_interrupts(nvme_t *);
243 static uint_t nvme_intr(caddr_t, caddr_t);
244 
245 static void nvme_shutdown(nvme_t *, int, boolean_t);
246 static boolean_t nvme_reset(nvme_t *, boolean_t);
247 static int nvme_init(nvme_t *);
248 static nvme_cmd_t *nvme_alloc_cmd(nvme_t *, int);
249 static void nvme_free_cmd(nvme_cmd_t *);
250 static nvme_cmd_t *nvme_create_nvm_cmd(nvme_namespace_t *, uint8_t,
251     bd_xfer_t *);
252 static int nvme_admin_cmd(nvme_cmd_t *, int);
253 static int nvme_submit_cmd(nvme_qpair_t *, nvme_cmd_t *);
254 static nvme_cmd_t *nvme_retrieve_cmd(nvme_t *, nvme_qpair_t *);
255 static boolean_t nvme_wait_cmd(nvme_cmd_t *, uint_t);
256 static void nvme_wakeup_cmd(void *);
257 static void nvme_async_event_task(void *);
258 
259 static int nvme_check_unknown_cmd_status(nvme_cmd_t *);
260 static int nvme_check_vendor_cmd_status(nvme_cmd_t *);
261 static int nvme_check_integrity_cmd_status(nvme_cmd_t *);
262 static int nvme_check_specific_cmd_status(nvme_cmd_t *);
263 static int nvme_check_generic_cmd_status(nvme_cmd_t *);
264 static inline int nvme_check_cmd_status(nvme_cmd_t *);
265 
266 static void nvme_abort_cmd(nvme_cmd_t *);
267 static int nvme_async_event(nvme_t *);
268 static int nvme_format_nvm(nvme_t *, uint32_t, uint8_t, boolean_t, uint8_t,
269     boolean_t, uint8_t);
270 static int nvme_get_logpage(nvme_t *, void **, size_t *, uint8_t, ...);
271 static void *nvme_identify(nvme_t *, uint32_t);
272 static boolean_t nvme_set_features(nvme_t *, uint32_t, uint8_t, uint32_t,
273     uint32_t *);
274 static boolean_t nvme_get_features(nvme_t *, uint32_t, uint8_t, uint32_t *,
275     void **, size_t *);
276 static boolean_t nvme_write_cache_set(nvme_t *, boolean_t);
277 static int nvme_set_nqueues(nvme_t *, uint16_t);
278 
279 static void nvme_free_dma(nvme_dma_t *);
280 static int nvme_zalloc_dma(nvme_t *, size_t, uint_t, ddi_dma_attr_t *,
281     nvme_dma_t **);
282 static int nvme_zalloc_queue_dma(nvme_t *, uint32_t, uint16_t, uint_t,
283     nvme_dma_t **);
284 static void nvme_free_qpair(nvme_qpair_t *);
285 static int nvme_alloc_qpair(nvme_t *, uint32_t, nvme_qpair_t **, int);
286 static int nvme_create_io_qpair(nvme_t *, nvme_qpair_t *, uint16_t);
287 
288 static inline void nvme_put64(nvme_t *, uintptr_t, uint64_t);
289 static inline void nvme_put32(nvme_t *, uintptr_t, uint32_t);
290 static inline uint64_t nvme_get64(nvme_t *, uintptr_t);
291 static inline uint32_t nvme_get32(nvme_t *, uintptr_t);
292 
293 static boolean_t nvme_check_regs_hdl(nvme_t *);
294 static boolean_t nvme_check_dma_hdl(nvme_dma_t *);
295 
296 static int nvme_fill_prp(nvme_cmd_t *, bd_xfer_t *);
297 
298 static void nvme_bd_xfer_done(void *);
299 static void nvme_bd_driveinfo(void *, bd_drive_t *);
300 static int nvme_bd_mediainfo(void *, bd_media_t *);
301 static int nvme_bd_cmd(nvme_namespace_t *, bd_xfer_t *, uint8_t);
302 static int nvme_bd_read(void *, bd_xfer_t *);
303 static int nvme_bd_write(void *, bd_xfer_t *);
304 static int nvme_bd_sync(void *, bd_xfer_t *);
305 static int nvme_bd_devid(void *, dev_info_t *, ddi_devid_t *);
306 
307 static int nvme_prp_dma_constructor(void *, void *, int);
308 static void nvme_prp_dma_destructor(void *, void *);
309 
310 static void nvme_prepare_devid(nvme_t *, uint32_t);
311 
312 static int nvme_open(dev_t *, int, int, cred_t *);
313 static int nvme_close(dev_t, int, int, cred_t *);
314 static int nvme_ioctl(dev_t, int, intptr_t, int, cred_t *, int *);
315 
316 #define	NVME_MINOR_INST_SHIFT	14
317 #define	NVME_MINOR(inst, nsid)	(((inst) << NVME_MINOR_INST_SHIFT) | (nsid))
318 #define	NVME_MINOR_INST(minor)	((minor) >> NVME_MINOR_INST_SHIFT)
319 #define	NVME_MINOR_NSID(minor)	((minor) & ((1 << NVME_MINOR_INST_SHIFT) - 1))
320 #define	NVME_MINOR_MAX		(NVME_MINOR(1, 0) - 2)
321 
322 static void *nvme_state;
323 static kmem_cache_t *nvme_cmd_cache;
324 
325 /*
326  * DMA attributes for queue DMA memory
327  *
328  * Queue DMA memory must be page aligned. The maximum length of a queue is
329  * 65536 entries, and an entry can be 64 bytes long.
330  */
331 static ddi_dma_attr_t nvme_queue_dma_attr = {
332 	.dma_attr_version	= DMA_ATTR_V0,
333 	.dma_attr_addr_lo	= 0,
334 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
335 	.dma_attr_count_max	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t) - 1,
336 	.dma_attr_align		= 0x1000,
337 	.dma_attr_burstsizes	= 0x7ff,
338 	.dma_attr_minxfer	= 0x1000,
339 	.dma_attr_maxxfer	= (UINT16_MAX + 1) * sizeof (nvme_sqe_t),
340 	.dma_attr_seg		= 0xffffffffffffffffULL,
341 	.dma_attr_sgllen	= 1,
342 	.dma_attr_granular	= 1,
343 	.dma_attr_flags		= 0,
344 };
345 
346 /*
347  * DMA attributes for transfers using Physical Region Page (PRP) entries
348  *
349  * A PRP entry describes one page of DMA memory using the page size specified
350  * in the controller configuration's memory page size register (CC.MPS). It uses
351  * a 64bit base address aligned to this page size. There is no limitation on
352  * chaining PRPs together for arbitrarily large DMA transfers.
353  */
354 static ddi_dma_attr_t nvme_prp_dma_attr = {
355 	.dma_attr_version	= DMA_ATTR_V0,
356 	.dma_attr_addr_lo	= 0,
357 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
358 	.dma_attr_count_max	= 0xfff,
359 	.dma_attr_align		= 0x1000,
360 	.dma_attr_burstsizes	= 0x7ff,
361 	.dma_attr_minxfer	= 0x1000,
362 	.dma_attr_maxxfer	= 0x1000,
363 	.dma_attr_seg		= 0xfff,
364 	.dma_attr_sgllen	= -1,
365 	.dma_attr_granular	= 1,
366 	.dma_attr_flags		= 0,
367 };
368 
369 /*
370  * DMA attributes for transfers using scatter/gather lists
371  *
372  * A SGL entry describes a chunk of DMA memory using a 64bit base address and a
373  * 32bit length field. SGL Segment and SGL Last Segment entries require the
374  * length to be a multiple of 16 bytes.
375  */
376 static ddi_dma_attr_t nvme_sgl_dma_attr = {
377 	.dma_attr_version	= DMA_ATTR_V0,
378 	.dma_attr_addr_lo	= 0,
379 	.dma_attr_addr_hi	= 0xffffffffffffffffULL,
380 	.dma_attr_count_max	= 0xffffffffUL,
381 	.dma_attr_align		= 1,
382 	.dma_attr_burstsizes	= 0x7ff,
383 	.dma_attr_minxfer	= 0x10,
384 	.dma_attr_maxxfer	= 0xfffffffffULL,
385 	.dma_attr_seg		= 0xffffffffffffffffULL,
386 	.dma_attr_sgllen	= -1,
387 	.dma_attr_granular	= 0x10,
388 	.dma_attr_flags		= 0
389 };
390 
391 static ddi_device_acc_attr_t nvme_reg_acc_attr = {
392 	.devacc_attr_version	= DDI_DEVICE_ATTR_V0,
393 	.devacc_attr_endian_flags = DDI_STRUCTURE_LE_ACC,
394 	.devacc_attr_dataorder	= DDI_STRICTORDER_ACC
395 };
396 
397 static struct cb_ops nvme_cb_ops = {
398 	.cb_open	= nvme_open,
399 	.cb_close	= nvme_close,
400 	.cb_strategy	= nodev,
401 	.cb_print	= nodev,
402 	.cb_dump	= nodev,
403 	.cb_read	= nodev,
404 	.cb_write	= nodev,
405 	.cb_ioctl	= nvme_ioctl,
406 	.cb_devmap	= nodev,
407 	.cb_mmap	= nodev,
408 	.cb_segmap	= nodev,
409 	.cb_chpoll	= nochpoll,
410 	.cb_prop_op	= ddi_prop_op,
411 	.cb_str		= 0,
412 	.cb_flag	= D_NEW | D_MP,
413 	.cb_rev		= CB_REV,
414 	.cb_aread	= nodev,
415 	.cb_awrite	= nodev
416 };
417 
418 static struct dev_ops nvme_dev_ops = {
419 	.devo_rev	= DEVO_REV,
420 	.devo_refcnt	= 0,
421 	.devo_getinfo	= ddi_no_info,
422 	.devo_identify	= nulldev,
423 	.devo_probe	= nulldev,
424 	.devo_attach	= nvme_attach,
425 	.devo_detach	= nvme_detach,
426 	.devo_reset	= nodev,
427 	.devo_cb_ops	= &nvme_cb_ops,
428 	.devo_bus_ops	= NULL,
429 	.devo_power	= NULL,
430 	.devo_quiesce	= nvme_quiesce,
431 };
432 
433 static struct modldrv nvme_modldrv = {
434 	.drv_modops	= &mod_driverops,
435 	.drv_linkinfo	= "NVMe v1.1b",
436 	.drv_dev_ops	= &nvme_dev_ops
437 };
438 
439 static struct modlinkage nvme_modlinkage = {
440 	.ml_rev		= MODREV_1,
441 	.ml_linkage	= { &nvme_modldrv, NULL }
442 };
443 
444 static bd_ops_t nvme_bd_ops = {
445 	.o_version	= BD_OPS_VERSION_0,
446 	.o_drive_info	= nvme_bd_driveinfo,
447 	.o_media_info	= nvme_bd_mediainfo,
448 	.o_devid_init	= nvme_bd_devid,
449 	.o_sync_cache	= nvme_bd_sync,
450 	.o_read		= nvme_bd_read,
451 	.o_write	= nvme_bd_write,
452 };
453 
454 int
455 _init(void)
456 {
457 	int error;
458 
459 	error = ddi_soft_state_init(&nvme_state, sizeof (nvme_t), 1);
460 	if (error != DDI_SUCCESS)
461 		return (error);
462 
463 	nvme_cmd_cache = kmem_cache_create("nvme_cmd_cache",
464 	    sizeof (nvme_cmd_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
465 
466 	bd_mod_init(&nvme_dev_ops);
467 
468 	error = mod_install(&nvme_modlinkage);
469 	if (error != DDI_SUCCESS) {
470 		ddi_soft_state_fini(&nvme_state);
471 		bd_mod_fini(&nvme_dev_ops);
472 	}
473 
474 	return (error);
475 }
476 
477 int
478 _fini(void)
479 {
480 	int error;
481 
482 	error = mod_remove(&nvme_modlinkage);
483 	if (error == DDI_SUCCESS) {
484 		ddi_soft_state_fini(&nvme_state);
485 		kmem_cache_destroy(nvme_cmd_cache);
486 		bd_mod_fini(&nvme_dev_ops);
487 	}
488 
489 	return (error);
490 }
491 
492 int
493 _info(struct modinfo *modinfop)
494 {
495 	return (mod_info(&nvme_modlinkage, modinfop));
496 }
497 
498 static inline void
499 nvme_put64(nvme_t *nvme, uintptr_t reg, uint64_t val)
500 {
501 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
502 
503 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
504 	ddi_put64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg), val);
505 }
506 
507 static inline void
508 nvme_put32(nvme_t *nvme, uintptr_t reg, uint32_t val)
509 {
510 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
511 
512 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
513 	ddi_put32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg), val);
514 }
515 
516 static inline uint64_t
517 nvme_get64(nvme_t *nvme, uintptr_t reg)
518 {
519 	uint64_t val;
520 
521 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x7) == 0);
522 
523 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
524 	val = ddi_get64(nvme->n_regh, (uint64_t *)(nvme->n_regs + reg));
525 
526 	return (val);
527 }
528 
529 static inline uint32_t
530 nvme_get32(nvme_t *nvme, uintptr_t reg)
531 {
532 	uint32_t val;
533 
534 	ASSERT(((uintptr_t)(nvme->n_regs + reg) & 0x3) == 0);
535 
536 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
537 	val = ddi_get32(nvme->n_regh, (uint32_t *)(nvme->n_regs + reg));
538 
539 	return (val);
540 }
541 
542 static boolean_t
543 nvme_check_regs_hdl(nvme_t *nvme)
544 {
545 	ddi_fm_error_t error;
546 
547 	ddi_fm_acc_err_get(nvme->n_regh, &error, DDI_FME_VERSION);
548 
549 	if (error.fme_status != DDI_FM_OK)
550 		return (B_TRUE);
551 
552 	return (B_FALSE);
553 }
554 
555 static boolean_t
556 nvme_check_dma_hdl(nvme_dma_t *dma)
557 {
558 	ddi_fm_error_t error;
559 
560 	if (dma == NULL)
561 		return (B_FALSE);
562 
563 	ddi_fm_dma_err_get(dma->nd_dmah, &error, DDI_FME_VERSION);
564 
565 	if (error.fme_status != DDI_FM_OK)
566 		return (B_TRUE);
567 
568 	return (B_FALSE);
569 }
570 
571 static void
572 nvme_free_dma_common(nvme_dma_t *dma)
573 {
574 	if (dma->nd_dmah != NULL)
575 		(void) ddi_dma_unbind_handle(dma->nd_dmah);
576 	if (dma->nd_acch != NULL)
577 		ddi_dma_mem_free(&dma->nd_acch);
578 	if (dma->nd_dmah != NULL)
579 		ddi_dma_free_handle(&dma->nd_dmah);
580 }
581 
582 static void
583 nvme_free_dma(nvme_dma_t *dma)
584 {
585 	nvme_free_dma_common(dma);
586 	kmem_free(dma, sizeof (*dma));
587 }
588 
589 /* ARGSUSED */
590 static void
591 nvme_prp_dma_destructor(void *buf, void *private)
592 {
593 	nvme_dma_t *dma = (nvme_dma_t *)buf;
594 
595 	nvme_free_dma_common(dma);
596 }
597 
598 static int
599 nvme_alloc_dma_common(nvme_t *nvme, nvme_dma_t *dma,
600     size_t len, uint_t flags, ddi_dma_attr_t *dma_attr)
601 {
602 	if (ddi_dma_alloc_handle(nvme->n_dip, dma_attr, DDI_DMA_SLEEP, NULL,
603 	    &dma->nd_dmah) != DDI_SUCCESS) {
604 		/*
605 		 * Due to DDI_DMA_SLEEP this can't be DDI_DMA_NORESOURCES, and
606 		 * the only other possible error is DDI_DMA_BADATTR which
607 		 * indicates a driver bug which should cause a panic.
608 		 */
609 		dev_err(nvme->n_dip, CE_PANIC,
610 		    "!failed to get DMA handle, check DMA attributes");
611 		return (DDI_FAILURE);
612 	}
613 
614 	/*
615 	 * ddi_dma_mem_alloc() can only fail when DDI_DMA_NOSLEEP is specified
616 	 * or the flags are conflicting, which isn't the case here.
617 	 */
618 	(void) ddi_dma_mem_alloc(dma->nd_dmah, len, &nvme->n_reg_acc_attr,
619 	    DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, &dma->nd_memp,
620 	    &dma->nd_len, &dma->nd_acch);
621 
622 	if (ddi_dma_addr_bind_handle(dma->nd_dmah, NULL, dma->nd_memp,
623 	    dma->nd_len, flags | DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL,
624 	    &dma->nd_cookie, &dma->nd_ncookie) != DDI_DMA_MAPPED) {
625 		dev_err(nvme->n_dip, CE_WARN,
626 		    "!failed to bind DMA memory");
627 		atomic_inc_32(&nvme->n_dma_bind_err);
628 		nvme_free_dma_common(dma);
629 		return (DDI_FAILURE);
630 	}
631 
632 	return (DDI_SUCCESS);
633 }
634 
635 static int
636 nvme_zalloc_dma(nvme_t *nvme, size_t len, uint_t flags,
637     ddi_dma_attr_t *dma_attr, nvme_dma_t **ret)
638 {
639 	nvme_dma_t *dma = kmem_zalloc(sizeof (nvme_dma_t), KM_SLEEP);
640 
641 	if (nvme_alloc_dma_common(nvme, dma, len, flags, dma_attr) !=
642 	    DDI_SUCCESS) {
643 		*ret = NULL;
644 		kmem_free(dma, sizeof (nvme_dma_t));
645 		return (DDI_FAILURE);
646 	}
647 
648 	bzero(dma->nd_memp, dma->nd_len);
649 
650 	*ret = dma;
651 	return (DDI_SUCCESS);
652 }
653 
654 /* ARGSUSED */
655 static int
656 nvme_prp_dma_constructor(void *buf, void *private, int flags)
657 {
658 	nvme_dma_t *dma = (nvme_dma_t *)buf;
659 	nvme_t *nvme = (nvme_t *)private;
660 
661 	dma->nd_dmah = NULL;
662 	dma->nd_acch = NULL;
663 
664 	if (nvme_alloc_dma_common(nvme, dma, nvme->n_pagesize,
665 	    DDI_DMA_READ, &nvme->n_prp_dma_attr) != DDI_SUCCESS) {
666 		return (-1);
667 	}
668 
669 	ASSERT(dma->nd_ncookie == 1);
670 
671 	dma->nd_cached = B_TRUE;
672 
673 	return (0);
674 }
675 
676 static int
677 nvme_zalloc_queue_dma(nvme_t *nvme, uint32_t nentry, uint16_t qe_len,
678     uint_t flags, nvme_dma_t **dma)
679 {
680 	uint32_t len = nentry * qe_len;
681 	ddi_dma_attr_t q_dma_attr = nvme->n_queue_dma_attr;
682 
683 	len = roundup(len, nvme->n_pagesize);
684 
685 	q_dma_attr.dma_attr_minxfer = len;
686 
687 	if (nvme_zalloc_dma(nvme, len, flags, &q_dma_attr, dma)
688 	    != DDI_SUCCESS) {
689 		dev_err(nvme->n_dip, CE_WARN,
690 		    "!failed to get DMA memory for queue");
691 		goto fail;
692 	}
693 
694 	if ((*dma)->nd_ncookie != 1) {
695 		dev_err(nvme->n_dip, CE_WARN,
696 		    "!got too many cookies for queue DMA");
697 		goto fail;
698 	}
699 
700 	return (DDI_SUCCESS);
701 
702 fail:
703 	if (*dma) {
704 		nvme_free_dma(*dma);
705 		*dma = NULL;
706 	}
707 
708 	return (DDI_FAILURE);
709 }
710 
711 static void
712 nvme_free_qpair(nvme_qpair_t *qp)
713 {
714 	int i;
715 
716 	mutex_destroy(&qp->nq_mutex);
717 
718 	if (qp->nq_sqdma != NULL)
719 		nvme_free_dma(qp->nq_sqdma);
720 	if (qp->nq_cqdma != NULL)
721 		nvme_free_dma(qp->nq_cqdma);
722 
723 	if (qp->nq_active_cmds > 0)
724 		for (i = 0; i != qp->nq_nentry; i++)
725 			if (qp->nq_cmd[i] != NULL)
726 				nvme_free_cmd(qp->nq_cmd[i]);
727 
728 	if (qp->nq_cmd != NULL)
729 		kmem_free(qp->nq_cmd, sizeof (nvme_cmd_t *) * qp->nq_nentry);
730 
731 	kmem_free(qp, sizeof (nvme_qpair_t));
732 }
733 
734 static int
735 nvme_alloc_qpair(nvme_t *nvme, uint32_t nentry, nvme_qpair_t **nqp,
736     int idx)
737 {
738 	nvme_qpair_t *qp = kmem_zalloc(sizeof (*qp), KM_SLEEP);
739 
740 	mutex_init(&qp->nq_mutex, NULL, MUTEX_DRIVER,
741 	    DDI_INTR_PRI(nvme->n_intr_pri));
742 
743 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_sqe_t),
744 	    DDI_DMA_WRITE, &qp->nq_sqdma) != DDI_SUCCESS)
745 		goto fail;
746 
747 	if (nvme_zalloc_queue_dma(nvme, nentry, sizeof (nvme_cqe_t),
748 	    DDI_DMA_READ, &qp->nq_cqdma) != DDI_SUCCESS)
749 		goto fail;
750 
751 	qp->nq_sq = (nvme_sqe_t *)qp->nq_sqdma->nd_memp;
752 	qp->nq_cq = (nvme_cqe_t *)qp->nq_cqdma->nd_memp;
753 	qp->nq_nentry = nentry;
754 
755 	qp->nq_sqtdbl = NVME_REG_SQTDBL(nvme, idx);
756 	qp->nq_cqhdbl = NVME_REG_CQHDBL(nvme, idx);
757 
758 	qp->nq_cmd = kmem_zalloc(sizeof (nvme_cmd_t *) * nentry, KM_SLEEP);
759 	qp->nq_next_cmd = 0;
760 
761 	*nqp = qp;
762 	return (DDI_SUCCESS);
763 
764 fail:
765 	nvme_free_qpair(qp);
766 	*nqp = NULL;
767 
768 	return (DDI_FAILURE);
769 }
770 
771 static nvme_cmd_t *
772 nvme_alloc_cmd(nvme_t *nvme, int kmflag)
773 {
774 	nvme_cmd_t *cmd = kmem_cache_alloc(nvme_cmd_cache, kmflag);
775 
776 	if (cmd == NULL)
777 		return (cmd);
778 
779 	bzero(cmd, sizeof (nvme_cmd_t));
780 
781 	cmd->nc_nvme = nvme;
782 
783 	mutex_init(&cmd->nc_mutex, NULL, MUTEX_DRIVER,
784 	    DDI_INTR_PRI(nvme->n_intr_pri));
785 	cv_init(&cmd->nc_cv, NULL, CV_DRIVER, NULL);
786 
787 	return (cmd);
788 }
789 
790 static void
791 nvme_free_cmd(nvme_cmd_t *cmd)
792 {
793 	if (cmd->nc_dma) {
794 		if (cmd->nc_dma->nd_cached)
795 			kmem_cache_free(cmd->nc_nvme->n_prp_cache,
796 			    cmd->nc_dma);
797 		else
798 			nvme_free_dma(cmd->nc_dma);
799 		cmd->nc_dma = NULL;
800 	}
801 
802 	cv_destroy(&cmd->nc_cv);
803 	mutex_destroy(&cmd->nc_mutex);
804 
805 	kmem_cache_free(nvme_cmd_cache, cmd);
806 }
807 
808 static int
809 nvme_submit_cmd(nvme_qpair_t *qp, nvme_cmd_t *cmd)
810 {
811 	nvme_reg_sqtdbl_t tail = { 0 };
812 
813 	mutex_enter(&qp->nq_mutex);
814 
815 	if (qp->nq_active_cmds == qp->nq_nentry) {
816 		mutex_exit(&qp->nq_mutex);
817 		return (DDI_FAILURE);
818 	}
819 
820 	cmd->nc_completed = B_FALSE;
821 
822 	/*
823 	 * Try to insert the cmd into the active cmd array at the nq_next_cmd
824 	 * slot. If the slot is already occupied advance to the next slot and
825 	 * try again. This can happen for long running commands like async event
826 	 * requests.
827 	 */
828 	while (qp->nq_cmd[qp->nq_next_cmd] != NULL)
829 		qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
830 	qp->nq_cmd[qp->nq_next_cmd] = cmd;
831 
832 	qp->nq_active_cmds++;
833 
834 	cmd->nc_sqe.sqe_cid = qp->nq_next_cmd;
835 	bcopy(&cmd->nc_sqe, &qp->nq_sq[qp->nq_sqtail], sizeof (nvme_sqe_t));
836 	(void) ddi_dma_sync(qp->nq_sqdma->nd_dmah,
837 	    sizeof (nvme_sqe_t) * qp->nq_sqtail,
838 	    sizeof (nvme_sqe_t), DDI_DMA_SYNC_FORDEV);
839 	qp->nq_next_cmd = (qp->nq_next_cmd + 1) % qp->nq_nentry;
840 
841 	tail.b.sqtdbl_sqt = qp->nq_sqtail = (qp->nq_sqtail + 1) % qp->nq_nentry;
842 	nvme_put32(cmd->nc_nvme, qp->nq_sqtdbl, tail.r);
843 
844 	mutex_exit(&qp->nq_mutex);
845 	return (DDI_SUCCESS);
846 }
847 
848 static nvme_cmd_t *
849 nvme_retrieve_cmd(nvme_t *nvme, nvme_qpair_t *qp)
850 {
851 	nvme_reg_cqhdbl_t head = { 0 };
852 
853 	nvme_cqe_t *cqe;
854 	nvme_cmd_t *cmd;
855 
856 	(void) ddi_dma_sync(qp->nq_cqdma->nd_dmah, 0,
857 	    sizeof (nvme_cqe_t) * qp->nq_nentry, DDI_DMA_SYNC_FORKERNEL);
858 
859 	cqe = &qp->nq_cq[qp->nq_cqhead];
860 
861 	/* Check phase tag of CQE. Hardware inverts it for new entries. */
862 	if (cqe->cqe_sf.sf_p == qp->nq_phase)
863 		return (NULL);
864 
865 	ASSERT(nvme->n_ioq[cqe->cqe_sqid] == qp);
866 	ASSERT(cqe->cqe_cid < qp->nq_nentry);
867 
868 	mutex_enter(&qp->nq_mutex);
869 	cmd = qp->nq_cmd[cqe->cqe_cid];
870 	qp->nq_cmd[cqe->cqe_cid] = NULL;
871 	qp->nq_active_cmds--;
872 	mutex_exit(&qp->nq_mutex);
873 
874 	ASSERT(cmd != NULL);
875 	ASSERT(cmd->nc_nvme == nvme);
876 	ASSERT(cmd->nc_sqid == cqe->cqe_sqid);
877 	ASSERT(cmd->nc_sqe.sqe_cid == cqe->cqe_cid);
878 	bcopy(cqe, &cmd->nc_cqe, sizeof (nvme_cqe_t));
879 
880 	qp->nq_sqhead = cqe->cqe_sqhd;
881 
882 	head.b.cqhdbl_cqh = qp->nq_cqhead = (qp->nq_cqhead + 1) % qp->nq_nentry;
883 
884 	/* Toggle phase on wrap-around. */
885 	if (qp->nq_cqhead == 0)
886 		qp->nq_phase = qp->nq_phase ? 0 : 1;
887 
888 	nvme_put32(cmd->nc_nvme, qp->nq_cqhdbl, head.r);
889 
890 	return (cmd);
891 }
892 
893 static int
894 nvme_check_unknown_cmd_status(nvme_cmd_t *cmd)
895 {
896 	nvme_cqe_t *cqe = &cmd->nc_cqe;
897 
898 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
899 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
900 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
901 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
902 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
903 
904 	if (cmd->nc_xfer != NULL)
905 		bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
906 
907 	if (cmd->nc_nvme->n_strict_version) {
908 		cmd->nc_nvme->n_dead = B_TRUE;
909 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
910 	}
911 
912 	return (EIO);
913 }
914 
915 static int
916 nvme_check_vendor_cmd_status(nvme_cmd_t *cmd)
917 {
918 	nvme_cqe_t *cqe = &cmd->nc_cqe;
919 
920 	dev_err(cmd->nc_nvme->n_dip, CE_WARN,
921 	    "!unknown command status received: opc = %x, sqid = %d, cid = %d, "
922 	    "sc = %x, sct = %x, dnr = %d, m = %d", cmd->nc_sqe.sqe_opc,
923 	    cqe->cqe_sqid, cqe->cqe_cid, cqe->cqe_sf.sf_sc, cqe->cqe_sf.sf_sct,
924 	    cqe->cqe_sf.sf_dnr, cqe->cqe_sf.sf_m);
925 	if (!cmd->nc_nvme->n_ignore_unknown_vendor_status) {
926 		cmd->nc_nvme->n_dead = B_TRUE;
927 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
928 	}
929 
930 	return (EIO);
931 }
932 
933 static int
934 nvme_check_integrity_cmd_status(nvme_cmd_t *cmd)
935 {
936 	nvme_cqe_t *cqe = &cmd->nc_cqe;
937 
938 	switch (cqe->cqe_sf.sf_sc) {
939 	case NVME_CQE_SC_INT_NVM_WRITE:
940 		/* write fail */
941 		/* TODO: post ereport */
942 		if (cmd->nc_xfer != NULL)
943 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
944 		return (EIO);
945 
946 	case NVME_CQE_SC_INT_NVM_READ:
947 		/* read fail */
948 		/* TODO: post ereport */
949 		if (cmd->nc_xfer != NULL)
950 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
951 		return (EIO);
952 
953 	default:
954 		return (nvme_check_unknown_cmd_status(cmd));
955 	}
956 }
957 
958 static int
959 nvme_check_generic_cmd_status(nvme_cmd_t *cmd)
960 {
961 	nvme_cqe_t *cqe = &cmd->nc_cqe;
962 
963 	switch (cqe->cqe_sf.sf_sc) {
964 	case NVME_CQE_SC_GEN_SUCCESS:
965 		return (0);
966 
967 	/*
968 	 * Errors indicating a bug in the driver should cause a panic.
969 	 */
970 	case NVME_CQE_SC_GEN_INV_OPC:
971 		/* Invalid Command Opcode */
972 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
973 		    "invalid opcode in cmd %p", (void *)cmd);
974 		return (0);
975 
976 	case NVME_CQE_SC_GEN_INV_FLD:
977 		/* Invalid Field in Command */
978 		if (!cmd->nc_dontpanic)
979 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
980 			    "programming error: invalid field in cmd %p",
981 			    (void *)cmd);
982 		return (EIO);
983 
984 	case NVME_CQE_SC_GEN_ID_CNFL:
985 		/* Command ID Conflict */
986 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
987 		    "cmd ID conflict in cmd %p", (void *)cmd);
988 		return (0);
989 
990 	case NVME_CQE_SC_GEN_INV_NS:
991 		/* Invalid Namespace or Format */
992 		if (!cmd->nc_dontpanic)
993 			dev_err(cmd->nc_nvme->n_dip, CE_PANIC,
994 			    "programming error: " "invalid NS/format in cmd %p",
995 			    (void *)cmd);
996 		return (EINVAL);
997 
998 	case NVME_CQE_SC_GEN_NVM_LBA_RANGE:
999 		/* LBA Out Of Range */
1000 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1001 		    "LBA out of range in cmd %p", (void *)cmd);
1002 		return (0);
1003 
1004 	/*
1005 	 * Non-fatal errors, handle gracefully.
1006 	 */
1007 	case NVME_CQE_SC_GEN_DATA_XFR_ERR:
1008 		/* Data Transfer Error (DMA) */
1009 		/* TODO: post ereport */
1010 		atomic_inc_32(&cmd->nc_nvme->n_data_xfr_err);
1011 		if (cmd->nc_xfer != NULL)
1012 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
1013 		return (EIO);
1014 
1015 	case NVME_CQE_SC_GEN_INTERNAL_ERR:
1016 		/*
1017 		 * Internal Error. The spec (v1.0, section 4.5.1.2) says
1018 		 * detailed error information is returned as async event,
1019 		 * so we pretty much ignore the error here and handle it
1020 		 * in the async event handler.
1021 		 */
1022 		atomic_inc_32(&cmd->nc_nvme->n_internal_err);
1023 		if (cmd->nc_xfer != NULL)
1024 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
1025 		return (EIO);
1026 
1027 	case NVME_CQE_SC_GEN_ABORT_REQUEST:
1028 		/*
1029 		 * Command Abort Requested. This normally happens only when a
1030 		 * command times out.
1031 		 */
1032 		/* TODO: post ereport or change blkdev to handle this? */
1033 		atomic_inc_32(&cmd->nc_nvme->n_abort_rq_err);
1034 		return (ECANCELED);
1035 
1036 	case NVME_CQE_SC_GEN_ABORT_PWRLOSS:
1037 		/* Command Aborted due to Power Loss Notification */
1038 		ddi_fm_service_impact(cmd->nc_nvme->n_dip, DDI_SERVICE_LOST);
1039 		cmd->nc_nvme->n_dead = B_TRUE;
1040 		return (EIO);
1041 
1042 	case NVME_CQE_SC_GEN_ABORT_SQ_DEL:
1043 		/* Command Aborted due to SQ Deletion */
1044 		atomic_inc_32(&cmd->nc_nvme->n_abort_sq_del);
1045 		return (EIO);
1046 
1047 	case NVME_CQE_SC_GEN_NVM_CAP_EXC:
1048 		/* Capacity Exceeded */
1049 		atomic_inc_32(&cmd->nc_nvme->n_nvm_cap_exc);
1050 		if (cmd->nc_xfer != NULL)
1051 			bd_error(cmd->nc_xfer, BD_ERR_MEDIA);
1052 		return (EIO);
1053 
1054 	case NVME_CQE_SC_GEN_NVM_NS_NOTRDY:
1055 		/* Namespace Not Ready */
1056 		atomic_inc_32(&cmd->nc_nvme->n_nvm_ns_notrdy);
1057 		if (cmd->nc_xfer != NULL)
1058 			bd_error(cmd->nc_xfer, BD_ERR_NTRDY);
1059 		return (EIO);
1060 
1061 	default:
1062 		return (nvme_check_unknown_cmd_status(cmd));
1063 	}
1064 }
1065 
1066 static int
1067 nvme_check_specific_cmd_status(nvme_cmd_t *cmd)
1068 {
1069 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1070 
1071 	switch (cqe->cqe_sf.sf_sc) {
1072 	case NVME_CQE_SC_SPC_INV_CQ:
1073 		/* Completion Queue Invalid */
1074 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE);
1075 		atomic_inc_32(&cmd->nc_nvme->n_inv_cq_err);
1076 		return (EINVAL);
1077 
1078 	case NVME_CQE_SC_SPC_INV_QID:
1079 		/* Invalid Queue Identifier */
1080 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
1081 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_SQUEUE ||
1082 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE ||
1083 		    cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
1084 		atomic_inc_32(&cmd->nc_nvme->n_inv_qid_err);
1085 		return (EINVAL);
1086 
1087 	case NVME_CQE_SC_SPC_MAX_QSZ_EXC:
1088 		/* Max Queue Size Exceeded */
1089 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_SQUEUE ||
1090 		    cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
1091 		atomic_inc_32(&cmd->nc_nvme->n_max_qsz_exc);
1092 		return (EINVAL);
1093 
1094 	case NVME_CQE_SC_SPC_ABRT_CMD_EXC:
1095 		/* Abort Command Limit Exceeded */
1096 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT);
1097 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1098 		    "abort command limit exceeded in cmd %p", (void *)cmd);
1099 		return (0);
1100 
1101 	case NVME_CQE_SC_SPC_ASYNC_EVREQ_EXC:
1102 		/* Async Event Request Limit Exceeded */
1103 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_ASYNC_EVENT);
1104 		dev_err(cmd->nc_nvme->n_dip, CE_PANIC, "programming error: "
1105 		    "async event request limit exceeded in cmd %p",
1106 		    (void *)cmd);
1107 		return (0);
1108 
1109 	case NVME_CQE_SC_SPC_INV_INT_VECT:
1110 		/* Invalid Interrupt Vector */
1111 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_CREATE_CQUEUE);
1112 		atomic_inc_32(&cmd->nc_nvme->n_inv_int_vect);
1113 		return (EINVAL);
1114 
1115 	case NVME_CQE_SC_SPC_INV_LOG_PAGE:
1116 		/* Invalid Log Page */
1117 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_GET_LOG_PAGE);
1118 		atomic_inc_32(&cmd->nc_nvme->n_inv_log_page);
1119 		return (EINVAL);
1120 
1121 	case NVME_CQE_SC_SPC_INV_FORMAT:
1122 		/* Invalid Format */
1123 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_FORMAT);
1124 		atomic_inc_32(&cmd->nc_nvme->n_inv_format);
1125 		if (cmd->nc_xfer != NULL)
1126 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1127 		return (EINVAL);
1128 
1129 	case NVME_CQE_SC_SPC_INV_Q_DEL:
1130 		/* Invalid Queue Deletion */
1131 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_DELETE_CQUEUE);
1132 		atomic_inc_32(&cmd->nc_nvme->n_inv_q_del);
1133 		return (EINVAL);
1134 
1135 	case NVME_CQE_SC_SPC_NVM_CNFL_ATTR:
1136 		/* Conflicting Attributes */
1137 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_DSET_MGMT ||
1138 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
1139 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1140 		atomic_inc_32(&cmd->nc_nvme->n_cnfl_attr);
1141 		if (cmd->nc_xfer != NULL)
1142 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1143 		return (EINVAL);
1144 
1145 	case NVME_CQE_SC_SPC_NVM_INV_PROT:
1146 		/* Invalid Protection Information */
1147 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_COMPARE ||
1148 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_READ ||
1149 		    cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1150 		atomic_inc_32(&cmd->nc_nvme->n_inv_prot);
1151 		if (cmd->nc_xfer != NULL)
1152 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1153 		return (EINVAL);
1154 
1155 	case NVME_CQE_SC_SPC_NVM_READONLY:
1156 		/* Write to Read Only Range */
1157 		ASSERT(cmd->nc_sqe.sqe_opc == NVME_OPC_NVM_WRITE);
1158 		atomic_inc_32(&cmd->nc_nvme->n_readonly);
1159 		if (cmd->nc_xfer != NULL)
1160 			bd_error(cmd->nc_xfer, BD_ERR_ILLRQ);
1161 		return (EROFS);
1162 
1163 	default:
1164 		return (nvme_check_unknown_cmd_status(cmd));
1165 	}
1166 }
1167 
1168 static inline int
1169 nvme_check_cmd_status(nvme_cmd_t *cmd)
1170 {
1171 	nvme_cqe_t *cqe = &cmd->nc_cqe;
1172 
1173 	/* take a shortcut if everything is alright */
1174 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1175 	    cqe->cqe_sf.sf_sc == NVME_CQE_SC_GEN_SUCCESS)
1176 		return (0);
1177 
1178 	if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC)
1179 		return (nvme_check_generic_cmd_status(cmd));
1180 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_SPECIFIC)
1181 		return (nvme_check_specific_cmd_status(cmd));
1182 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_INTEGRITY)
1183 		return (nvme_check_integrity_cmd_status(cmd));
1184 	else if (cqe->cqe_sf.sf_sct == NVME_CQE_SCT_VENDOR)
1185 		return (nvme_check_vendor_cmd_status(cmd));
1186 
1187 	return (nvme_check_unknown_cmd_status(cmd));
1188 }
1189 
1190 /*
1191  * nvme_abort_cmd_cb -- replaces nc_callback of aborted commands
1192  *
1193  * This functions takes care of cleaning up aborted commands. The command
1194  * status is checked to catch any fatal errors.
1195  */
1196 static void
1197 nvme_abort_cmd_cb(void *arg)
1198 {
1199 	nvme_cmd_t *cmd = arg;
1200 
1201 	/*
1202 	 * Grab the command mutex. Once we have it we hold the last reference
1203 	 * to the command and can safely free it.
1204 	 */
1205 	mutex_enter(&cmd->nc_mutex);
1206 	(void) nvme_check_cmd_status(cmd);
1207 	mutex_exit(&cmd->nc_mutex);
1208 
1209 	nvme_free_cmd(cmd);
1210 }
1211 
1212 static void
1213 nvme_abort_cmd(nvme_cmd_t *abort_cmd)
1214 {
1215 	nvme_t *nvme = abort_cmd->nc_nvme;
1216 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1217 	nvme_abort_cmd_t ac = { 0 };
1218 
1219 	sema_p(&nvme->n_abort_sema);
1220 
1221 	ac.b.ac_cid = abort_cmd->nc_sqe.sqe_cid;
1222 	ac.b.ac_sqid = abort_cmd->nc_sqid;
1223 
1224 	/*
1225 	 * Drop the mutex of the aborted command. From this point on
1226 	 * we must assume that the abort callback has freed the command.
1227 	 */
1228 	mutex_exit(&abort_cmd->nc_mutex);
1229 
1230 	cmd->nc_sqid = 0;
1231 	cmd->nc_sqe.sqe_opc = NVME_OPC_ABORT;
1232 	cmd->nc_callback = nvme_wakeup_cmd;
1233 	cmd->nc_sqe.sqe_cdw10 = ac.r;
1234 
1235 	/*
1236 	 * Send the ABORT to the hardware. The ABORT command will return _after_
1237 	 * the aborted command has completed (aborted or otherwise).
1238 	 */
1239 	if (nvme_admin_cmd(cmd, nvme_admin_cmd_timeout) != DDI_SUCCESS) {
1240 		sema_v(&nvme->n_abort_sema);
1241 		dev_err(nvme->n_dip, CE_WARN,
1242 		    "!nvme_admin_cmd failed for ABORT");
1243 		atomic_inc_32(&nvme->n_abort_failed);
1244 		return;
1245 	}
1246 	sema_v(&nvme->n_abort_sema);
1247 
1248 	if (nvme_check_cmd_status(cmd)) {
1249 		dev_err(nvme->n_dip, CE_WARN,
1250 		    "!ABORT failed with sct = %x, sc = %x",
1251 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1252 		atomic_inc_32(&nvme->n_abort_failed);
1253 	} else {
1254 		atomic_inc_32(&nvme->n_cmd_aborted);
1255 	}
1256 
1257 	nvme_free_cmd(cmd);
1258 }
1259 
1260 /*
1261  * nvme_wait_cmd -- wait for command completion or timeout
1262  *
1263  * Returns B_TRUE if the command completed normally.
1264  *
1265  * Returns B_FALSE if the command timed out and an abort was attempted. The
1266  * command mutex will be dropped and the command must be considered freed. The
1267  * freeing of the command is normally done by the abort command callback.
1268  *
1269  * In case of a serious error or a timeout of the abort command the hardware
1270  * will be declared dead and FMA will be notified.
1271  */
1272 static boolean_t
1273 nvme_wait_cmd(nvme_cmd_t *cmd, uint_t sec)
1274 {
1275 	clock_t timeout = ddi_get_lbolt() + drv_usectohz(sec * MICROSEC);
1276 	nvme_t *nvme = cmd->nc_nvme;
1277 	nvme_reg_csts_t csts;
1278 
1279 	ASSERT(mutex_owned(&cmd->nc_mutex));
1280 
1281 	while (!cmd->nc_completed) {
1282 		if (cv_timedwait(&cmd->nc_cv, &cmd->nc_mutex, timeout) == -1)
1283 			break;
1284 	}
1285 
1286 	if (cmd->nc_completed)
1287 		return (B_TRUE);
1288 
1289 	/*
1290 	 * The command timed out. Change the callback to the cleanup function.
1291 	 */
1292 	cmd->nc_callback = nvme_abort_cmd_cb;
1293 
1294 	/*
1295 	 * Check controller for fatal status, any errors associated with the
1296 	 * register or DMA handle, or for a double timeout (abort command timed
1297 	 * out). If necessary log a warning and call FMA.
1298 	 */
1299 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
1300 	dev_err(nvme->n_dip, CE_WARN, "!command timeout, "
1301 	    "OPC = %x, CFS = %d", cmd->nc_sqe.sqe_opc, csts.b.csts_cfs);
1302 	atomic_inc_32(&nvme->n_cmd_timeout);
1303 
1304 	if (csts.b.csts_cfs ||
1305 	    nvme_check_regs_hdl(nvme) ||
1306 	    nvme_check_dma_hdl(cmd->nc_dma) ||
1307 	    cmd->nc_sqe.sqe_opc == NVME_OPC_ABORT) {
1308 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1309 		nvme->n_dead = B_TRUE;
1310 		mutex_exit(&cmd->nc_mutex);
1311 	} else {
1312 		/*
1313 		 * Try to abort the command. The command mutex is released by
1314 		 * nvme_abort_cmd().
1315 		 * If the abort succeeds it will have freed the aborted command.
1316 		 * If the abort fails for other reasons we must assume that the
1317 		 * command may complete at any time, and the callback will free
1318 		 * it for us.
1319 		 */
1320 		nvme_abort_cmd(cmd);
1321 	}
1322 
1323 	return (B_FALSE);
1324 }
1325 
1326 static void
1327 nvme_wakeup_cmd(void *arg)
1328 {
1329 	nvme_cmd_t *cmd = arg;
1330 
1331 	mutex_enter(&cmd->nc_mutex);
1332 	/*
1333 	 * There is a slight chance that this command completed shortly after
1334 	 * the timeout was hit in nvme_wait_cmd() but before the callback was
1335 	 * changed. Catch that case here and clean up accordingly.
1336 	 */
1337 	if (cmd->nc_callback == nvme_abort_cmd_cb) {
1338 		mutex_exit(&cmd->nc_mutex);
1339 		nvme_abort_cmd_cb(cmd);
1340 		return;
1341 	}
1342 
1343 	cmd->nc_completed = B_TRUE;
1344 	cv_signal(&cmd->nc_cv);
1345 	mutex_exit(&cmd->nc_mutex);
1346 }
1347 
1348 static void
1349 nvme_async_event_task(void *arg)
1350 {
1351 	nvme_cmd_t *cmd = arg;
1352 	nvme_t *nvme = cmd->nc_nvme;
1353 	nvme_error_log_entry_t *error_log = NULL;
1354 	nvme_health_log_t *health_log = NULL;
1355 	size_t logsize = 0;
1356 	nvme_async_event_t event;
1357 	int ret;
1358 
1359 	/*
1360 	 * Check for errors associated with the async request itself. The only
1361 	 * command-specific error is "async event limit exceeded", which
1362 	 * indicates a programming error in the driver and causes a panic in
1363 	 * nvme_check_cmd_status().
1364 	 *
1365 	 * Other possible errors are various scenarios where the async request
1366 	 * was aborted, or internal errors in the device. Internal errors are
1367 	 * reported to FMA, the command aborts need no special handling here.
1368 	 */
1369 	if (nvme_check_cmd_status(cmd)) {
1370 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1371 		    "!async event request returned failure, sct = %x, "
1372 		    "sc = %x, dnr = %d, m = %d", cmd->nc_cqe.cqe_sf.sf_sct,
1373 		    cmd->nc_cqe.cqe_sf.sf_sc, cmd->nc_cqe.cqe_sf.sf_dnr,
1374 		    cmd->nc_cqe.cqe_sf.sf_m);
1375 
1376 		if (cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1377 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INTERNAL_ERR) {
1378 			cmd->nc_nvme->n_dead = B_TRUE;
1379 			ddi_fm_service_impact(cmd->nc_nvme->n_dip,
1380 			    DDI_SERVICE_LOST);
1381 		}
1382 		nvme_free_cmd(cmd);
1383 		return;
1384 	}
1385 
1386 
1387 	event.r = cmd->nc_cqe.cqe_dw0;
1388 
1389 	/* Clear CQE and re-submit the async request. */
1390 	bzero(&cmd->nc_cqe, sizeof (nvme_cqe_t));
1391 	ret = nvme_submit_cmd(nvme->n_adminq, cmd);
1392 
1393 	if (ret != DDI_SUCCESS) {
1394 		dev_err(nvme->n_dip, CE_WARN,
1395 		    "!failed to resubmit async event request");
1396 		atomic_inc_32(&nvme->n_async_resubmit_failed);
1397 		nvme_free_cmd(cmd);
1398 	}
1399 
1400 	switch (event.b.ae_type) {
1401 	case NVME_ASYNC_TYPE_ERROR:
1402 		if (event.b.ae_logpage == NVME_LOGPAGE_ERROR) {
1403 			(void) nvme_get_logpage(nvme, (void **)&error_log,
1404 			    &logsize, event.b.ae_logpage);
1405 		} else {
1406 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1407 			    "async event reply: %d", event.b.ae_logpage);
1408 			atomic_inc_32(&nvme->n_wrong_logpage);
1409 		}
1410 
1411 		switch (event.b.ae_info) {
1412 		case NVME_ASYNC_ERROR_INV_SQ:
1413 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1414 			    "invalid submission queue");
1415 			return;
1416 
1417 		case NVME_ASYNC_ERROR_INV_DBL:
1418 			dev_err(nvme->n_dip, CE_PANIC, "programming error: "
1419 			    "invalid doorbell write value");
1420 			return;
1421 
1422 		case NVME_ASYNC_ERROR_DIAGFAIL:
1423 			dev_err(nvme->n_dip, CE_WARN, "!diagnostic failure");
1424 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1425 			nvme->n_dead = B_TRUE;
1426 			atomic_inc_32(&nvme->n_diagfail_event);
1427 			break;
1428 
1429 		case NVME_ASYNC_ERROR_PERSISTENT:
1430 			dev_err(nvme->n_dip, CE_WARN, "!persistent internal "
1431 			    "device error");
1432 			ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
1433 			nvme->n_dead = B_TRUE;
1434 			atomic_inc_32(&nvme->n_persistent_event);
1435 			break;
1436 
1437 		case NVME_ASYNC_ERROR_TRANSIENT:
1438 			dev_err(nvme->n_dip, CE_WARN, "!transient internal "
1439 			    "device error");
1440 			/* TODO: send ereport */
1441 			atomic_inc_32(&nvme->n_transient_event);
1442 			break;
1443 
1444 		case NVME_ASYNC_ERROR_FW_LOAD:
1445 			dev_err(nvme->n_dip, CE_WARN,
1446 			    "!firmware image load error");
1447 			atomic_inc_32(&nvme->n_fw_load_event);
1448 			break;
1449 		}
1450 		break;
1451 
1452 	case NVME_ASYNC_TYPE_HEALTH:
1453 		if (event.b.ae_logpage == NVME_LOGPAGE_HEALTH) {
1454 			(void) nvme_get_logpage(nvme, (void **)&health_log,
1455 			    &logsize, event.b.ae_logpage, -1);
1456 		} else {
1457 			dev_err(nvme->n_dip, CE_WARN, "!wrong logpage in "
1458 			    "async event reply: %d", event.b.ae_logpage);
1459 			atomic_inc_32(&nvme->n_wrong_logpage);
1460 		}
1461 
1462 		switch (event.b.ae_info) {
1463 		case NVME_ASYNC_HEALTH_RELIABILITY:
1464 			dev_err(nvme->n_dip, CE_WARN,
1465 			    "!device reliability compromised");
1466 			/* TODO: send ereport */
1467 			atomic_inc_32(&nvme->n_reliability_event);
1468 			break;
1469 
1470 		case NVME_ASYNC_HEALTH_TEMPERATURE:
1471 			dev_err(nvme->n_dip, CE_WARN,
1472 			    "!temperature above threshold");
1473 			/* TODO: send ereport */
1474 			atomic_inc_32(&nvme->n_temperature_event);
1475 			break;
1476 
1477 		case NVME_ASYNC_HEALTH_SPARE:
1478 			dev_err(nvme->n_dip, CE_WARN,
1479 			    "!spare space below threshold");
1480 			/* TODO: send ereport */
1481 			atomic_inc_32(&nvme->n_spare_event);
1482 			break;
1483 		}
1484 		break;
1485 
1486 	case NVME_ASYNC_TYPE_VENDOR:
1487 		dev_err(nvme->n_dip, CE_WARN, "!vendor specific async event "
1488 		    "received, info = %x, logpage = %x", event.b.ae_info,
1489 		    event.b.ae_logpage);
1490 		atomic_inc_32(&nvme->n_vendor_event);
1491 		break;
1492 
1493 	default:
1494 		dev_err(nvme->n_dip, CE_WARN, "!unknown async event received, "
1495 		    "type = %x, info = %x, logpage = %x", event.b.ae_type,
1496 		    event.b.ae_info, event.b.ae_logpage);
1497 		atomic_inc_32(&nvme->n_unknown_event);
1498 		break;
1499 	}
1500 
1501 	if (error_log)
1502 		kmem_free(error_log, logsize);
1503 
1504 	if (health_log)
1505 		kmem_free(health_log, logsize);
1506 }
1507 
1508 static int
1509 nvme_admin_cmd(nvme_cmd_t *cmd, int sec)
1510 {
1511 	int ret;
1512 
1513 	mutex_enter(&cmd->nc_mutex);
1514 	ret = nvme_submit_cmd(cmd->nc_nvme->n_adminq, cmd);
1515 
1516 	if (ret != DDI_SUCCESS) {
1517 		mutex_exit(&cmd->nc_mutex);
1518 		dev_err(cmd->nc_nvme->n_dip, CE_WARN,
1519 		    "!nvme_submit_cmd failed");
1520 		atomic_inc_32(&cmd->nc_nvme->n_admin_queue_full);
1521 		nvme_free_cmd(cmd);
1522 		return (DDI_FAILURE);
1523 	}
1524 
1525 	if (nvme_wait_cmd(cmd, sec) == B_FALSE) {
1526 		/*
1527 		 * The command timed out. An abort command was posted that
1528 		 * will take care of the cleanup.
1529 		 */
1530 		return (DDI_FAILURE);
1531 	}
1532 	mutex_exit(&cmd->nc_mutex);
1533 
1534 	return (DDI_SUCCESS);
1535 }
1536 
1537 static int
1538 nvme_async_event(nvme_t *nvme)
1539 {
1540 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1541 	int ret;
1542 
1543 	cmd->nc_sqid = 0;
1544 	cmd->nc_sqe.sqe_opc = NVME_OPC_ASYNC_EVENT;
1545 	cmd->nc_callback = nvme_async_event_task;
1546 
1547 	ret = nvme_submit_cmd(nvme->n_adminq, cmd);
1548 
1549 	if (ret != DDI_SUCCESS) {
1550 		dev_err(nvme->n_dip, CE_WARN,
1551 		    "!nvme_submit_cmd failed for ASYNCHRONOUS EVENT");
1552 		nvme_free_cmd(cmd);
1553 		return (DDI_FAILURE);
1554 	}
1555 
1556 	return (DDI_SUCCESS);
1557 }
1558 
1559 static int
1560 nvme_format_nvm(nvme_t *nvme, uint32_t nsid, uint8_t lbaf, boolean_t ms,
1561     uint8_t pi, boolean_t pil, uint8_t ses)
1562 {
1563 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1564 	nvme_format_nvm_t format_nvm = { 0 };
1565 	int ret;
1566 
1567 	format_nvm.b.fm_lbaf = lbaf & 0xf;
1568 	format_nvm.b.fm_ms = ms ? 1 : 0;
1569 	format_nvm.b.fm_pi = pi & 0x7;
1570 	format_nvm.b.fm_pil = pil ? 1 : 0;
1571 	format_nvm.b.fm_ses = ses & 0x7;
1572 
1573 	cmd->nc_sqid = 0;
1574 	cmd->nc_callback = nvme_wakeup_cmd;
1575 	cmd->nc_sqe.sqe_nsid = nsid;
1576 	cmd->nc_sqe.sqe_opc = NVME_OPC_NVM_FORMAT;
1577 	cmd->nc_sqe.sqe_cdw10 = format_nvm.r;
1578 
1579 	/*
1580 	 * Some devices like Samsung SM951 don't allow formatting of all
1581 	 * namespaces in one command. Handle that gracefully.
1582 	 */
1583 	if (nsid == (uint32_t)-1)
1584 		cmd->nc_dontpanic = B_TRUE;
1585 
1586 	if ((ret = nvme_admin_cmd(cmd, nvme_format_cmd_timeout))
1587 	    != DDI_SUCCESS) {
1588 		dev_err(nvme->n_dip, CE_WARN,
1589 		    "!nvme_admin_cmd failed for FORMAT NVM");
1590 		return (EIO);
1591 	}
1592 
1593 	if ((ret = nvme_check_cmd_status(cmd)) != 0) {
1594 		dev_err(nvme->n_dip, CE_WARN,
1595 		    "!FORMAT failed with sct = %x, sc = %x",
1596 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1597 	}
1598 
1599 	nvme_free_cmd(cmd);
1600 	return (ret);
1601 }
1602 
1603 static int
1604 nvme_get_logpage(nvme_t *nvme, void **buf, size_t *bufsize, uint8_t logpage,
1605     ...)
1606 {
1607 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1608 	nvme_getlogpage_t getlogpage = { 0 };
1609 	va_list ap;
1610 	int ret = DDI_FAILURE;
1611 
1612 	va_start(ap, logpage);
1613 
1614 	cmd->nc_sqid = 0;
1615 	cmd->nc_callback = nvme_wakeup_cmd;
1616 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_LOG_PAGE;
1617 
1618 	getlogpage.b.lp_lid = logpage;
1619 
1620 	switch (logpage) {
1621 	case NVME_LOGPAGE_ERROR:
1622 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1623 		/*
1624 		 * The GET LOG PAGE command can use at most 2 pages to return
1625 		 * data, PRP lists are not supported.
1626 		 */
1627 		*bufsize = MIN(2 * nvme->n_pagesize,
1628 		    nvme->n_error_log_len * sizeof (nvme_error_log_entry_t));
1629 		break;
1630 
1631 	case NVME_LOGPAGE_HEALTH:
1632 		cmd->nc_sqe.sqe_nsid = va_arg(ap, uint32_t);
1633 		*bufsize = sizeof (nvme_health_log_t);
1634 		break;
1635 
1636 	case NVME_LOGPAGE_FWSLOT:
1637 		cmd->nc_sqe.sqe_nsid = (uint32_t)-1;
1638 		*bufsize = sizeof (nvme_fwslot_log_t);
1639 		break;
1640 
1641 	default:
1642 		dev_err(nvme->n_dip, CE_WARN, "!unknown log page requested: %d",
1643 		    logpage);
1644 		atomic_inc_32(&nvme->n_unknown_logpage);
1645 		goto fail;
1646 	}
1647 
1648 	va_end(ap);
1649 
1650 	getlogpage.b.lp_numd = *bufsize / sizeof (uint32_t) - 1;
1651 
1652 	cmd->nc_sqe.sqe_cdw10 = getlogpage.r;
1653 
1654 	if (nvme_zalloc_dma(nvme, getlogpage.b.lp_numd * sizeof (uint32_t),
1655 	    DDI_DMA_READ, &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1656 		dev_err(nvme->n_dip, CE_WARN,
1657 		    "!nvme_zalloc_dma failed for GET LOG PAGE");
1658 		goto fail;
1659 	}
1660 
1661 	if (cmd->nc_dma->nd_ncookie > 2) {
1662 		dev_err(nvme->n_dip, CE_WARN,
1663 		    "!too many DMA cookies for GET LOG PAGE");
1664 		atomic_inc_32(&nvme->n_too_many_cookies);
1665 		goto fail;
1666 	}
1667 
1668 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1669 	if (cmd->nc_dma->nd_ncookie > 1) {
1670 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1671 		    &cmd->nc_dma->nd_cookie);
1672 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1673 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1674 	}
1675 
1676 	if (nvme_admin_cmd(cmd, nvme_admin_cmd_timeout) != DDI_SUCCESS) {
1677 		dev_err(nvme->n_dip, CE_WARN,
1678 		    "!nvme_admin_cmd failed for GET LOG PAGE");
1679 		return (ret);
1680 	}
1681 
1682 	if (nvme_check_cmd_status(cmd)) {
1683 		dev_err(nvme->n_dip, CE_WARN,
1684 		    "!GET LOG PAGE failed with sct = %x, sc = %x",
1685 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1686 		goto fail;
1687 	}
1688 
1689 	*buf = kmem_alloc(*bufsize, KM_SLEEP);
1690 	bcopy(cmd->nc_dma->nd_memp, *buf, *bufsize);
1691 
1692 	ret = DDI_SUCCESS;
1693 
1694 fail:
1695 	nvme_free_cmd(cmd);
1696 
1697 	return (ret);
1698 }
1699 
1700 static void *
1701 nvme_identify(nvme_t *nvme, uint32_t nsid)
1702 {
1703 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1704 	void *buf = NULL;
1705 
1706 	cmd->nc_sqid = 0;
1707 	cmd->nc_callback = nvme_wakeup_cmd;
1708 	cmd->nc_sqe.sqe_opc = NVME_OPC_IDENTIFY;
1709 	cmd->nc_sqe.sqe_nsid = nsid;
1710 	cmd->nc_sqe.sqe_cdw10 = nsid ? NVME_IDENTIFY_NSID : NVME_IDENTIFY_CTRL;
1711 
1712 	if (nvme_zalloc_dma(nvme, NVME_IDENTIFY_BUFSIZE, DDI_DMA_READ,
1713 	    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1714 		dev_err(nvme->n_dip, CE_WARN,
1715 		    "!nvme_zalloc_dma failed for IDENTIFY");
1716 		goto fail;
1717 	}
1718 
1719 	if (cmd->nc_dma->nd_ncookie > 2) {
1720 		dev_err(nvme->n_dip, CE_WARN,
1721 		    "!too many DMA cookies for IDENTIFY");
1722 		atomic_inc_32(&nvme->n_too_many_cookies);
1723 		goto fail;
1724 	}
1725 
1726 	cmd->nc_sqe.sqe_dptr.d_prp[0] = cmd->nc_dma->nd_cookie.dmac_laddress;
1727 	if (cmd->nc_dma->nd_ncookie > 1) {
1728 		ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1729 		    &cmd->nc_dma->nd_cookie);
1730 		cmd->nc_sqe.sqe_dptr.d_prp[1] =
1731 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1732 	}
1733 
1734 	if (nvme_admin_cmd(cmd, nvme_admin_cmd_timeout) != DDI_SUCCESS) {
1735 		dev_err(nvme->n_dip, CE_WARN,
1736 		    "!nvme_admin_cmd failed for IDENTIFY");
1737 		return (NULL);
1738 	}
1739 
1740 	if (nvme_check_cmd_status(cmd)) {
1741 		dev_err(nvme->n_dip, CE_WARN,
1742 		    "!IDENTIFY failed with sct = %x, sc = %x",
1743 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1744 		goto fail;
1745 	}
1746 
1747 	buf = kmem_alloc(NVME_IDENTIFY_BUFSIZE, KM_SLEEP);
1748 	bcopy(cmd->nc_dma->nd_memp, buf, NVME_IDENTIFY_BUFSIZE);
1749 
1750 fail:
1751 	nvme_free_cmd(cmd);
1752 
1753 	return (buf);
1754 }
1755 
1756 static boolean_t
1757 nvme_set_features(nvme_t *nvme, uint32_t nsid, uint8_t feature, uint32_t val,
1758     uint32_t *res)
1759 {
1760 	_NOTE(ARGUNUSED(nsid));
1761 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1762 	boolean_t ret = B_FALSE;
1763 
1764 	ASSERT(res != NULL);
1765 
1766 	cmd->nc_sqid = 0;
1767 	cmd->nc_callback = nvme_wakeup_cmd;
1768 	cmd->nc_sqe.sqe_opc = NVME_OPC_SET_FEATURES;
1769 	cmd->nc_sqe.sqe_cdw10 = feature;
1770 	cmd->nc_sqe.sqe_cdw11 = val;
1771 
1772 	switch (feature) {
1773 	case NVME_FEAT_WRITE_CACHE:
1774 		if (!nvme->n_write_cache_present)
1775 			goto fail;
1776 		break;
1777 
1778 	case NVME_FEAT_NQUEUES:
1779 		break;
1780 
1781 	default:
1782 		goto fail;
1783 	}
1784 
1785 	if (nvme_admin_cmd(cmd, nvme_admin_cmd_timeout) != DDI_SUCCESS) {
1786 		dev_err(nvme->n_dip, CE_WARN,
1787 		    "!nvme_admin_cmd failed for SET FEATURES");
1788 		return (ret);
1789 	}
1790 
1791 	if (nvme_check_cmd_status(cmd)) {
1792 		dev_err(nvme->n_dip, CE_WARN,
1793 		    "!SET FEATURES %d failed with sct = %x, sc = %x",
1794 		    feature, cmd->nc_cqe.cqe_sf.sf_sct,
1795 		    cmd->nc_cqe.cqe_sf.sf_sc);
1796 		goto fail;
1797 	}
1798 
1799 	*res = cmd->nc_cqe.cqe_dw0;
1800 	ret = B_TRUE;
1801 
1802 fail:
1803 	nvme_free_cmd(cmd);
1804 	return (ret);
1805 }
1806 
1807 static boolean_t
1808 nvme_get_features(nvme_t *nvme, uint32_t nsid, uint8_t feature, uint32_t *res,
1809     void **buf, size_t *bufsize)
1810 {
1811 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1812 	boolean_t ret = B_FALSE;
1813 
1814 	ASSERT(res != NULL);
1815 
1816 	if (bufsize != NULL)
1817 		*bufsize = 0;
1818 
1819 	cmd->nc_sqid = 0;
1820 	cmd->nc_callback = nvme_wakeup_cmd;
1821 	cmd->nc_sqe.sqe_opc = NVME_OPC_GET_FEATURES;
1822 	cmd->nc_sqe.sqe_cdw10 = feature;
1823 	cmd->nc_sqe.sqe_cdw11 = *res;
1824 
1825 	switch (feature) {
1826 	case NVME_FEAT_ARBITRATION:
1827 	case NVME_FEAT_POWER_MGMT:
1828 	case NVME_FEAT_TEMPERATURE:
1829 	case NVME_FEAT_ERROR:
1830 	case NVME_FEAT_NQUEUES:
1831 	case NVME_FEAT_INTR_COAL:
1832 	case NVME_FEAT_INTR_VECT:
1833 	case NVME_FEAT_WRITE_ATOM:
1834 	case NVME_FEAT_ASYNC_EVENT:
1835 	case NVME_FEAT_PROGRESS:
1836 		break;
1837 
1838 	case NVME_FEAT_WRITE_CACHE:
1839 		if (!nvme->n_write_cache_present)
1840 			goto fail;
1841 		break;
1842 
1843 	case NVME_FEAT_LBA_RANGE:
1844 		if (!nvme->n_lba_range_supported)
1845 			goto fail;
1846 
1847 		/*
1848 		 * The LBA Range Type feature is optional. There doesn't seem
1849 		 * be a method of detecting whether it is supported other than
1850 		 * using it. This will cause a "invalid field in command" error,
1851 		 * which is normally considered a programming error and causes
1852 		 * panic in nvme_check_generic_cmd_status().
1853 		 */
1854 		cmd->nc_dontpanic = B_TRUE;
1855 		cmd->nc_sqe.sqe_nsid = nsid;
1856 		ASSERT(bufsize != NULL);
1857 		*bufsize = NVME_LBA_RANGE_BUFSIZE;
1858 
1859 		break;
1860 
1861 	case NVME_FEAT_AUTO_PST:
1862 		if (!nvme->n_auto_pst_supported)
1863 			goto fail;
1864 
1865 		ASSERT(bufsize != NULL);
1866 		*bufsize = NVME_AUTO_PST_BUFSIZE;
1867 		break;
1868 
1869 	default:
1870 		goto fail;
1871 	}
1872 
1873 	if (bufsize != NULL && *bufsize != 0) {
1874 		if (nvme_zalloc_dma(nvme, *bufsize, DDI_DMA_READ,
1875 		    &nvme->n_prp_dma_attr, &cmd->nc_dma) != DDI_SUCCESS) {
1876 			dev_err(nvme->n_dip, CE_WARN,
1877 			    "!nvme_zalloc_dma failed for GET FEATURES");
1878 			goto fail;
1879 		}
1880 
1881 		if (cmd->nc_dma->nd_ncookie > 2) {
1882 			dev_err(nvme->n_dip, CE_WARN,
1883 			    "!too many DMA cookies for GET FEATURES");
1884 			atomic_inc_32(&nvme->n_too_many_cookies);
1885 			goto fail;
1886 		}
1887 
1888 		cmd->nc_sqe.sqe_dptr.d_prp[0] =
1889 		    cmd->nc_dma->nd_cookie.dmac_laddress;
1890 		if (cmd->nc_dma->nd_ncookie > 1) {
1891 			ddi_dma_nextcookie(cmd->nc_dma->nd_dmah,
1892 			    &cmd->nc_dma->nd_cookie);
1893 			cmd->nc_sqe.sqe_dptr.d_prp[1] =
1894 			    cmd->nc_dma->nd_cookie.dmac_laddress;
1895 		}
1896 	}
1897 
1898 	if (nvme_admin_cmd(cmd, nvme_admin_cmd_timeout) != DDI_SUCCESS) {
1899 		dev_err(nvme->n_dip, CE_WARN,
1900 		    "!nvme_admin_cmd failed for GET FEATURES");
1901 		return (ret);
1902 	}
1903 
1904 	if (nvme_check_cmd_status(cmd)) {
1905 		if (feature == NVME_FEAT_LBA_RANGE &&
1906 		    cmd->nc_cqe.cqe_sf.sf_sct == NVME_CQE_SCT_GENERIC &&
1907 		    cmd->nc_cqe.cqe_sf.sf_sc == NVME_CQE_SC_GEN_INV_FLD)
1908 			nvme->n_lba_range_supported = B_FALSE;
1909 		else
1910 			dev_err(nvme->n_dip, CE_WARN,
1911 			    "!GET FEATURES %d failed with sct = %x, sc = %x",
1912 			    feature, cmd->nc_cqe.cqe_sf.sf_sct,
1913 			    cmd->nc_cqe.cqe_sf.sf_sc);
1914 		goto fail;
1915 	}
1916 
1917 	if (bufsize != NULL && *bufsize != 0) {
1918 		ASSERT(buf != NULL);
1919 		*buf = kmem_alloc(*bufsize, KM_SLEEP);
1920 		bcopy(cmd->nc_dma->nd_memp, *buf, *bufsize);
1921 	}
1922 
1923 	*res = cmd->nc_cqe.cqe_dw0;
1924 	ret = B_TRUE;
1925 
1926 fail:
1927 	nvme_free_cmd(cmd);
1928 	return (ret);
1929 }
1930 
1931 static boolean_t
1932 nvme_write_cache_set(nvme_t *nvme, boolean_t enable)
1933 {
1934 	nvme_write_cache_t nwc = { 0 };
1935 
1936 	if (enable)
1937 		nwc.b.wc_wce = 1;
1938 
1939 	if (!nvme_set_features(nvme, 0, NVME_FEAT_WRITE_CACHE, nwc.r, &nwc.r))
1940 		return (B_FALSE);
1941 
1942 	return (B_TRUE);
1943 }
1944 
1945 static int
1946 nvme_set_nqueues(nvme_t *nvme, uint16_t nqueues)
1947 {
1948 	nvme_nqueues_t nq = { 0 };
1949 
1950 	nq.b.nq_nsq = nq.b.nq_ncq = nqueues - 1;
1951 
1952 	if (!nvme_set_features(nvme, 0, NVME_FEAT_NQUEUES, nq.r, &nq.r)) {
1953 		return (0);
1954 	}
1955 
1956 	/*
1957 	 * Always use the same number of submission and completion queues, and
1958 	 * never use more than the requested number of queues.
1959 	 */
1960 	return (MIN(nqueues, MIN(nq.b.nq_nsq, nq.b.nq_ncq) + 1));
1961 }
1962 
1963 static int
1964 nvme_create_io_qpair(nvme_t *nvme, nvme_qpair_t *qp, uint16_t idx)
1965 {
1966 	nvme_cmd_t *cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
1967 	nvme_create_queue_dw10_t dw10 = { 0 };
1968 	nvme_create_cq_dw11_t c_dw11 = { 0 };
1969 	nvme_create_sq_dw11_t s_dw11 = { 0 };
1970 
1971 	dw10.b.q_qid = idx;
1972 	dw10.b.q_qsize = qp->nq_nentry - 1;
1973 
1974 	c_dw11.b.cq_pc = 1;
1975 	c_dw11.b.cq_ien = 1;
1976 	c_dw11.b.cq_iv = idx % nvme->n_intr_cnt;
1977 
1978 	cmd->nc_sqid = 0;
1979 	cmd->nc_callback = nvme_wakeup_cmd;
1980 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_CQUEUE;
1981 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
1982 	cmd->nc_sqe.sqe_cdw11 = c_dw11.r;
1983 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_cqdma->nd_cookie.dmac_laddress;
1984 
1985 	if (nvme_admin_cmd(cmd, nvme_admin_cmd_timeout) != DDI_SUCCESS) {
1986 		dev_err(nvme->n_dip, CE_WARN,
1987 		    "!nvme_admin_cmd failed for CREATE CQUEUE");
1988 		return (DDI_FAILURE);
1989 	}
1990 
1991 	if (nvme_check_cmd_status(cmd)) {
1992 		dev_err(nvme->n_dip, CE_WARN,
1993 		    "!CREATE CQUEUE failed with sct = %x, sc = %x",
1994 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
1995 		nvme_free_cmd(cmd);
1996 		return (DDI_FAILURE);
1997 	}
1998 
1999 	nvme_free_cmd(cmd);
2000 
2001 	s_dw11.b.sq_pc = 1;
2002 	s_dw11.b.sq_cqid = idx;
2003 
2004 	cmd = nvme_alloc_cmd(nvme, KM_SLEEP);
2005 	cmd->nc_sqid = 0;
2006 	cmd->nc_callback = nvme_wakeup_cmd;
2007 	cmd->nc_sqe.sqe_opc = NVME_OPC_CREATE_SQUEUE;
2008 	cmd->nc_sqe.sqe_cdw10 = dw10.r;
2009 	cmd->nc_sqe.sqe_cdw11 = s_dw11.r;
2010 	cmd->nc_sqe.sqe_dptr.d_prp[0] = qp->nq_sqdma->nd_cookie.dmac_laddress;
2011 
2012 	if (nvme_admin_cmd(cmd, nvme_admin_cmd_timeout) != DDI_SUCCESS) {
2013 		dev_err(nvme->n_dip, CE_WARN,
2014 		    "!nvme_admin_cmd failed for CREATE SQUEUE");
2015 		return (DDI_FAILURE);
2016 	}
2017 
2018 	if (nvme_check_cmd_status(cmd)) {
2019 		dev_err(nvme->n_dip, CE_WARN,
2020 		    "!CREATE SQUEUE failed with sct = %x, sc = %x",
2021 		    cmd->nc_cqe.cqe_sf.sf_sct, cmd->nc_cqe.cqe_sf.sf_sc);
2022 		nvme_free_cmd(cmd);
2023 		return (DDI_FAILURE);
2024 	}
2025 
2026 	nvme_free_cmd(cmd);
2027 
2028 	return (DDI_SUCCESS);
2029 }
2030 
2031 static boolean_t
2032 nvme_reset(nvme_t *nvme, boolean_t quiesce)
2033 {
2034 	nvme_reg_csts_t csts;
2035 	int i;
2036 
2037 	nvme_put32(nvme, NVME_REG_CC, 0);
2038 
2039 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2040 	if (csts.b.csts_rdy == 1) {
2041 		nvme_put32(nvme, NVME_REG_CC, 0);
2042 		for (i = 0; i != nvme->n_timeout * 10; i++) {
2043 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2044 			if (csts.b.csts_rdy == 0)
2045 				break;
2046 
2047 			if (quiesce)
2048 				drv_usecwait(50000);
2049 			else
2050 				delay(drv_usectohz(50000));
2051 		}
2052 	}
2053 
2054 	nvme_put32(nvme, NVME_REG_AQA, 0);
2055 	nvme_put32(nvme, NVME_REG_ASQ, 0);
2056 	nvme_put32(nvme, NVME_REG_ACQ, 0);
2057 
2058 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2059 	return (csts.b.csts_rdy == 0 ? B_TRUE : B_FALSE);
2060 }
2061 
2062 static void
2063 nvme_shutdown(nvme_t *nvme, int mode, boolean_t quiesce)
2064 {
2065 	nvme_reg_cc_t cc;
2066 	nvme_reg_csts_t csts;
2067 	int i;
2068 
2069 	ASSERT(mode == NVME_CC_SHN_NORMAL || mode == NVME_CC_SHN_ABRUPT);
2070 
2071 	cc.r = nvme_get32(nvme, NVME_REG_CC);
2072 	cc.b.cc_shn = mode & 0x3;
2073 	nvme_put32(nvme, NVME_REG_CC, cc.r);
2074 
2075 	for (i = 0; i != 10; i++) {
2076 		csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2077 		if (csts.b.csts_shst == NVME_CSTS_SHN_COMPLETE)
2078 			break;
2079 
2080 		if (quiesce)
2081 			drv_usecwait(100000);
2082 		else
2083 			delay(drv_usectohz(100000));
2084 	}
2085 }
2086 
2087 
2088 static void
2089 nvme_prepare_devid(nvme_t *nvme, uint32_t nsid)
2090 {
2091 	/*
2092 	 * Section 7.7 of the spec describes how to get a unique ID for
2093 	 * the controller: the vendor ID, the model name and the serial
2094 	 * number shall be unique when combined.
2095 	 *
2096 	 * If a namespace has no EUI64 we use the above and add the hex
2097 	 * namespace ID to get a unique ID for the namespace.
2098 	 */
2099 	char model[sizeof (nvme->n_idctl->id_model) + 1];
2100 	char serial[sizeof (nvme->n_idctl->id_serial) + 1];
2101 
2102 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
2103 	bcopy(nvme->n_idctl->id_serial, serial,
2104 	    sizeof (nvme->n_idctl->id_serial));
2105 
2106 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
2107 	serial[sizeof (nvme->n_idctl->id_serial)] = '\0';
2108 
2109 	nvme->n_ns[nsid - 1].ns_devid = kmem_asprintf("%4X-%s-%s-%X",
2110 	    nvme->n_idctl->id_vid, model, serial, nsid);
2111 }
2112 
2113 static int
2114 nvme_init_ns(nvme_t *nvme, int nsid)
2115 {
2116 	nvme_namespace_t *ns = &nvme->n_ns[nsid - 1];
2117 	nvme_identify_nsid_t *idns;
2118 	int last_rp;
2119 
2120 	ns->ns_nvme = nvme;
2121 	idns = nvme_identify(nvme, nsid);
2122 
2123 	if (idns == NULL) {
2124 		dev_err(nvme->n_dip, CE_WARN,
2125 		    "!failed to identify namespace %d", nsid);
2126 		return (DDI_FAILURE);
2127 	}
2128 
2129 	ns->ns_idns = idns;
2130 	ns->ns_id = nsid;
2131 	ns->ns_block_count = idns->id_nsize;
2132 	ns->ns_block_size =
2133 	    1 << idns->id_lbaf[idns->id_flbas.lba_format].lbaf_lbads;
2134 	ns->ns_best_block_size = ns->ns_block_size;
2135 
2136 	/*
2137 	 * Get the EUI64 if present. Use it for devid and device node names.
2138 	 */
2139 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 1))
2140 		bcopy(idns->id_eui64, ns->ns_eui64, sizeof (ns->ns_eui64));
2141 
2142 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
2143 	if (*(uint64_t *)ns->ns_eui64 != 0) {
2144 		uint8_t *eui64 = ns->ns_eui64;
2145 
2146 		(void) snprintf(ns->ns_name, sizeof (ns->ns_name),
2147 		    "%02x%02x%02x%02x%02x%02x%02x%02x",
2148 		    eui64[0], eui64[1], eui64[2], eui64[3],
2149 		    eui64[4], eui64[5], eui64[6], eui64[7]);
2150 	} else {
2151 		(void) snprintf(ns->ns_name, sizeof (ns->ns_name), "%d",
2152 		    ns->ns_id);
2153 
2154 		nvme_prepare_devid(nvme, ns->ns_id);
2155 	}
2156 
2157 	/*
2158 	 * Find the LBA format with no metadata and the best relative
2159 	 * performance. A value of 3 means "degraded", 0 is best.
2160 	 */
2161 	last_rp = 3;
2162 	for (int j = 0; j <= idns->id_nlbaf; j++) {
2163 		if (idns->id_lbaf[j].lbaf_lbads == 0)
2164 			break;
2165 		if (idns->id_lbaf[j].lbaf_ms != 0)
2166 			continue;
2167 		if (idns->id_lbaf[j].lbaf_rp >= last_rp)
2168 			continue;
2169 		last_rp = idns->id_lbaf[j].lbaf_rp;
2170 		ns->ns_best_block_size =
2171 		    1 << idns->id_lbaf[j].lbaf_lbads;
2172 	}
2173 
2174 	if (ns->ns_best_block_size < nvme->n_min_block_size)
2175 		ns->ns_best_block_size = nvme->n_min_block_size;
2176 
2177 	/*
2178 	 * We currently don't support namespaces that use either:
2179 	 * - thin provisioning
2180 	 * - protection information
2181 	 * - illegal block size (< 512)
2182 	 */
2183 	if (idns->id_nsfeat.f_thin ||
2184 	    idns->id_dps.dp_pinfo) {
2185 		dev_err(nvme->n_dip, CE_WARN,
2186 		    "!ignoring namespace %d, unsupported features: "
2187 		    "thin = %d, pinfo = %d", nsid,
2188 		    idns->id_nsfeat.f_thin, idns->id_dps.dp_pinfo);
2189 		ns->ns_ignore = B_TRUE;
2190 	} else if (ns->ns_block_size < 512) {
2191 		dev_err(nvme->n_dip, CE_WARN,
2192 		    "!ignoring namespace %d, unsupported block size %"PRIu64,
2193 		    nsid, (uint64_t)ns->ns_block_size);
2194 		ns->ns_ignore = B_TRUE;
2195 	} else {
2196 		ns->ns_ignore = B_FALSE;
2197 	}
2198 
2199 	return (DDI_SUCCESS);
2200 }
2201 
2202 static int
2203 nvme_init(nvme_t *nvme)
2204 {
2205 	nvme_reg_cc_t cc = { 0 };
2206 	nvme_reg_aqa_t aqa = { 0 };
2207 	nvme_reg_asq_t asq = { 0 };
2208 	nvme_reg_acq_t acq = { 0 };
2209 	nvme_reg_cap_t cap;
2210 	nvme_reg_vs_t vs;
2211 	nvme_reg_csts_t csts;
2212 	int i = 0;
2213 	int nqueues;
2214 	char model[sizeof (nvme->n_idctl->id_model) + 1];
2215 	char *vendor, *product;
2216 
2217 	/* Check controller version */
2218 	vs.r = nvme_get32(nvme, NVME_REG_VS);
2219 	nvme->n_version.v_major = vs.b.vs_mjr;
2220 	nvme->n_version.v_minor = vs.b.vs_mnr;
2221 	dev_err(nvme->n_dip, CE_CONT, "?NVMe spec version %d.%d",
2222 	    nvme->n_version.v_major, nvme->n_version.v_minor);
2223 
2224 	if (NVME_VERSION_HIGHER(&nvme->n_version,
2225 	    nvme_version_major, nvme_version_minor)) {
2226 		dev_err(nvme->n_dip, CE_WARN, "!no support for version > %d.%d",
2227 		    nvme_version_major, nvme_version_minor);
2228 		if (nvme->n_strict_version)
2229 			goto fail;
2230 	}
2231 
2232 	/* retrieve controller configuration */
2233 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
2234 
2235 	if ((cap.b.cap_css & NVME_CAP_CSS_NVM) == 0) {
2236 		dev_err(nvme->n_dip, CE_WARN,
2237 		    "!NVM command set not supported by hardware");
2238 		goto fail;
2239 	}
2240 
2241 	nvme->n_nssr_supported = cap.b.cap_nssrs;
2242 	nvme->n_doorbell_stride = 4 << cap.b.cap_dstrd;
2243 	nvme->n_timeout = cap.b.cap_to;
2244 	nvme->n_arbitration_mechanisms = cap.b.cap_ams;
2245 	nvme->n_cont_queues_reqd = cap.b.cap_cqr;
2246 	nvme->n_max_queue_entries = cap.b.cap_mqes + 1;
2247 
2248 	/*
2249 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to specify
2250 	 * the base page size of 4k (1<<12), so add 12 here to get the real
2251 	 * page size value.
2252 	 */
2253 	nvme->n_pageshift = MIN(MAX(cap.b.cap_mpsmin + 12, PAGESHIFT),
2254 	    cap.b.cap_mpsmax + 12);
2255 	nvme->n_pagesize = 1UL << (nvme->n_pageshift);
2256 
2257 	/*
2258 	 * Set up Queue DMA to transfer at least 1 page-aligned page at a time.
2259 	 */
2260 	nvme->n_queue_dma_attr.dma_attr_align = nvme->n_pagesize;
2261 	nvme->n_queue_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
2262 
2263 	/*
2264 	 * Set up PRP DMA to transfer 1 page-aligned page at a time.
2265 	 * Maxxfer may be increased after we identified the controller limits.
2266 	 */
2267 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_pagesize;
2268 	nvme->n_prp_dma_attr.dma_attr_minxfer = nvme->n_pagesize;
2269 	nvme->n_prp_dma_attr.dma_attr_align = nvme->n_pagesize;
2270 	nvme->n_prp_dma_attr.dma_attr_seg = nvme->n_pagesize - 1;
2271 
2272 	/*
2273 	 * Reset controller if it's still in ready state.
2274 	 */
2275 	if (nvme_reset(nvme, B_FALSE) == B_FALSE) {
2276 		dev_err(nvme->n_dip, CE_WARN, "!unable to reset controller");
2277 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
2278 		nvme->n_dead = B_TRUE;
2279 		goto fail;
2280 	}
2281 
2282 	/*
2283 	 * Create the admin queue pair.
2284 	 */
2285 	if (nvme_alloc_qpair(nvme, nvme->n_admin_queue_len, &nvme->n_adminq, 0)
2286 	    != DDI_SUCCESS) {
2287 		dev_err(nvme->n_dip, CE_WARN,
2288 		    "!unable to allocate admin qpair");
2289 		goto fail;
2290 	}
2291 	nvme->n_ioq = kmem_alloc(sizeof (nvme_qpair_t *), KM_SLEEP);
2292 	nvme->n_ioq[0] = nvme->n_adminq;
2293 
2294 	nvme->n_progress |= NVME_ADMIN_QUEUE;
2295 
2296 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2297 	    "admin-queue-len", nvme->n_admin_queue_len);
2298 
2299 	aqa.b.aqa_asqs = aqa.b.aqa_acqs = nvme->n_admin_queue_len - 1;
2300 	asq = nvme->n_adminq->nq_sqdma->nd_cookie.dmac_laddress;
2301 	acq = nvme->n_adminq->nq_cqdma->nd_cookie.dmac_laddress;
2302 
2303 	ASSERT((asq & (nvme->n_pagesize - 1)) == 0);
2304 	ASSERT((acq & (nvme->n_pagesize - 1)) == 0);
2305 
2306 	nvme_put32(nvme, NVME_REG_AQA, aqa.r);
2307 	nvme_put64(nvme, NVME_REG_ASQ, asq);
2308 	nvme_put64(nvme, NVME_REG_ACQ, acq);
2309 
2310 	cc.b.cc_ams = 0;	/* use Round-Robin arbitration */
2311 	cc.b.cc_css = 0;	/* use NVM command set */
2312 	cc.b.cc_mps = nvme->n_pageshift - 12;
2313 	cc.b.cc_shn = 0;	/* no shutdown in progress */
2314 	cc.b.cc_en = 1;		/* enable controller */
2315 	cc.b.cc_iosqes = 6;	/* submission queue entry is 2^6 bytes long */
2316 	cc.b.cc_iocqes = 4;	/* completion queue entry is 2^4 bytes long */
2317 
2318 	nvme_put32(nvme, NVME_REG_CC, cc.r);
2319 
2320 	/*
2321 	 * Wait for the controller to become ready.
2322 	 */
2323 	csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2324 	if (csts.b.csts_rdy == 0) {
2325 		for (i = 0; i != nvme->n_timeout * 10; i++) {
2326 			delay(drv_usectohz(50000));
2327 			csts.r = nvme_get32(nvme, NVME_REG_CSTS);
2328 
2329 			if (csts.b.csts_cfs == 1) {
2330 				dev_err(nvme->n_dip, CE_WARN,
2331 				    "!controller fatal status at init");
2332 				ddi_fm_service_impact(nvme->n_dip,
2333 				    DDI_SERVICE_LOST);
2334 				nvme->n_dead = B_TRUE;
2335 				goto fail;
2336 			}
2337 
2338 			if (csts.b.csts_rdy == 1)
2339 				break;
2340 		}
2341 	}
2342 
2343 	if (csts.b.csts_rdy == 0) {
2344 		dev_err(nvme->n_dip, CE_WARN, "!controller not ready");
2345 		ddi_fm_service_impact(nvme->n_dip, DDI_SERVICE_LOST);
2346 		nvme->n_dead = B_TRUE;
2347 		goto fail;
2348 	}
2349 
2350 	/*
2351 	 * Assume an abort command limit of 1. We'll destroy and re-init
2352 	 * that later when we know the true abort command limit.
2353 	 */
2354 	sema_init(&nvme->n_abort_sema, 1, NULL, SEMA_DRIVER, NULL);
2355 
2356 	/*
2357 	 * Setup initial interrupt for admin queue.
2358 	 */
2359 	if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX, 1)
2360 	    != DDI_SUCCESS) &&
2361 	    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI, 1)
2362 	    != DDI_SUCCESS) &&
2363 	    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_FIXED, 1)
2364 	    != DDI_SUCCESS)) {
2365 		dev_err(nvme->n_dip, CE_WARN,
2366 		    "!failed to setup initial interrupt");
2367 		goto fail;
2368 	}
2369 
2370 	/*
2371 	 * Post an asynchronous event command to catch errors.
2372 	 */
2373 	if (nvme_async_event(nvme) != DDI_SUCCESS) {
2374 		dev_err(nvme->n_dip, CE_WARN,
2375 		    "!failed to post async event");
2376 		goto fail;
2377 	}
2378 
2379 	/*
2380 	 * Identify Controller
2381 	 */
2382 	nvme->n_idctl = nvme_identify(nvme, 0);
2383 	if (nvme->n_idctl == NULL) {
2384 		dev_err(nvme->n_dip, CE_WARN,
2385 		    "!failed to identify controller");
2386 		goto fail;
2387 	}
2388 
2389 	/*
2390 	 * Get Vendor & Product ID
2391 	 */
2392 	bcopy(nvme->n_idctl->id_model, model, sizeof (nvme->n_idctl->id_model));
2393 	model[sizeof (nvme->n_idctl->id_model)] = '\0';
2394 	sata_split_model(model, &vendor, &product);
2395 
2396 	if (vendor == NULL)
2397 		nvme->n_vendor = strdup("NVMe");
2398 	else
2399 		nvme->n_vendor = strdup(vendor);
2400 
2401 	nvme->n_product = strdup(product);
2402 
2403 	/*
2404 	 * Get controller limits.
2405 	 */
2406 	nvme->n_async_event_limit = MAX(NVME_MIN_ASYNC_EVENT_LIMIT,
2407 	    MIN(nvme->n_admin_queue_len / 10,
2408 	    MIN(nvme->n_idctl->id_aerl + 1, nvme->n_async_event_limit)));
2409 
2410 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2411 	    "async-event-limit", nvme->n_async_event_limit);
2412 
2413 	nvme->n_abort_command_limit = nvme->n_idctl->id_acl + 1;
2414 
2415 	/*
2416 	 * Reinitialize the semaphore with the true abort command limit
2417 	 * supported by the hardware. It's not necessary to disable interrupts
2418 	 * as only command aborts use the semaphore, and no commands are
2419 	 * executed or aborted while we're here.
2420 	 */
2421 	sema_destroy(&nvme->n_abort_sema);
2422 	sema_init(&nvme->n_abort_sema, nvme->n_abort_command_limit - 1, NULL,
2423 	    SEMA_DRIVER, NULL);
2424 
2425 	nvme->n_progress |= NVME_CTRL_LIMITS;
2426 
2427 	if (nvme->n_idctl->id_mdts == 0)
2428 		nvme->n_max_data_transfer_size = nvme->n_pagesize * 65536;
2429 	else
2430 		nvme->n_max_data_transfer_size =
2431 		    1ull << (nvme->n_pageshift + nvme->n_idctl->id_mdts);
2432 
2433 	nvme->n_error_log_len = nvme->n_idctl->id_elpe + 1;
2434 
2435 	/*
2436 	 * Limit n_max_data_transfer_size to what we can handle in one PRP.
2437 	 * Chained PRPs are currently unsupported.
2438 	 *
2439 	 * This is a no-op on hardware which doesn't support a transfer size
2440 	 * big enough to require chained PRPs.
2441 	 */
2442 	nvme->n_max_data_transfer_size = MIN(nvme->n_max_data_transfer_size,
2443 	    (nvme->n_pagesize / sizeof (uint64_t) * nvme->n_pagesize));
2444 
2445 	nvme->n_prp_dma_attr.dma_attr_maxxfer = nvme->n_max_data_transfer_size;
2446 
2447 	/*
2448 	 * Make sure the minimum/maximum queue entry sizes are not
2449 	 * larger/smaller than the default.
2450 	 */
2451 
2452 	if (((1 << nvme->n_idctl->id_sqes.qes_min) > sizeof (nvme_sqe_t)) ||
2453 	    ((1 << nvme->n_idctl->id_sqes.qes_max) < sizeof (nvme_sqe_t)) ||
2454 	    ((1 << nvme->n_idctl->id_cqes.qes_min) > sizeof (nvme_cqe_t)) ||
2455 	    ((1 << nvme->n_idctl->id_cqes.qes_max) < sizeof (nvme_cqe_t)))
2456 		goto fail;
2457 
2458 	/*
2459 	 * Check for the presence of a Volatile Write Cache. If present,
2460 	 * enable or disable based on the value of the property
2461 	 * volatile-write-cache-enable (default is enabled).
2462 	 */
2463 	nvme->n_write_cache_present =
2464 	    nvme->n_idctl->id_vwc.vwc_present == 0 ? B_FALSE : B_TRUE;
2465 
2466 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2467 	    "volatile-write-cache-present",
2468 	    nvme->n_write_cache_present ? 1 : 0);
2469 
2470 	if (!nvme->n_write_cache_present) {
2471 		nvme->n_write_cache_enabled = B_FALSE;
2472 	} else if (!nvme_write_cache_set(nvme, nvme->n_write_cache_enabled)) {
2473 		dev_err(nvme->n_dip, CE_WARN,
2474 		    "!failed to %sable volatile write cache",
2475 		    nvme->n_write_cache_enabled ? "en" : "dis");
2476 		/*
2477 		 * Assume the cache is (still) enabled.
2478 		 */
2479 		nvme->n_write_cache_enabled = B_TRUE;
2480 	}
2481 
2482 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip,
2483 	    "volatile-write-cache-enable",
2484 	    nvme->n_write_cache_enabled ? 1 : 0);
2485 
2486 	/*
2487 	 * Assume LBA Range Type feature is supported. If it isn't this
2488 	 * will be set to B_FALSE by nvme_get_features().
2489 	 */
2490 	nvme->n_lba_range_supported = B_TRUE;
2491 
2492 	/*
2493 	 * Check support for Autonomous Power State Transition.
2494 	 */
2495 	if (NVME_VERSION_ATLEAST(&nvme->n_version, 1, 1))
2496 		nvme->n_auto_pst_supported =
2497 		    nvme->n_idctl->id_apsta.ap_sup == 0 ? B_FALSE : B_TRUE;
2498 
2499 	/*
2500 	 * Identify Namespaces
2501 	 */
2502 	nvme->n_namespace_count = nvme->n_idctl->id_nn;
2503 	if (nvme->n_namespace_count > NVME_MINOR_MAX) {
2504 		dev_err(nvme->n_dip, CE_WARN,
2505 		    "!too many namespaces: %d, limiting to %d\n",
2506 		    nvme->n_namespace_count, NVME_MINOR_MAX);
2507 		nvme->n_namespace_count = NVME_MINOR_MAX;
2508 	}
2509 
2510 	nvme->n_ns = kmem_zalloc(sizeof (nvme_namespace_t) *
2511 	    nvme->n_namespace_count, KM_SLEEP);
2512 
2513 	for (i = 0; i != nvme->n_namespace_count; i++) {
2514 		mutex_init(&nvme->n_ns[i].ns_minor.nm_mutex, NULL, MUTEX_DRIVER,
2515 		    NULL);
2516 		if (nvme_init_ns(nvme, i + 1) != DDI_SUCCESS)
2517 			goto fail;
2518 	}
2519 
2520 	/*
2521 	 * Try to set up MSI/MSI-X interrupts.
2522 	 */
2523 	if ((nvme->n_intr_types & (DDI_INTR_TYPE_MSI | DDI_INTR_TYPE_MSIX))
2524 	    != 0) {
2525 		nvme_release_interrupts(nvme);
2526 
2527 		nqueues = MIN(UINT16_MAX, ncpus);
2528 
2529 		if ((nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSIX,
2530 		    nqueues) != DDI_SUCCESS) &&
2531 		    (nvme_setup_interrupts(nvme, DDI_INTR_TYPE_MSI,
2532 		    nqueues) != DDI_SUCCESS)) {
2533 			dev_err(nvme->n_dip, CE_WARN,
2534 			    "!failed to setup MSI/MSI-X interrupts");
2535 			goto fail;
2536 		}
2537 	}
2538 
2539 	nqueues = nvme->n_intr_cnt;
2540 
2541 	/*
2542 	 * Create I/O queue pairs.
2543 	 */
2544 	nvme->n_ioq_count = nvme_set_nqueues(nvme, nqueues);
2545 	if (nvme->n_ioq_count == 0) {
2546 		dev_err(nvme->n_dip, CE_WARN,
2547 		    "!failed to set number of I/O queues to %d", nqueues);
2548 		goto fail;
2549 	}
2550 
2551 	/*
2552 	 * Reallocate I/O queue array
2553 	 */
2554 	kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *));
2555 	nvme->n_ioq = kmem_zalloc(sizeof (nvme_qpair_t *) *
2556 	    (nvme->n_ioq_count + 1), KM_SLEEP);
2557 	nvme->n_ioq[0] = nvme->n_adminq;
2558 
2559 	/*
2560 	 * If we got less queues than we asked for we might as well give
2561 	 * some of the interrupt vectors back to the system.
2562 	 */
2563 	if (nvme->n_ioq_count < nqueues) {
2564 		nvme_release_interrupts(nvme);
2565 
2566 		if (nvme_setup_interrupts(nvme, nvme->n_intr_type,
2567 		    nvme->n_ioq_count) != DDI_SUCCESS) {
2568 			dev_err(nvme->n_dip, CE_WARN,
2569 			    "!failed to reduce number of interrupts");
2570 			goto fail;
2571 		}
2572 	}
2573 
2574 	/*
2575 	 * Alloc & register I/O queue pairs
2576 	 */
2577 	nvme->n_io_queue_len =
2578 	    MIN(nvme->n_io_queue_len, nvme->n_max_queue_entries);
2579 	(void) ddi_prop_update_int(DDI_DEV_T_NONE, nvme->n_dip, "io-queue-len",
2580 	    nvme->n_io_queue_len);
2581 
2582 	for (i = 1; i != nvme->n_ioq_count + 1; i++) {
2583 		if (nvme_alloc_qpair(nvme, nvme->n_io_queue_len,
2584 		    &nvme->n_ioq[i], i) != DDI_SUCCESS) {
2585 			dev_err(nvme->n_dip, CE_WARN,
2586 			    "!unable to allocate I/O qpair %d", i);
2587 			goto fail;
2588 		}
2589 
2590 		if (nvme_create_io_qpair(nvme, nvme->n_ioq[i], i)
2591 		    != DDI_SUCCESS) {
2592 			dev_err(nvme->n_dip, CE_WARN,
2593 			    "!unable to create I/O qpair %d", i);
2594 			goto fail;
2595 		}
2596 	}
2597 
2598 	/*
2599 	 * Post more asynchronous events commands to reduce event reporting
2600 	 * latency as suggested by the spec.
2601 	 */
2602 	for (i = 1; i != nvme->n_async_event_limit; i++) {
2603 		if (nvme_async_event(nvme) != DDI_SUCCESS) {
2604 			dev_err(nvme->n_dip, CE_WARN,
2605 			    "!failed to post async event %d", i);
2606 			goto fail;
2607 		}
2608 	}
2609 
2610 	return (DDI_SUCCESS);
2611 
2612 fail:
2613 	(void) nvme_reset(nvme, B_FALSE);
2614 	return (DDI_FAILURE);
2615 }
2616 
2617 static uint_t
2618 nvme_intr(caddr_t arg1, caddr_t arg2)
2619 {
2620 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
2621 	nvme_t *nvme = (nvme_t *)arg1;
2622 	int inum = (int)(uintptr_t)arg2;
2623 	int ccnt = 0;
2624 	int qnum;
2625 	nvme_cmd_t *cmd;
2626 
2627 	if (inum >= nvme->n_intr_cnt)
2628 		return (DDI_INTR_UNCLAIMED);
2629 
2630 	/*
2631 	 * The interrupt vector a queue uses is calculated as queue_idx %
2632 	 * intr_cnt in nvme_create_io_qpair(). Iterate through the queue array
2633 	 * in steps of n_intr_cnt to process all queues using this vector.
2634 	 */
2635 	for (qnum = inum;
2636 	    qnum < nvme->n_ioq_count + 1 && nvme->n_ioq[qnum] != NULL;
2637 	    qnum += nvme->n_intr_cnt) {
2638 		while ((cmd = nvme_retrieve_cmd(nvme, nvme->n_ioq[qnum]))) {
2639 			taskq_dispatch_ent((taskq_t *)cmd->nc_nvme->n_cmd_taskq,
2640 			    cmd->nc_callback, cmd, TQ_NOSLEEP, &cmd->nc_tqent);
2641 			ccnt++;
2642 		}
2643 	}
2644 
2645 	return (ccnt > 0 ? DDI_INTR_CLAIMED : DDI_INTR_UNCLAIMED);
2646 }
2647 
2648 static void
2649 nvme_release_interrupts(nvme_t *nvme)
2650 {
2651 	int i;
2652 
2653 	for (i = 0; i < nvme->n_intr_cnt; i++) {
2654 		if (nvme->n_inth[i] == NULL)
2655 			break;
2656 
2657 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
2658 			(void) ddi_intr_block_disable(&nvme->n_inth[i], 1);
2659 		else
2660 			(void) ddi_intr_disable(nvme->n_inth[i]);
2661 
2662 		(void) ddi_intr_remove_handler(nvme->n_inth[i]);
2663 		(void) ddi_intr_free(nvme->n_inth[i]);
2664 	}
2665 
2666 	kmem_free(nvme->n_inth, nvme->n_inth_sz);
2667 	nvme->n_inth = NULL;
2668 	nvme->n_inth_sz = 0;
2669 
2670 	nvme->n_progress &= ~NVME_INTERRUPTS;
2671 }
2672 
2673 static int
2674 nvme_setup_interrupts(nvme_t *nvme, int intr_type, int nqpairs)
2675 {
2676 	int nintrs, navail, count;
2677 	int ret;
2678 	int i;
2679 
2680 	if (nvme->n_intr_types == 0) {
2681 		ret = ddi_intr_get_supported_types(nvme->n_dip,
2682 		    &nvme->n_intr_types);
2683 		if (ret != DDI_SUCCESS) {
2684 			dev_err(nvme->n_dip, CE_WARN,
2685 			    "!%s: ddi_intr_get_supported types failed",
2686 			    __func__);
2687 			return (ret);
2688 		}
2689 #ifdef __x86
2690 		if (get_hwenv() == HW_VMWARE)
2691 			nvme->n_intr_types &= ~DDI_INTR_TYPE_MSIX;
2692 #endif
2693 	}
2694 
2695 	if ((nvme->n_intr_types & intr_type) == 0)
2696 		return (DDI_FAILURE);
2697 
2698 	ret = ddi_intr_get_nintrs(nvme->n_dip, intr_type, &nintrs);
2699 	if (ret != DDI_SUCCESS) {
2700 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_nintrs failed",
2701 		    __func__);
2702 		return (ret);
2703 	}
2704 
2705 	ret = ddi_intr_get_navail(nvme->n_dip, intr_type, &navail);
2706 	if (ret != DDI_SUCCESS) {
2707 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_navail failed",
2708 		    __func__);
2709 		return (ret);
2710 	}
2711 
2712 	/* We want at most one interrupt per queue pair. */
2713 	if (navail > nqpairs)
2714 		navail = nqpairs;
2715 
2716 	nvme->n_inth_sz = sizeof (ddi_intr_handle_t) * navail;
2717 	nvme->n_inth = kmem_zalloc(nvme->n_inth_sz, KM_SLEEP);
2718 
2719 	ret = ddi_intr_alloc(nvme->n_dip, nvme->n_inth, intr_type, 0, navail,
2720 	    &count, 0);
2721 	if (ret != DDI_SUCCESS) {
2722 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_alloc failed",
2723 		    __func__);
2724 		goto fail;
2725 	}
2726 
2727 	nvme->n_intr_cnt = count;
2728 
2729 	ret = ddi_intr_get_pri(nvme->n_inth[0], &nvme->n_intr_pri);
2730 	if (ret != DDI_SUCCESS) {
2731 		dev_err(nvme->n_dip, CE_WARN, "!%s: ddi_intr_get_pri failed",
2732 		    __func__);
2733 		goto fail;
2734 	}
2735 
2736 	for (i = 0; i < count; i++) {
2737 		ret = ddi_intr_add_handler(nvme->n_inth[i], nvme_intr,
2738 		    (void *)nvme, (void *)(uintptr_t)i);
2739 		if (ret != DDI_SUCCESS) {
2740 			dev_err(nvme->n_dip, CE_WARN,
2741 			    "!%s: ddi_intr_add_handler failed", __func__);
2742 			goto fail;
2743 		}
2744 	}
2745 
2746 	(void) ddi_intr_get_cap(nvme->n_inth[0], &nvme->n_intr_cap);
2747 
2748 	for (i = 0; i < count; i++) {
2749 		if (nvme->n_intr_cap & DDI_INTR_FLAG_BLOCK)
2750 			ret = ddi_intr_block_enable(&nvme->n_inth[i], 1);
2751 		else
2752 			ret = ddi_intr_enable(nvme->n_inth[i]);
2753 
2754 		if (ret != DDI_SUCCESS) {
2755 			dev_err(nvme->n_dip, CE_WARN,
2756 			    "!%s: enabling interrupt %d failed", __func__, i);
2757 			goto fail;
2758 		}
2759 	}
2760 
2761 	nvme->n_intr_type = intr_type;
2762 
2763 	nvme->n_progress |= NVME_INTERRUPTS;
2764 
2765 	return (DDI_SUCCESS);
2766 
2767 fail:
2768 	nvme_release_interrupts(nvme);
2769 
2770 	return (ret);
2771 }
2772 
2773 static int
2774 nvme_fm_errcb(dev_info_t *dip, ddi_fm_error_t *fm_error, const void *arg)
2775 {
2776 	_NOTE(ARGUNUSED(arg));
2777 
2778 	pci_ereport_post(dip, fm_error, NULL);
2779 	return (fm_error->fme_status);
2780 }
2781 
2782 static int
2783 nvme_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
2784 {
2785 	nvme_t *nvme;
2786 	int instance;
2787 	int nregs;
2788 	off_t regsize;
2789 	int i;
2790 	char name[32];
2791 
2792 	if (cmd != DDI_ATTACH)
2793 		return (DDI_FAILURE);
2794 
2795 	instance = ddi_get_instance(dip);
2796 
2797 	if (ddi_soft_state_zalloc(nvme_state, instance) != DDI_SUCCESS)
2798 		return (DDI_FAILURE);
2799 
2800 	nvme = ddi_get_soft_state(nvme_state, instance);
2801 	ddi_set_driver_private(dip, nvme);
2802 	nvme->n_dip = dip;
2803 
2804 	mutex_init(&nvme->n_minor.nm_mutex, NULL, MUTEX_DRIVER, NULL);
2805 
2806 	nvme->n_strict_version = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2807 	    DDI_PROP_DONTPASS, "strict-version", 1) == 1 ? B_TRUE : B_FALSE;
2808 	nvme->n_ignore_unknown_vendor_status = ddi_prop_get_int(DDI_DEV_T_ANY,
2809 	    dip, DDI_PROP_DONTPASS, "ignore-unknown-vendor-status", 0) == 1 ?
2810 	    B_TRUE : B_FALSE;
2811 	nvme->n_admin_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2812 	    DDI_PROP_DONTPASS, "admin-queue-len", NVME_DEFAULT_ADMIN_QUEUE_LEN);
2813 	nvme->n_io_queue_len = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2814 	    DDI_PROP_DONTPASS, "io-queue-len", NVME_DEFAULT_IO_QUEUE_LEN);
2815 	nvme->n_async_event_limit = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2816 	    DDI_PROP_DONTPASS, "async-event-limit",
2817 	    NVME_DEFAULT_ASYNC_EVENT_LIMIT);
2818 	nvme->n_write_cache_enabled = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2819 	    DDI_PROP_DONTPASS, "volatile-write-cache-enable", 1) != 0 ?
2820 	    B_TRUE : B_FALSE;
2821 	nvme->n_min_block_size = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2822 	    DDI_PROP_DONTPASS, "min-phys-block-size",
2823 	    NVME_DEFAULT_MIN_BLOCK_SIZE);
2824 
2825 	if (!ISP2(nvme->n_min_block_size) ||
2826 	    (nvme->n_min_block_size < NVME_DEFAULT_MIN_BLOCK_SIZE)) {
2827 		dev_err(dip, CE_WARN, "!min-phys-block-size %s, "
2828 		    "using default %d", ISP2(nvme->n_min_block_size) ?
2829 		    "too low" : "not a power of 2",
2830 		    NVME_DEFAULT_MIN_BLOCK_SIZE);
2831 		nvme->n_min_block_size = NVME_DEFAULT_MIN_BLOCK_SIZE;
2832 	}
2833 
2834 	if (nvme->n_admin_queue_len < NVME_MIN_ADMIN_QUEUE_LEN)
2835 		nvme->n_admin_queue_len = NVME_MIN_ADMIN_QUEUE_LEN;
2836 	else if (nvme->n_admin_queue_len > NVME_MAX_ADMIN_QUEUE_LEN)
2837 		nvme->n_admin_queue_len = NVME_MAX_ADMIN_QUEUE_LEN;
2838 
2839 	if (nvme->n_io_queue_len < NVME_MIN_IO_QUEUE_LEN)
2840 		nvme->n_io_queue_len = NVME_MIN_IO_QUEUE_LEN;
2841 
2842 	if (nvme->n_async_event_limit < 1)
2843 		nvme->n_async_event_limit = NVME_DEFAULT_ASYNC_EVENT_LIMIT;
2844 
2845 	nvme->n_reg_acc_attr = nvme_reg_acc_attr;
2846 	nvme->n_queue_dma_attr = nvme_queue_dma_attr;
2847 	nvme->n_prp_dma_attr = nvme_prp_dma_attr;
2848 	nvme->n_sgl_dma_attr = nvme_sgl_dma_attr;
2849 
2850 	/*
2851 	 * Setup FMA support.
2852 	 */
2853 	nvme->n_fm_cap = ddi_getprop(DDI_DEV_T_ANY, dip,
2854 	    DDI_PROP_CANSLEEP | DDI_PROP_DONTPASS, "fm-capable",
2855 	    DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
2856 	    DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
2857 
2858 	ddi_fm_init(dip, &nvme->n_fm_cap, &nvme->n_fm_ibc);
2859 
2860 	if (nvme->n_fm_cap) {
2861 		if (nvme->n_fm_cap & DDI_FM_ACCCHK_CAPABLE)
2862 			nvme->n_reg_acc_attr.devacc_attr_access =
2863 			    DDI_FLAGERR_ACC;
2864 
2865 		if (nvme->n_fm_cap & DDI_FM_DMACHK_CAPABLE) {
2866 			nvme->n_prp_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2867 			nvme->n_sgl_dma_attr.dma_attr_flags |= DDI_DMA_FLAGERR;
2868 		}
2869 
2870 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
2871 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2872 			pci_ereport_setup(dip);
2873 
2874 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
2875 			ddi_fm_handler_register(dip, nvme_fm_errcb,
2876 			    (void *)nvme);
2877 	}
2878 
2879 	nvme->n_progress |= NVME_FMA_INIT;
2880 
2881 	/*
2882 	 * The spec defines several register sets. Only the controller
2883 	 * registers (set 1) are currently used.
2884 	 */
2885 	if (ddi_dev_nregs(dip, &nregs) == DDI_FAILURE ||
2886 	    nregs < 2 ||
2887 	    ddi_dev_regsize(dip, 1, &regsize) == DDI_FAILURE)
2888 		goto fail;
2889 
2890 	if (ddi_regs_map_setup(dip, 1, &nvme->n_regs, 0, regsize,
2891 	    &nvme->n_reg_acc_attr, &nvme->n_regh) != DDI_SUCCESS) {
2892 		dev_err(dip, CE_WARN, "!failed to map regset 1");
2893 		goto fail;
2894 	}
2895 
2896 	nvme->n_progress |= NVME_REGS_MAPPED;
2897 
2898 	/*
2899 	 * Create taskq for command completion.
2900 	 */
2901 	(void) snprintf(name, sizeof (name), "%s%d_cmd_taskq",
2902 	    ddi_driver_name(dip), ddi_get_instance(dip));
2903 	nvme->n_cmd_taskq = ddi_taskq_create(dip, name, MIN(UINT16_MAX, ncpus),
2904 	    TASKQ_DEFAULTPRI, 0);
2905 	if (nvme->n_cmd_taskq == NULL) {
2906 		dev_err(dip, CE_WARN, "!failed to create cmd taskq");
2907 		goto fail;
2908 	}
2909 
2910 	/*
2911 	 * Create PRP DMA cache
2912 	 */
2913 	(void) snprintf(name, sizeof (name), "%s%d_prp_cache",
2914 	    ddi_driver_name(dip), ddi_get_instance(dip));
2915 	nvme->n_prp_cache = kmem_cache_create(name, sizeof (nvme_dma_t),
2916 	    0, nvme_prp_dma_constructor, nvme_prp_dma_destructor,
2917 	    NULL, (void *)nvme, NULL, 0);
2918 
2919 	if (nvme_init(nvme) != DDI_SUCCESS)
2920 		goto fail;
2921 
2922 	/*
2923 	 * Attach the blkdev driver for each namespace.
2924 	 */
2925 	for (i = 0; i != nvme->n_namespace_count; i++) {
2926 		if (ddi_create_minor_node(nvme->n_dip, nvme->n_ns[i].ns_name,
2927 		    S_IFCHR, NVME_MINOR(ddi_get_instance(nvme->n_dip), i + 1),
2928 		    DDI_NT_NVME_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
2929 			dev_err(dip, CE_WARN,
2930 			    "!failed to create minor node for namespace %d", i);
2931 			goto fail;
2932 		}
2933 
2934 		if (nvme->n_ns[i].ns_ignore)
2935 			continue;
2936 
2937 		nvme->n_ns[i].ns_bd_hdl = bd_alloc_handle(&nvme->n_ns[i],
2938 		    &nvme_bd_ops, &nvme->n_prp_dma_attr, KM_SLEEP);
2939 
2940 		if (nvme->n_ns[i].ns_bd_hdl == NULL) {
2941 			dev_err(dip, CE_WARN,
2942 			    "!failed to get blkdev handle for namespace %d", i);
2943 			goto fail;
2944 		}
2945 
2946 		if (bd_attach_handle(dip, nvme->n_ns[i].ns_bd_hdl)
2947 		    != DDI_SUCCESS) {
2948 			dev_err(dip, CE_WARN,
2949 			    "!failed to attach blkdev handle for namespace %d",
2950 			    i);
2951 			goto fail;
2952 		}
2953 	}
2954 
2955 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
2956 	    NVME_MINOR(ddi_get_instance(dip), 0), DDI_NT_NVME_NEXUS, 0)
2957 	    != DDI_SUCCESS) {
2958 		dev_err(dip, CE_WARN, "nvme_attach: "
2959 		    "cannot create devctl minor node");
2960 		goto fail;
2961 	}
2962 
2963 	return (DDI_SUCCESS);
2964 
2965 fail:
2966 	/* attach successful anyway so that FMA can retire the device */
2967 	if (nvme->n_dead)
2968 		return (DDI_SUCCESS);
2969 
2970 	(void) nvme_detach(dip, DDI_DETACH);
2971 
2972 	return (DDI_FAILURE);
2973 }
2974 
2975 static int
2976 nvme_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
2977 {
2978 	int instance, i;
2979 	nvme_t *nvme;
2980 
2981 	if (cmd != DDI_DETACH)
2982 		return (DDI_FAILURE);
2983 
2984 	instance = ddi_get_instance(dip);
2985 
2986 	nvme = ddi_get_soft_state(nvme_state, instance);
2987 
2988 	if (nvme == NULL)
2989 		return (DDI_FAILURE);
2990 
2991 	ddi_remove_minor_node(dip, "devctl");
2992 	mutex_destroy(&nvme->n_minor.nm_mutex);
2993 
2994 	if (nvme->n_ns) {
2995 		for (i = 0; i != nvme->n_namespace_count; i++) {
2996 			ddi_remove_minor_node(dip, nvme->n_ns[i].ns_name);
2997 			mutex_destroy(&nvme->n_ns[i].ns_minor.nm_mutex);
2998 
2999 			if (nvme->n_ns[i].ns_bd_hdl) {
3000 				(void) bd_detach_handle(
3001 				    nvme->n_ns[i].ns_bd_hdl);
3002 				bd_free_handle(nvme->n_ns[i].ns_bd_hdl);
3003 			}
3004 
3005 			if (nvme->n_ns[i].ns_idns)
3006 				kmem_free(nvme->n_ns[i].ns_idns,
3007 				    sizeof (nvme_identify_nsid_t));
3008 			if (nvme->n_ns[i].ns_devid)
3009 				strfree(nvme->n_ns[i].ns_devid);
3010 		}
3011 
3012 		kmem_free(nvme->n_ns, sizeof (nvme_namespace_t) *
3013 		    nvme->n_namespace_count);
3014 	}
3015 
3016 	if (nvme->n_progress & NVME_INTERRUPTS)
3017 		nvme_release_interrupts(nvme);
3018 
3019 	if (nvme->n_cmd_taskq)
3020 		ddi_taskq_wait(nvme->n_cmd_taskq);
3021 
3022 	if (nvme->n_ioq_count > 0) {
3023 		for (i = 1; i != nvme->n_ioq_count + 1; i++) {
3024 			if (nvme->n_ioq[i] != NULL) {
3025 				/* TODO: send destroy queue commands */
3026 				nvme_free_qpair(nvme->n_ioq[i]);
3027 			}
3028 		}
3029 
3030 		kmem_free(nvme->n_ioq, sizeof (nvme_qpair_t *) *
3031 		    (nvme->n_ioq_count + 1));
3032 	}
3033 
3034 	if (nvme->n_prp_cache != NULL) {
3035 		kmem_cache_destroy(nvme->n_prp_cache);
3036 	}
3037 
3038 	if (nvme->n_progress & NVME_REGS_MAPPED) {
3039 		nvme_shutdown(nvme, NVME_CC_SHN_NORMAL, B_FALSE);
3040 		(void) nvme_reset(nvme, B_FALSE);
3041 	}
3042 
3043 	if (nvme->n_cmd_taskq)
3044 		ddi_taskq_destroy(nvme->n_cmd_taskq);
3045 
3046 	if (nvme->n_progress & NVME_CTRL_LIMITS)
3047 		sema_destroy(&nvme->n_abort_sema);
3048 
3049 	if (nvme->n_progress & NVME_ADMIN_QUEUE)
3050 		nvme_free_qpair(nvme->n_adminq);
3051 
3052 	if (nvme->n_idctl)
3053 		kmem_free(nvme->n_idctl, NVME_IDENTIFY_BUFSIZE);
3054 
3055 	if (nvme->n_progress & NVME_REGS_MAPPED)
3056 		ddi_regs_map_free(&nvme->n_regh);
3057 
3058 	if (nvme->n_progress & NVME_FMA_INIT) {
3059 		if (DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
3060 			ddi_fm_handler_unregister(nvme->n_dip);
3061 
3062 		if (DDI_FM_EREPORT_CAP(nvme->n_fm_cap) ||
3063 		    DDI_FM_ERRCB_CAP(nvme->n_fm_cap))
3064 			pci_ereport_teardown(nvme->n_dip);
3065 
3066 		ddi_fm_fini(nvme->n_dip);
3067 	}
3068 
3069 	if (nvme->n_vendor != NULL)
3070 		strfree(nvme->n_vendor);
3071 
3072 	if (nvme->n_product != NULL)
3073 		strfree(nvme->n_product);
3074 
3075 	ddi_soft_state_free(nvme_state, instance);
3076 
3077 	return (DDI_SUCCESS);
3078 }
3079 
3080 static int
3081 nvme_quiesce(dev_info_t *dip)
3082 {
3083 	int instance;
3084 	nvme_t *nvme;
3085 
3086 	instance = ddi_get_instance(dip);
3087 
3088 	nvme = ddi_get_soft_state(nvme_state, instance);
3089 
3090 	if (nvme == NULL)
3091 		return (DDI_FAILURE);
3092 
3093 	nvme_shutdown(nvme, NVME_CC_SHN_ABRUPT, B_TRUE);
3094 
3095 	(void) nvme_reset(nvme, B_TRUE);
3096 
3097 	return (DDI_FAILURE);
3098 }
3099 
3100 static int
3101 nvme_fill_prp(nvme_cmd_t *cmd, bd_xfer_t *xfer)
3102 {
3103 	nvme_t *nvme = cmd->nc_nvme;
3104 	int nprp_page, nprp;
3105 	uint64_t *prp;
3106 
3107 	if (xfer->x_ndmac == 0)
3108 		return (DDI_FAILURE);
3109 
3110 	cmd->nc_sqe.sqe_dptr.d_prp[0] = xfer->x_dmac.dmac_laddress;
3111 	ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
3112 
3113 	if (xfer->x_ndmac == 1) {
3114 		cmd->nc_sqe.sqe_dptr.d_prp[1] = 0;
3115 		return (DDI_SUCCESS);
3116 	} else if (xfer->x_ndmac == 2) {
3117 		cmd->nc_sqe.sqe_dptr.d_prp[1] = xfer->x_dmac.dmac_laddress;
3118 		return (DDI_SUCCESS);
3119 	}
3120 
3121 	xfer->x_ndmac--;
3122 
3123 	nprp_page = nvme->n_pagesize / sizeof (uint64_t) - 1;
3124 	ASSERT(nprp_page > 0);
3125 	nprp = (xfer->x_ndmac + nprp_page - 1) / nprp_page;
3126 
3127 	/*
3128 	 * We currently don't support chained PRPs and set up our DMA
3129 	 * attributes to reflect that. If we still get an I/O request
3130 	 * that needs a chained PRP something is very wrong.
3131 	 */
3132 	VERIFY(nprp == 1);
3133 
3134 	cmd->nc_dma = kmem_cache_alloc(nvme->n_prp_cache, KM_SLEEP);
3135 	bzero(cmd->nc_dma->nd_memp, cmd->nc_dma->nd_len);
3136 
3137 	cmd->nc_sqe.sqe_dptr.d_prp[1] = cmd->nc_dma->nd_cookie.dmac_laddress;
3138 
3139 	/*LINTED: E_PTR_BAD_CAST_ALIGN*/
3140 	for (prp = (uint64_t *)cmd->nc_dma->nd_memp;
3141 	    xfer->x_ndmac > 0;
3142 	    prp++, xfer->x_ndmac--) {
3143 		*prp = xfer->x_dmac.dmac_laddress;
3144 		ddi_dma_nextcookie(xfer->x_dmah, &xfer->x_dmac);
3145 	}
3146 
3147 	(void) ddi_dma_sync(cmd->nc_dma->nd_dmah, 0, cmd->nc_dma->nd_len,
3148 	    DDI_DMA_SYNC_FORDEV);
3149 	return (DDI_SUCCESS);
3150 }
3151 
3152 static nvme_cmd_t *
3153 nvme_create_nvm_cmd(nvme_namespace_t *ns, uint8_t opc, bd_xfer_t *xfer)
3154 {
3155 	nvme_t *nvme = ns->ns_nvme;
3156 	nvme_cmd_t *cmd;
3157 
3158 	/*
3159 	 * Blkdev only sets BD_XFER_POLL when dumping, so don't sleep.
3160 	 */
3161 	cmd = nvme_alloc_cmd(nvme, (xfer->x_flags & BD_XFER_POLL) ?
3162 	    KM_NOSLEEP : KM_SLEEP);
3163 
3164 	if (cmd == NULL)
3165 		return (NULL);
3166 
3167 	cmd->nc_sqe.sqe_opc = opc;
3168 	cmd->nc_callback = nvme_bd_xfer_done;
3169 	cmd->nc_xfer = xfer;
3170 
3171 	switch (opc) {
3172 	case NVME_OPC_NVM_WRITE:
3173 	case NVME_OPC_NVM_READ:
3174 		VERIFY(xfer->x_nblks <= 0x10000);
3175 
3176 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
3177 
3178 		cmd->nc_sqe.sqe_cdw10 = xfer->x_blkno & 0xffffffffu;
3179 		cmd->nc_sqe.sqe_cdw11 = (xfer->x_blkno >> 32);
3180 		cmd->nc_sqe.sqe_cdw12 = (uint16_t)(xfer->x_nblks - 1);
3181 
3182 		if (nvme_fill_prp(cmd, xfer) != DDI_SUCCESS)
3183 			goto fail;
3184 		break;
3185 
3186 	case NVME_OPC_NVM_FLUSH:
3187 		cmd->nc_sqe.sqe_nsid = ns->ns_id;
3188 		break;
3189 
3190 	default:
3191 		goto fail;
3192 	}
3193 
3194 	return (cmd);
3195 
3196 fail:
3197 	nvme_free_cmd(cmd);
3198 	return (NULL);
3199 }
3200 
3201 static void
3202 nvme_bd_xfer_done(void *arg)
3203 {
3204 	nvme_cmd_t *cmd = arg;
3205 	bd_xfer_t *xfer = cmd->nc_xfer;
3206 	int error = 0;
3207 
3208 	error = nvme_check_cmd_status(cmd);
3209 	nvme_free_cmd(cmd);
3210 
3211 	bd_xfer_done(xfer, error);
3212 }
3213 
3214 static void
3215 nvme_bd_driveinfo(void *arg, bd_drive_t *drive)
3216 {
3217 	nvme_namespace_t *ns = arg;
3218 	nvme_t *nvme = ns->ns_nvme;
3219 
3220 	/*
3221 	 * blkdev maintains one queue size per instance (namespace),
3222 	 * but all namespace share the I/O queues.
3223 	 * TODO: need to figure out a sane default, or use per-NS I/O queues,
3224 	 * or change blkdev to handle EAGAIN
3225 	 */
3226 	drive->d_qsize = nvme->n_ioq_count * nvme->n_io_queue_len
3227 	    / nvme->n_namespace_count;
3228 
3229 	/*
3230 	 * d_maxxfer is not set, which means the value is taken from the DMA
3231 	 * attributes specified to bd_alloc_handle.
3232 	 */
3233 
3234 	drive->d_removable = B_FALSE;
3235 	drive->d_hotpluggable = B_FALSE;
3236 
3237 	bcopy(ns->ns_eui64, drive->d_eui64, sizeof (drive->d_eui64));
3238 	drive->d_target = ns->ns_id;
3239 	drive->d_lun = 0;
3240 
3241 	drive->d_model = nvme->n_idctl->id_model;
3242 	drive->d_model_len = sizeof (nvme->n_idctl->id_model);
3243 	drive->d_vendor = nvme->n_vendor;
3244 	drive->d_vendor_len = strlen(nvme->n_vendor);
3245 	drive->d_product = nvme->n_product;
3246 	drive->d_product_len = strlen(nvme->n_product);
3247 	drive->d_serial = nvme->n_idctl->id_serial;
3248 	drive->d_serial_len = sizeof (nvme->n_idctl->id_serial);
3249 	drive->d_revision = nvme->n_idctl->id_fwrev;
3250 	drive->d_revision_len = sizeof (nvme->n_idctl->id_fwrev);
3251 }
3252 
3253 static int
3254 nvme_bd_mediainfo(void *arg, bd_media_t *media)
3255 {
3256 	nvme_namespace_t *ns = arg;
3257 
3258 	media->m_nblks = ns->ns_block_count;
3259 	media->m_blksize = ns->ns_block_size;
3260 	media->m_readonly = B_FALSE;
3261 	media->m_solidstate = B_TRUE;
3262 
3263 	media->m_pblksize = ns->ns_best_block_size;
3264 
3265 	return (0);
3266 }
3267 
3268 static int
3269 nvme_bd_cmd(nvme_namespace_t *ns, bd_xfer_t *xfer, uint8_t opc)
3270 {
3271 	nvme_t *nvme = ns->ns_nvme;
3272 	nvme_cmd_t *cmd;
3273 
3274 	if (nvme->n_dead)
3275 		return (EIO);
3276 
3277 	/* No polling for now */
3278 	if (xfer->x_flags & BD_XFER_POLL)
3279 		return (EIO);
3280 
3281 	cmd = nvme_create_nvm_cmd(ns, opc, xfer);
3282 	if (cmd == NULL)
3283 		return (ENOMEM);
3284 
3285 	cmd->nc_sqid = (CPU->cpu_id % nvme->n_ioq_count) + 1;
3286 	ASSERT(cmd->nc_sqid <= nvme->n_ioq_count);
3287 
3288 	if (nvme_submit_cmd(nvme->n_ioq[cmd->nc_sqid], cmd)
3289 	    != DDI_SUCCESS)
3290 		return (EAGAIN);
3291 
3292 	return (0);
3293 }
3294 
3295 static int
3296 nvme_bd_read(void *arg, bd_xfer_t *xfer)
3297 {
3298 	nvme_namespace_t *ns = arg;
3299 
3300 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_READ));
3301 }
3302 
3303 static int
3304 nvme_bd_write(void *arg, bd_xfer_t *xfer)
3305 {
3306 	nvme_namespace_t *ns = arg;
3307 
3308 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_WRITE));
3309 }
3310 
3311 static int
3312 nvme_bd_sync(void *arg, bd_xfer_t *xfer)
3313 {
3314 	nvme_namespace_t *ns = arg;
3315 
3316 	if (ns->ns_nvme->n_dead)
3317 		return (EIO);
3318 
3319 	/*
3320 	 * If the volatile write cache is not present or not enabled the FLUSH
3321 	 * command is a no-op, so we can take a shortcut here.
3322 	 */
3323 	if (!ns->ns_nvme->n_write_cache_present) {
3324 		bd_xfer_done(xfer, ENOTSUP);
3325 		return (0);
3326 	}
3327 
3328 	if (!ns->ns_nvme->n_write_cache_enabled) {
3329 		bd_xfer_done(xfer, 0);
3330 		return (0);
3331 	}
3332 
3333 	return (nvme_bd_cmd(ns, xfer, NVME_OPC_NVM_FLUSH));
3334 }
3335 
3336 static int
3337 nvme_bd_devid(void *arg, dev_info_t *devinfo, ddi_devid_t *devid)
3338 {
3339 	nvme_namespace_t *ns = arg;
3340 
3341 	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
3342 	if (*(uint64_t *)ns->ns_eui64 != 0) {
3343 		return (ddi_devid_init(devinfo, DEVID_SCSI3_WWN,
3344 		    sizeof (ns->ns_eui64), ns->ns_eui64, devid));
3345 	} else {
3346 		return (ddi_devid_init(devinfo, DEVID_ENCAP,
3347 		    strlen(ns->ns_devid), ns->ns_devid, devid));
3348 	}
3349 }
3350 
3351 static int
3352 nvme_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
3353 {
3354 #ifndef __lock_lint
3355 	_NOTE(ARGUNUSED(cred_p));
3356 #endif
3357 	minor_t minor = getminor(*devp);
3358 	nvme_t *nvme = ddi_get_soft_state(nvme_state, NVME_MINOR_INST(minor));
3359 	int nsid = NVME_MINOR_NSID(minor);
3360 	nvme_minor_state_t *nm;
3361 	int rv = 0;
3362 
3363 	if (otyp != OTYP_CHR)
3364 		return (EINVAL);
3365 
3366 	if (nvme == NULL)
3367 		return (ENXIO);
3368 
3369 	if (nsid > nvme->n_namespace_count)
3370 		return (ENXIO);
3371 
3372 	nm = nsid == 0 ? &nvme->n_minor : &nvme->n_ns[nsid - 1].ns_minor;
3373 
3374 	mutex_enter(&nm->nm_mutex);
3375 	if (nm->nm_oexcl) {
3376 		rv = EBUSY;
3377 		goto out;
3378 	}
3379 
3380 	if (flag & FEXCL) {
3381 		if (nm->nm_ocnt != 0) {
3382 			rv = EBUSY;
3383 			goto out;
3384 		}
3385 		nm->nm_oexcl = B_TRUE;
3386 	}
3387 
3388 	nm->nm_ocnt++;
3389 
3390 out:
3391 	mutex_exit(&nm->nm_mutex);
3392 	return (rv);
3393 
3394 }
3395 
3396 static int
3397 nvme_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3398 {
3399 #ifndef __lock_lint
3400 	_NOTE(ARGUNUSED(cred_p));
3401 	_NOTE(ARGUNUSED(flag));
3402 #endif
3403 	minor_t minor = getminor(dev);
3404 	nvme_t *nvme = ddi_get_soft_state(nvme_state, NVME_MINOR_INST(minor));
3405 	int nsid = NVME_MINOR_NSID(minor);
3406 	nvme_minor_state_t *nm;
3407 
3408 	if (otyp != OTYP_CHR)
3409 		return (ENXIO);
3410 
3411 	if (nvme == NULL)
3412 		return (ENXIO);
3413 
3414 	if (nsid > nvme->n_namespace_count)
3415 		return (ENXIO);
3416 
3417 	nm = nsid == 0 ? &nvme->n_minor : &nvme->n_ns[nsid - 1].ns_minor;
3418 
3419 	mutex_enter(&nm->nm_mutex);
3420 	if (nm->nm_oexcl)
3421 		nm->nm_oexcl = B_FALSE;
3422 
3423 	ASSERT(nm->nm_ocnt > 0);
3424 	nm->nm_ocnt--;
3425 	mutex_exit(&nm->nm_mutex);
3426 
3427 	return (0);
3428 }
3429 
3430 static int
3431 nvme_ioctl_identify(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3432     cred_t *cred_p)
3433 {
3434 	_NOTE(ARGUNUSED(cred_p));
3435 	int rv = 0;
3436 	void *idctl;
3437 
3438 	if ((mode & FREAD) == 0)
3439 		return (EPERM);
3440 
3441 	if (nioc->n_len < NVME_IDENTIFY_BUFSIZE)
3442 		return (EINVAL);
3443 
3444 	idctl = nvme_identify(nvme, nsid);
3445 	if (idctl == NULL)
3446 		return (EIO);
3447 
3448 	if (ddi_copyout(idctl, (void *)nioc->n_buf, NVME_IDENTIFY_BUFSIZE, mode)
3449 	    != 0)
3450 		rv = EFAULT;
3451 
3452 	kmem_free(idctl, NVME_IDENTIFY_BUFSIZE);
3453 
3454 	return (rv);
3455 }
3456 
3457 static int
3458 nvme_ioctl_capabilities(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc,
3459     int mode, cred_t *cred_p)
3460 {
3461 	_NOTE(ARGUNUSED(nsid, cred_p));
3462 	int rv = 0;
3463 	nvme_reg_cap_t cap = { 0 };
3464 	nvme_capabilities_t nc;
3465 
3466 	if ((mode & FREAD) == 0)
3467 		return (EPERM);
3468 
3469 	if (nioc->n_len < sizeof (nc))
3470 		return (EINVAL);
3471 
3472 	cap.r = nvme_get64(nvme, NVME_REG_CAP);
3473 
3474 	/*
3475 	 * The MPSMIN and MPSMAX fields in the CAP register use 0 to
3476 	 * specify the base page size of 4k (1<<12), so add 12 here to
3477 	 * get the real page size value.
3478 	 */
3479 	nc.mpsmax = 1 << (12 + cap.b.cap_mpsmax);
3480 	nc.mpsmin = 1 << (12 + cap.b.cap_mpsmin);
3481 
3482 	if (ddi_copyout(&nc, (void *)nioc->n_buf, sizeof (nc), mode) != 0)
3483 		rv = EFAULT;
3484 
3485 	return (rv);
3486 }
3487 
3488 static int
3489 nvme_ioctl_get_logpage(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc,
3490     int mode, cred_t *cred_p)
3491 {
3492 	_NOTE(ARGUNUSED(cred_p));
3493 	void *log = NULL;
3494 	size_t bufsize = 0;
3495 	int rv = 0;
3496 
3497 	if ((mode & FREAD) == 0)
3498 		return (EPERM);
3499 
3500 	switch (nioc->n_arg) {
3501 	case NVME_LOGPAGE_ERROR:
3502 		if (nsid != 0)
3503 			return (EINVAL);
3504 		break;
3505 	case NVME_LOGPAGE_HEALTH:
3506 		if (nsid != 0 && nvme->n_idctl->id_lpa.lp_smart == 0)
3507 			return (EINVAL);
3508 
3509 		if (nsid == 0)
3510 			nsid = (uint32_t)-1;
3511 
3512 		break;
3513 	case NVME_LOGPAGE_FWSLOT:
3514 		if (nsid != 0)
3515 			return (EINVAL);
3516 		break;
3517 	default:
3518 		return (EINVAL);
3519 	}
3520 
3521 	if (nvme_get_logpage(nvme, &log, &bufsize, nioc->n_arg, nsid)
3522 	    != DDI_SUCCESS)
3523 		return (EIO);
3524 
3525 	if (nioc->n_len < bufsize) {
3526 		kmem_free(log, bufsize);
3527 		return (EINVAL);
3528 	}
3529 
3530 	if (ddi_copyout(log, (void *)nioc->n_buf, bufsize, mode) != 0)
3531 		rv = EFAULT;
3532 
3533 	nioc->n_len = bufsize;
3534 	kmem_free(log, bufsize);
3535 
3536 	return (rv);
3537 }
3538 
3539 static int
3540 nvme_ioctl_get_features(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc,
3541     int mode, cred_t *cred_p)
3542 {
3543 	_NOTE(ARGUNUSED(cred_p));
3544 	void *buf = NULL;
3545 	size_t bufsize = 0;
3546 	uint32_t res = 0;
3547 	uint8_t feature;
3548 	int rv = 0;
3549 
3550 	if ((mode & FREAD) == 0)
3551 		return (EPERM);
3552 
3553 	if ((nioc->n_arg >> 32) > 0xff)
3554 		return (EINVAL);
3555 
3556 	feature = (uint8_t)(nioc->n_arg >> 32);
3557 
3558 	switch (feature) {
3559 	case NVME_FEAT_ARBITRATION:
3560 	case NVME_FEAT_POWER_MGMT:
3561 	case NVME_FEAT_TEMPERATURE:
3562 	case NVME_FEAT_ERROR:
3563 	case NVME_FEAT_NQUEUES:
3564 	case NVME_FEAT_INTR_COAL:
3565 	case NVME_FEAT_WRITE_ATOM:
3566 	case NVME_FEAT_ASYNC_EVENT:
3567 	case NVME_FEAT_PROGRESS:
3568 		if (nsid != 0)
3569 			return (EINVAL);
3570 		break;
3571 
3572 	case NVME_FEAT_INTR_VECT:
3573 		if (nsid != 0)
3574 			return (EINVAL);
3575 
3576 		res = nioc->n_arg & 0xffffffffUL;
3577 		if (res >= nvme->n_intr_cnt)
3578 			return (EINVAL);
3579 		break;
3580 
3581 	case NVME_FEAT_LBA_RANGE:
3582 		if (nvme->n_lba_range_supported == B_FALSE)
3583 			return (EINVAL);
3584 
3585 		if (nsid == 0 ||
3586 		    nsid > nvme->n_namespace_count)
3587 			return (EINVAL);
3588 
3589 		break;
3590 
3591 	case NVME_FEAT_WRITE_CACHE:
3592 		if (nsid != 0)
3593 			return (EINVAL);
3594 
3595 		if (!nvme->n_write_cache_present)
3596 			return (EINVAL);
3597 
3598 		break;
3599 
3600 	case NVME_FEAT_AUTO_PST:
3601 		if (nsid != 0)
3602 			return (EINVAL);
3603 
3604 		if (!nvme->n_auto_pst_supported)
3605 			return (EINVAL);
3606 
3607 		break;
3608 
3609 	default:
3610 		return (EINVAL);
3611 	}
3612 
3613 	if (nvme_get_features(nvme, nsid, feature, &res, &buf, &bufsize) ==
3614 	    B_FALSE)
3615 		return (EIO);
3616 
3617 	if (nioc->n_len < bufsize) {
3618 		kmem_free(buf, bufsize);
3619 		return (EINVAL);
3620 	}
3621 
3622 	if (buf && ddi_copyout(buf, (void*)nioc->n_buf, bufsize, mode) != 0)
3623 		rv = EFAULT;
3624 
3625 	kmem_free(buf, bufsize);
3626 	nioc->n_arg = res;
3627 	nioc->n_len = bufsize;
3628 
3629 	return (rv);
3630 }
3631 
3632 static int
3633 nvme_ioctl_intr_cnt(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3634     cred_t *cred_p)
3635 {
3636 	_NOTE(ARGUNUSED(nsid, mode, cred_p));
3637 
3638 	if ((mode & FREAD) == 0)
3639 		return (EPERM);
3640 
3641 	nioc->n_arg = nvme->n_intr_cnt;
3642 	return (0);
3643 }
3644 
3645 static int
3646 nvme_ioctl_version(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3647     cred_t *cred_p)
3648 {
3649 	_NOTE(ARGUNUSED(nsid, cred_p));
3650 	int rv = 0;
3651 
3652 	if ((mode & FREAD) == 0)
3653 		return (EPERM);
3654 
3655 	if (nioc->n_len < sizeof (nvme->n_version))
3656 		return (ENOMEM);
3657 
3658 	if (ddi_copyout(&nvme->n_version, (void *)nioc->n_buf,
3659 	    sizeof (nvme->n_version), mode) != 0)
3660 		rv = EFAULT;
3661 
3662 	return (rv);
3663 }
3664 
3665 static int
3666 nvme_ioctl_format(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3667     cred_t *cred_p)
3668 {
3669 	_NOTE(ARGUNUSED(mode));
3670 	nvme_format_nvm_t frmt = { 0 };
3671 	int c_nsid = nsid != 0 ? nsid - 1 : 0;
3672 
3673 	if ((mode & FWRITE) == 0 || secpolicy_sys_config(cred_p, B_FALSE) != 0)
3674 		return (EPERM);
3675 
3676 	frmt.r = nioc->n_arg & 0xffffffff;
3677 
3678 	/*
3679 	 * Check whether the FORMAT NVM command is supported.
3680 	 */
3681 	if (nvme->n_idctl->id_oacs.oa_format == 0)
3682 		return (EINVAL);
3683 
3684 	/*
3685 	 * Don't allow format or secure erase of individual namespace if that
3686 	 * would cause a format or secure erase of all namespaces.
3687 	 */
3688 	if (nsid != 0 && nvme->n_idctl->id_fna.fn_format != 0)
3689 		return (EINVAL);
3690 
3691 	if (nsid != 0 && frmt.b.fm_ses != NVME_FRMT_SES_NONE &&
3692 	    nvme->n_idctl->id_fna.fn_sec_erase != 0)
3693 		return (EINVAL);
3694 
3695 	/*
3696 	 * Don't allow formatting with Protection Information.
3697 	 */
3698 	if (frmt.b.fm_pi != 0 || frmt.b.fm_pil != 0 || frmt.b.fm_ms != 0)
3699 		return (EINVAL);
3700 
3701 	/*
3702 	 * Don't allow formatting using an illegal LBA format, or any LBA format
3703 	 * that uses metadata.
3704 	 */
3705 	if (frmt.b.fm_lbaf > nvme->n_ns[c_nsid].ns_idns->id_nlbaf ||
3706 	    nvme->n_ns[c_nsid].ns_idns->id_lbaf[frmt.b.fm_lbaf].lbaf_ms != 0)
3707 		return (EINVAL);
3708 
3709 	/*
3710 	 * Don't allow formatting using an illegal Secure Erase setting.
3711 	 */
3712 	if (frmt.b.fm_ses > NVME_FRMT_MAX_SES ||
3713 	    (frmt.b.fm_ses == NVME_FRMT_SES_CRYPTO &&
3714 	    nvme->n_idctl->id_fna.fn_crypt_erase == 0))
3715 		return (EINVAL);
3716 
3717 	if (nsid == 0)
3718 		nsid = (uint32_t)-1;
3719 
3720 	return (nvme_format_nvm(nvme, nsid, frmt.b.fm_lbaf, B_FALSE, 0, B_FALSE,
3721 	    frmt.b.fm_ses));
3722 }
3723 
3724 static int
3725 nvme_ioctl_detach(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3726     cred_t *cred_p)
3727 {
3728 	_NOTE(ARGUNUSED(nioc, mode));
3729 	int rv = 0;
3730 
3731 	if ((mode & FWRITE) == 0 || secpolicy_sys_config(cred_p, B_FALSE) != 0)
3732 		return (EPERM);
3733 
3734 	if (nsid == 0)
3735 		return (EINVAL);
3736 
3737 	rv = bd_detach_handle(nvme->n_ns[nsid - 1].ns_bd_hdl);
3738 	if (rv != DDI_SUCCESS)
3739 		rv = EBUSY;
3740 
3741 	return (rv);
3742 }
3743 
3744 static int
3745 nvme_ioctl_attach(nvme_t *nvme, int nsid, nvme_ioctl_t *nioc, int mode,
3746     cred_t *cred_p)
3747 {
3748 	_NOTE(ARGUNUSED(nioc, mode));
3749 	nvme_identify_nsid_t *idns;
3750 	int rv = 0;
3751 
3752 	if ((mode & FWRITE) == 0 || secpolicy_sys_config(cred_p, B_FALSE) != 0)
3753 		return (EPERM);
3754 
3755 	if (nsid == 0)
3756 		return (EINVAL);
3757 
3758 	/*
3759 	 * Identify namespace again, free old identify data.
3760 	 */
3761 	idns = nvme->n_ns[nsid - 1].ns_idns;
3762 	if (nvme_init_ns(nvme, nsid) != DDI_SUCCESS)
3763 		return (EIO);
3764 
3765 	kmem_free(idns, sizeof (nvme_identify_nsid_t));
3766 
3767 	rv = bd_attach_handle(nvme->n_dip, nvme->n_ns[nsid - 1].ns_bd_hdl);
3768 	if (rv != DDI_SUCCESS)
3769 		rv = EBUSY;
3770 
3771 	return (rv);
3772 }
3773 
3774 static int
3775 nvme_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *cred_p,
3776     int *rval_p)
3777 {
3778 #ifndef __lock_lint
3779 	_NOTE(ARGUNUSED(rval_p));
3780 #endif
3781 	minor_t minor = getminor(dev);
3782 	nvme_t *nvme = ddi_get_soft_state(nvme_state, NVME_MINOR_INST(minor));
3783 	int nsid = NVME_MINOR_NSID(minor);
3784 	int rv = 0;
3785 	nvme_ioctl_t nioc;
3786 
3787 	int (*nvme_ioctl[])(nvme_t *, int, nvme_ioctl_t *, int, cred_t *) = {
3788 		NULL,
3789 		nvme_ioctl_identify,
3790 		nvme_ioctl_identify,
3791 		nvme_ioctl_capabilities,
3792 		nvme_ioctl_get_logpage,
3793 		nvme_ioctl_get_features,
3794 		nvme_ioctl_intr_cnt,
3795 		nvme_ioctl_version,
3796 		nvme_ioctl_format,
3797 		nvme_ioctl_detach,
3798 		nvme_ioctl_attach
3799 	};
3800 
3801 	if (nvme == NULL)
3802 		return (ENXIO);
3803 
3804 	if (nsid > nvme->n_namespace_count)
3805 		return (ENXIO);
3806 
3807 	if (IS_DEVCTL(cmd))
3808 		return (ndi_devctl_ioctl(nvme->n_dip, cmd, arg, mode, 0));
3809 
3810 #ifdef _MULTI_DATAMODEL
3811 	switch (ddi_model_convert_from(mode & FMODELS)) {
3812 	case DDI_MODEL_ILP32: {
3813 		nvme_ioctl32_t nioc32;
3814 		if (ddi_copyin((void*)arg, &nioc32, sizeof (nvme_ioctl32_t),
3815 		    mode) != 0)
3816 			return (EFAULT);
3817 		nioc.n_len = nioc32.n_len;
3818 		nioc.n_buf = nioc32.n_buf;
3819 		nioc.n_arg = nioc32.n_arg;
3820 		break;
3821 	}
3822 	case DDI_MODEL_NONE:
3823 #endif
3824 		if (ddi_copyin((void*)arg, &nioc, sizeof (nvme_ioctl_t), mode)
3825 		    != 0)
3826 			return (EFAULT);
3827 #ifdef _MULTI_DATAMODEL
3828 		break;
3829 	}
3830 #endif
3831 
3832 	if (cmd == NVME_IOC_IDENTIFY_CTRL) {
3833 		/*
3834 		 * This makes NVME_IOC_IDENTIFY_CTRL work the same on devctl and
3835 		 * attachment point nodes.
3836 		 */
3837 		nsid = 0;
3838 	} else if (cmd == NVME_IOC_IDENTIFY_NSID && nsid == 0) {
3839 		/*
3840 		 * This makes NVME_IOC_IDENTIFY_NSID work on a devctl node, it
3841 		 * will always return identify data for namespace 1.
3842 		 */
3843 		nsid = 1;
3844 	}
3845 
3846 	if (IS_NVME_IOC(cmd) && nvme_ioctl[NVME_IOC_CMD(cmd)] != NULL)
3847 		rv = nvme_ioctl[NVME_IOC_CMD(cmd)](nvme, nsid, &nioc, mode,
3848 		    cred_p);
3849 	else
3850 		rv = EINVAL;
3851 
3852 #ifdef _MULTI_DATAMODEL
3853 	switch (ddi_model_convert_from(mode & FMODELS)) {
3854 	case DDI_MODEL_ILP32: {
3855 		nvme_ioctl32_t nioc32;
3856 
3857 		nioc32.n_len = (size32_t)nioc.n_len;
3858 		nioc32.n_buf = (uintptr32_t)nioc.n_buf;
3859 		nioc32.n_arg = nioc.n_arg;
3860 
3861 		if (ddi_copyout(&nioc32, (void *)arg, sizeof (nvme_ioctl32_t),
3862 		    mode) != 0)
3863 			return (EFAULT);
3864 		break;
3865 	}
3866 	case DDI_MODEL_NONE:
3867 #endif
3868 		if (ddi_copyout(&nioc, (void *)arg, sizeof (nvme_ioctl_t), mode)
3869 		    != 0)
3870 			return (EFAULT);
3871 #ifdef _MULTI_DATAMODEL
3872 		break;
3873 	}
3874 #endif
3875 
3876 	return (rv);
3877 }
3878