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