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