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