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