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